int BranchProbabilities::CheckIntegerHeuristic() { // Heuristic fails if the last instruction is not a conditional branch BranchInst *BI = dyn_cast<BranchInst>(_TI); if ((!BI) || (BI->isUnconditional())) return -1; // All integer comparisons are done with the icmp instruction ICmpInst *icmp = dyn_cast<ICmpInst>(BI->getCondition()); if (!icmp) return -1; Value *v[2]; v[0] = icmp->getOperand(0); v[1] = icmp->getOperand(1); // If neither is a constant, nothing to do if (!isa<ConstantInt>(v[0]) && !isa<ConstantInt>(v[1])) return -1; // If we're dealing with something other than ints, nothing to do if (!isa<IntegerType>(v[0]->getType())) return -1; // Get comparison ICmpInst::Predicate pred = icmp->getPredicate(); // Eq and Not Eq are easy cases if (pred == ICmpInst::ICMP_EQ) return 1; else if (pred == ICmpInst::ICMP_NE) return 0; ConstantInt *CI = dyn_cast<ConstantInt>(v[1]); // If the right side isn't a constant, swap the predicate so we can pretend if (!CI) { pred = icmp->getSwappedPredicate(); CI = cast<ConstantInt>(v[0]); } // Choose the appropriate branch depending on the const val and predicate if (CI->isZero()) { switch (pred) { case ICmpInst::ICMP_UGE: assert("UGE zero always returns true"); return -1; case ICmpInst::ICMP_ULT: assert("ULT zero always returns false"); return -1; case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: return 0; case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: return 1; default: return -1; } } else if (CI->isOne()) { switch (pred) { case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_SGE: return 0; case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_SLT: return 1; default: return -1; } } else if (CI->isAllOnesValue()) { switch (pred) { case ICmpInst::ICMP_SGT: return 0; case ICmpInst::ICMP_SLE: return 1; default: return -1; } } return -1; }