14 #define DEBUG_TYPE "simplifycfg"
51 using namespace PatternMatch;
55 cl::desc(
"Control the amount of phi node folding to perform (default = 1)"));
59 cl::desc(
"Duplicate return instructions into unconditional branches"));
63 cl::desc(
"Sink common instructions down to the end block"));
67 cl::desc(
"Hoist conditional stores if an unconditional store preceeds"));
69 STATISTIC(NumBitMaps,
"Number of switch instructions turned into bitmaps");
70 STATISTIC(NumLookupTables,
"Number of switch instructions turned into lookup tables");
71 STATISTIC(NumSinkCommons,
"Number of common instructions sunk down to the end block");
72 STATISTIC(NumSpeculations,
"Number of speculative executed instructions");
76 struct ValueEqualityComparisonCase {
81 : Value(Value), Dest(Dest) {}
83 bool operator<(ValueEqualityComparisonCase RHS)
const {
85 return Value < RHS.Value;
91 class SimplifyCFGOpt {
96 std::vector<ValueEqualityComparisonCase> &Cases);
97 bool SimplifyEqualityComparisonWithOnlyPredecessor(
TerminatorInst *TI,
113 : TTI(TTI), TD(TD) {}
122 if (SI1 == SI2)
return false;
134 isa<PHINode>(BBI); ++BBI) {
135 PHINode *PN = cast<PHINode>(BBI);
153 if (SI1 == SI2)
return false;
162 if (!Ci2)
return false;
163 if (!(Cond->
getOperand(0) == Ci2->getOperand(0) &&
165 !(Cond->
getOperand(0) == Ci2->getOperand(1) &&
175 isa<PHINode>(BBI); ++BBI) {
176 PHINode *PN = cast<PHINode>(BBI);
191 if (!isa<PHINode>(Succ->
begin()))
return;
204 "Instruction is not safe to speculatively execute!");
209 case Instruction::GetElementPtr:
211 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
215 case Instruction::Add:
216 case Instruction::Sub:
220 case Instruction::Shl:
221 case Instruction::LShr:
222 case Instruction::AShr:
223 case Instruction::ICmp:
224 case Instruction::Trunc:
225 case Instruction::ZExt:
226 case Instruction::SExt:
254 unsigned &CostRemaining) {
268 if (PBB == BB)
return false;
279 if (AggressiveInsts == 0)
return false;
282 if (AggressiveInsts->
count(I))
return true;
292 if (Cost > CostRemaining)
295 CostRemaining -= Cost;
303 AggressiveInsts->
insert(I);
320 if (isa<ConstantPointerNull>(V))
325 if (CE->getOpcode() == Instruction::IntToPtr)
326 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
331 return cast<ConstantInt>
345 if (I == 0)
return 0;
348 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
356 if (
match(ICI->getOperand(0),
406 unsigned NumValsBeforeLHS = Vals.size();
407 unsigned UsedICmpsBeforeLHS = UsedICmps;
410 unsigned NumVals = Vals.size();
411 unsigned UsedICmpsBeforeRHS = UsedICmps;
416 Vals.resize(NumVals);
417 UsedICmps = UsedICmpsBeforeRHS;
422 if (Extra == 0 || Extra == I->
getOperand(1)) {
427 Vals.resize(NumValsBeforeLHS);
428 UsedICmps = UsedICmpsBeforeLHS;
434 if (Extra == 0 || Extra == I->
getOperand(0)) {
435 Value *OldExtra = Extra;
440 assert(Vals.size() == NumValsBeforeLHS);
449 if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
451 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
452 if (BI->isConditional())
453 Cond = dyn_cast<Instruction>(BI->getCondition());
466 if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
469 if (SI->getNumSuccessors()*std::distance(
pred_begin(SI->getParent()),
471 CV = SI->getCondition();
472 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI))
473 if (BI->isConditional() && BI->getCondition()->hasOneUse())
474 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
476 CV = ICI->getOperand(0);
481 Value *Ptr = PTII->getPointerOperand();
482 if (PTII->getType() ==
TD->getIntPtrType(Ptr->
getType()))
493 std::vector<ValueEqualityComparisonCase>
495 if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
496 Cases.reserve(SI->getNumCases());
498 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
499 i.getCaseSuccessor()));
500 return SI->getDefaultDest();
506 Cases.push_back(ValueEqualityComparisonCase(
GetConstantInt(ICI->getOperand(1),
516 std::vector<ValueEqualityComparisonCase> &Cases) {
517 Cases.erase(
std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
524 std::vector<ValueEqualityComparisonCase > &C2) {
525 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *
V2 = &C2;
528 if (V1->size() > V2->size())
531 if (V1->size() == 0)
return false;
532 if (V1->size() == 1) {
535 for (
unsigned i = 0, e = V2->size(); i != e; ++i)
536 if (TheVal == (*V2)[i].
Value)
543 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
544 while (i1 != e1 && i2 != e2) {
547 if ((*V1)[i1].Value < (*V2)[i2].Value)
561 bool SimplifyCFGOpt::
566 if (!PredVal)
return false;
568 Value *ThisVal = isValueEqualityComparison(TI);
569 assert(ThisVal &&
"This isn't a value comparison!!");
570 if (ThisVal != PredVal)
return false;
576 std::vector<ValueEqualityComparisonCase> PredCases;
582 std::vector<ValueEqualityComparisonCase> ThisCases;
583 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
595 if (isa<BranchInst>(TI)) {
598 assert(ThisCases.size() == 1 &&
"Branch can only have one case!");
604 ThisCases[0].Dest->removePredecessor(TI->
getParent());
607 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI <<
"\n");
616 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
617 DeadCases.
insert(PredCases[i].Value);
620 <<
"Through successor TI: " << *TI);
635 if (DeadCases.count(i.getCaseValue())) {
637 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
640 i.getCaseSuccessor()->removePredecessor(TI->
getParent());
644 if (HasWeight && Weights.size() >= 2)
647 createBranchWeights(Weights));
649 DEBUG(
dbgs() <<
"Leaving: " << *TI <<
"\n");
657 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
658 if (PredCases[i].Dest == TIBB) {
661 TIV = PredCases[i].
Value;
663 assert(TIV &&
"No edge from pred to succ?");
668 for (
unsigned i = 0, e = ThisCases.size(); i != e; ++i)
669 if (ThisCases[i].
Value == TIV) {
670 TheRealDest = ThisCases[i].Dest;
675 if (TheRealDest == 0) TheRealDest = ThisDef;
680 if (*SI != CheckEdge)
690 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI <<
"\n");
700 struct ConstantIntOrdering {
722 return MDS->getString().equals(
"branch_weights");
743 if (
BranchInst* BI = dyn_cast<BranchInst>(TI)) {
744 assert(Weights.
size() == 2);
755 for (
unsigned i = 0; i < Weights.
size(); ++i)
756 if (Weights[i] > UINT_MAX) {
764 for (
unsigned i = 0; i < Weights.
size(); ++i)
772 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(
TerminatorInst *TI,
775 Value *CV = isValueEqualityComparison(TI);
776 assert(CV &&
"Not a comparison?");
777 bool Changed =
false;
780 while (!Preds.empty()) {
785 Value *PCV = isValueEqualityComparison(PTI);
789 std::vector<ValueEqualityComparisonCase> BBCases;
790 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
792 std::vector<ValueEqualityComparisonCase> PredCases;
793 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
805 if (PredHasWeights) {
808 if (Weights.
size() != 1 + PredCases.size())
809 PredHasWeights = SuccHasWeights =
false;
810 }
else if (SuccHasWeights)
814 Weights.
assign(1 + PredCases.size(), 1);
817 if (SuccHasWeights) {
820 if (SuccWeights.
size() != 1 + BBCases.size())
821 PredHasWeights = SuccHasWeights =
false;
822 }
else if (PredHasWeights)
823 SuccWeights.
assign(1 + BBCases.size(), 1);
825 if (PredDefault == BB) {
828 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
829 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
830 if (PredCases[i].Dest != BB)
831 PTIHandled.insert(PredCases[i].
Value);
834 std::swap(PredCases[i], PredCases.back());
836 if (PredHasWeights || SuccHasWeights) {
838 Weights[0] += Weights[i+1];
843 PredCases.pop_back();
848 if (PredDefault != BBDefault) {
850 PredDefault = BBDefault;
854 unsigned CasesFromPred = Weights.
size();
855 uint64_t ValidTotalSuccWeight = 0;
856 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
857 if (!PTIHandled.count(BBCases[i].Value) &&
858 BBCases[i].Dest != BBDefault) {
859 PredCases.push_back(BBCases[i]);
860 NewSuccessors.
push_back(BBCases[i].Dest);
861 if (SuccHasWeights || PredHasWeights) {
865 Weights.
push_back(Weights[0] * SuccWeights[i+1]);
866 ValidTotalSuccWeight += SuccWeights[i+1];
870 if (SuccHasWeights || PredHasWeights) {
871 ValidTotalSuccWeight += SuccWeights[0];
873 for (
unsigned i = 1; i < CasesFromPred; ++i)
874 Weights[i] *= ValidTotalSuccWeight;
876 Weights[0] *= SuccWeights[0];
882 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
883 std::map<ConstantInt*, uint64_t> WeightsForHandled;
884 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
885 if (PredCases[i].Dest == BB) {
886 PTIHandled.
insert(PredCases[i].Value);
888 if (PredHasWeights || SuccHasWeights) {
889 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
894 std::swap(PredCases[i], PredCases.back());
895 PredCases.pop_back();
901 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
902 if (PTIHandled.count(BBCases[i].Value)) {
904 if (PredHasWeights || SuccHasWeights)
905 Weights.
push_back(WeightsForHandled[BBCases[i].Value]);
906 PredCases.push_back(BBCases[i]);
907 NewSuccessors.
push_back(BBCases[i].Dest);
908 PTIHandled.erase(BBCases[i].Value);
913 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator
I =
915 E = PTIHandled.end();
I != E; ++
I) {
916 if (PredHasWeights || SuccHasWeights)
918 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
926 for (
unsigned i = 0, e = NewSuccessors.
size(); i != e; ++i)
932 assert(
TD &&
"Cannot switch on pointer without DataLayout");
941 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
942 NewSI->
addCase(PredCases[i].Value, PredCases[i].Dest);
944 if (PredHasWeights || SuccHasWeights) {
952 createBranchWeights(MDWeights));
963 if (InfLoopBlock == 0) {
991 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1019 while (isa<DbgInfoIntrinsic>(I1))
1021 while (isa<DbgInfoIntrinsic>(I2))
1030 bool Changed =
false;
1034 if (isa<TerminatorInst>(I1))
1035 goto HoistTerminator;
1041 if (!I2->use_empty())
1042 I2->replaceAllUsesWith(I1);
1044 I2->eraseFromParent();
1053 while (isa<DbgInfoIntrinsic>(I1))
1055 while (isa<DbgInfoIntrinsic>(I2))
1088 I2->replaceAllUsesWith(NT);
1097 std::map<std::pair<Value*,Value*>,
SelectInst*> InsertedSelects;
1104 if (BB1V == BB2V)
continue;
1108 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1110 SI = cast<SelectInst>
1112 BB1V->
getName()+
"."+BB2V->getName()));
1147 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1153 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1157 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
1158 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1159 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1160 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1162 FirstNonPhiInBBEnd = &*
I;
1166 if (!FirstNonPhiInBBEnd)
1177 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1180 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1187 bool Changed =
false;
1188 while (RI1 != RE1 && RI2 != RE2) {
1190 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1193 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1201 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1202 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1203 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1204 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1208 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1209 MapValueFromBB1ToBB2[I1].first != I2)
1214 bool SwapOpnds =
false;
1215 if (ICmp1 && ICmp2 &&
1216 ICmp1->
getOperand(0) != ICmp2->getOperand(0) &&
1217 ICmp1->
getOperand(1) != ICmp2->getOperand(1) &&
1218 (ICmp1->
getOperand(0) == ICmp2->getOperand(1) ||
1219 ICmp1->
getOperand(1) == ICmp2->getOperand(0))) {
1220 ICmp2->swapOperands();
1225 ICmp2->swapOperands();
1232 Value *DifferentOp1 = 0, *DifferentOp2 = 0;
1233 unsigned Op1Idx = 0;
1241 MapValueFromBB1ToBB2.find(I1->
getOperand(I)) !=
1242 MapValueFromBB1ToBB2.end() ||
1244 isa<Constant>(I2->getOperand(I))) {
1247 ICmp2->swapOperands();
1252 DifferentOp2 = I2->getOperand(I);
1259 DifferentOp1->
getName() +
".sink",
1261 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1266 DEBUG(
dbgs() <<
"Create PHI node " << *NewPN <<
"\n";);
1268 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1269 MapValueFromBB1ToBB2.erase(I1);
1271 DEBUG(
dbgs() <<
"SINK common instructions " << *I1 <<
"\n";);
1275 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->
begin());
1282 if (!I2->use_empty())
1283 I2->replaceAllUsesWith(I1);
1285 I2->eraseFromParent();
1288 RE1 = BB1->getInstList().rend();
1291 FirstNonPhiInBBEnd = I1;
1337 unsigned MaxNumInstToLookAt = 10;
1339 RE = BrBB->
rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1398 if (isa<FCmpInst>(BrCond))
1406 bool Invert =
false;
1408 assert(ThenBB == BI->
getSuccessor(1) &&
"No edge from 'if' block?");
1411 assert(EndBB == BI->
getSuccessor(!Invert) &&
"No edge from to end block");
1420 unsigned SpeculationCost = 0;
1421 Value *SpeculatedStoreValue = 0;
1425 BBI != BBE; ++BBI) {
1428 if (isa<DbgInfoIntrinsic>(I))
1434 if (SpeculationCost > 1)
1443 if (!SpeculatedStoreValue &&
1448 if (SpeculatedStoreValue)
1449 SpeculatedStore = cast<StoreInst>(
I);
1461 ++SinkCandidateUseCounts[OpI];
1469 SinkCandidateUseCounts.
begin(), E = SinkCandidateUseCounts.end();
1471 if (I->first->getNumUses() == I->second) {
1473 if (SpeculationCost > 1)
1478 bool HaveRewritablePHIs =
false;
1489 HaveRewritablePHIs =
true;
1492 if (!OrigCE && !ThenCE)
1508 if (SpeculationCost > 1)
1514 if (!HaveRewritablePHIs && !(
HoistCondStores && SpeculatedStoreValue))
1518 DEBUG(
dbgs() <<
"SPECULATIVELY EXECUTING BB" << *ThenBB <<
"\n";);
1521 if (SpeculatedStoreValue) {
1524 Value *FalseV = SpeculatedStoreValue;
1552 Value *TrueV = ThenV, *FalseV = OrigV;
1556 TrueV->
getName() +
"." + FalseV->getName());
1585 if (isa<DbgInfoIntrinsic>(BBI))
1587 if (Size > 10)
return false;
1595 if (U->
getParent() != BB || isa<PHINode>(U))
return false;
1638 if (RealDest == BB)
continue;
1647 RealDest->
getName()+
".critedge",
1660 if (
PHINode *PN = dyn_cast<PHINode>(BBI)) {
1666 if (BBI->hasName()) N->
setName(BBI->getName()+
".c");
1672 if (PI != TranslateMap.
end())
1678 TranslateMap[BBI] = V;
1683 if (!BBI->use_empty())
1684 TranslateMap[BBI] = N;
1718 isa<ConstantInt>(IfCond))
1726 unsigned NumPhis = 0;
1739 PHINode *PN = cast<PHINode>(II++);
1756 if (PN == 0)
return true;
1763 isa<BinaryOperator>(IfCond)))
1773 if (cast<BranchInst>(IfBlock1->
getTerminator())->isConditional()) {
1778 if (!AggressiveInsts.
count(I) && !isa<DbgInfoIntrinsic>(
I)) {
1786 if (cast<BranchInst>(IfBlock2->
getTerminator())->isConditional()) {
1791 if (!AggressiveInsts.
count(I) && !isa<DbgInfoIntrinsic>(
I)) {
1799 DEBUG(
dbgs() <<
"FOUND IF CONDITION! " << *IfCond <<
" T: "
1824 cast<SelectInst>(Builder.
CreateSelect(IfCond, TrueVal, FalseVal,
""));
1845 assert(BI->
isConditional() &&
"Must be a conditional branch");
1848 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1854 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1863 if (FalseRet->getNumOperands() == 0) {
1864 TrueSucc->removePredecessor(BI->
getParent());
1874 Value *FalseValue = FalseRet->getReturnValue();
1877 if (
PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1878 if (TVPN->getParent() == TrueSucc)
1879 TrueValue = TVPN->getIncomingValueForBlock(BI->
getParent());
1880 if (
PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1881 if (FVPN->getParent() == FalseSucc)
1882 FalseValue = FVPN->getIncomingValueForBlock(BI->
getParent());
1889 if (
ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1892 if (
ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1898 TrueSucc->removePredecessor(BI->
getParent());
1905 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1906 }
else if (isa<UndefValue>(TrueValue)) {
1907 TrueValue = FalseValue;
1910 FalseValue,
"retval");
1914 Value *RI = !TrueValue ?
1919 DEBUG(
dbgs() <<
"\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1920 <<
"\n " << *BI <<
"NewRet = " << *RI
1921 <<
"TRUEBLOCK: " << *TrueSucc <<
"FALSEBLOCK: "<< *FalseSucc);
1933 uint64_t &ProbTrue, uint64_t &ProbFalse) {
1935 "Looking for probabilities on unconditional branch?");
1937 if (!ProfileData || ProfileData->getNumOperands() != 3)
return false;
1940 if (!CITrue || !CIFalse)
return false;
1942 ProbFalse = CIFalse->getValue().getZExtValue();
1950 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1979 if (
BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1980 if (PBI->isConditional() &&
1986 if (isa<CmpInst>(Curr)) {
2000 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2010 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2017 if (&*FrontIt != Cond &&
2018 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
2020 BonusInst = &*FrontIt;
2024 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2028 if (&*FrontIt != Cond)
2035 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2052 if (TrueDest == BB || FalseDest == BB)
2072 bool InvertPredCond =
false;
2096 bool UsedByBranch = (BonusInst && BonusInst->
hasOneUse() &&
2099 if (BonusInst && !UsedByBranch) {
2103 OE = BonusInst->
op_end(); OI != OE; ++OI) {
2105 if (!isa<Constant>(V) && !isa<Argument>(V))
2115 while (!Worklist.
empty()) {
2116 std::pair<Value*, unsigned> Pair = Worklist.
back();
2119 if (Pair.second >= 4)
continue;
2120 UsedValues.
erase(Pair.first);
2121 if (UsedValues.
empty())
break;
2123 if (
Instruction *I = dyn_cast<Instruction>(Pair.first)) {
2126 Worklist.
push_back(std::make_pair(OI->get(), Pair.second+1));
2130 if (!UsedValues.
empty())
return false;
2133 DEBUG(
dbgs() <<
"FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2137 if (InvertPredCond) {
2140 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
2141 CmpInst *CI = cast<CmpInst>(NewCond);
2155 NewBonus = BonusInst->
clone();
2175 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2183 if (PredHasWeights && SuccHasWeights) {
2187 NewWeights.
push_back(PredTrueWeight * SuccTrueWeight);
2192 NewWeights.
push_back(PredFalseWeight * (SuccFalseWeight +
2193 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2199 if (PredHasWeights && SuccHasWeights) {
2204 NewWeights.
push_back(PredTrueWeight * (SuccFalseWeight +
2205 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2207 NewWeights.
push_back(PredFalseWeight * SuccFalseWeight);
2212 if (NewWeights.
size() == 2) {
2219 createBranchWeights(MDWeights));
2224 for (
unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2226 PHIs[i]->getIncomingValueForBlock(PBI->
getParent()));
2253 if (PBI_C->
isOne()) {
2259 NotCond, MergedCond,
2264 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->
getParent()),
2278 if (isa<DbgInfoIntrinsic>(*I))
2301 if (BB->getSinglePredecessor()) {
2315 std::distance(PB, PE),
2345 while (isa<DbgInfoIntrinsic>(BBI))
2359 PBIOp = 0, BIOp = 1;
2361 PBIOp = 1, BIOp = 0;
2378 unsigned NumPhis = 0;
2380 isa<PHINode>(II); ++II, ++NumPhis)
2398 if (OtherDest == BB) {
2402 "infloop", BB->getParent());
2404 OtherDest = InfLoopBlock;
2416 PBICond = Builder.
CreateNot(PBICond, PBICond->getName()+
".not");
2423 Value *Cond = Builder.
CreateOr(PBICond, BICond,
"brmerge");
2431 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2436 if (PredHasWeights && SuccHasWeights) {
2437 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2438 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2439 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2440 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2445 NewWeights.
push_back(PredCommon * (SuccCommon + SuccOther) +
2446 PredOther * SuccCommon);
2447 NewWeights.
push_back(PredOther * SuccOther);
2454 createBranchWeights(MDWeights));
2469 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->
getParent());
2470 Value *PBIV = PN->getIncomingValue(PBBIdx);
2473 Value *
NV = cast<SelectInst>
2475 PN->setIncomingValue(PBBIdx, NV);
2494 uint32_t TrueWeight,
2495 uint32_t FalseWeight){
2501 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
2507 if (Succ == KeepEdge1)
2509 else if (Succ == KeepEdge2)
2519 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
2520 if (TrueBB == FalseBB)
2528 if (TrueWeight != FalseWeight)
2531 createBranchWeights(TrueWeight, FalseWeight));
2533 }
else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2561 if (!TrueVal || !FalseVal)
2570 uint32_t TrueWeight = 0, FalseWeight = 0;
2577 getSuccessorIndex()];
2578 FalseWeight = (uint32_t)Weights[SI->
findCaseValue(FalseVal).
2579 getSuccessorIndex()];
2585 TrueWeight, FalseWeight);
2633 if (isa<PHINode>(BB->
begin()) || !ICI->
hasOneUse())
return false;
2642 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator()))
return false;
2644 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2653 assert(VVal &&
"Should have a unique destination value");
2684 if (PHIUse == 0 || PHIUse != &SuccBlock->
front() ||
2711 Weights[0] = (Weights[0]+1) >> 1;
2712 Weights.push_back(Weights[0]);
2717 createBranchWeights(MDWeights));
2736 if (Cond == 0)
return false;
2743 std::vector<ConstantInt*> Values;
2744 bool TrueWhenEqual =
true;
2745 Value *ExtraCase = 0;
2746 unsigned UsedICmps = 0;
2754 TrueWhenEqual =
false;
2758 if (CompVal == 0)
return false;
2767 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2771 if (ExtraCase && Values.size() < 2)
return false;
2779 if (!TrueWhenEqual)
std::swap(DefaultBB, EdgeBB);
2783 DEBUG(
dbgs() <<
"Converting 'icmp' chain with " << Values.size()
2784 <<
" cases into SWITCH. BB is:\n" << *BB);
2806 DEBUG(
dbgs() <<
" ** 'icmp' chain unhandled condition: " << *ExtraCase
2807 <<
"\nEXTRABB = " << *BB);
2814 assert(TD &&
"Cannot switch on pointer without DataLayout");
2824 for (
unsigned i = 0, e = Values.size(); i != e; ++i)
2825 New->
addCase(Values[i], EdgeBB);
2831 isa<PHINode>(BBI); ++BBI) {
2832 PHINode *PN = cast<PHINode>(BBI);
2834 for (
unsigned i = 0, e = Values.size()-1; i != e; ++i)
2841 DEBUG(
dbgs() <<
" ** 'icmp' chain result is:\n" << *BB <<
'\n');
2858 if (!isa<DbgInfoIntrinsic>(I))
2862 bool InvokeRequiresTableEntry =
false;
2863 bool Changed =
false;
2865 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2870 InvokeRequiresTableEntry =
true;
2898 if (!InvokeRequiresTableEntry)
2915 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2925 while (!UncondBranchPreds.
empty()) {
2928 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
2943 while (!CondBranchPreds.
empty()) {
2958 bool Changed =
false;
2962 while (UI != BB->
begin()) {
2968 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
break;
2970 if (BBI->mayHaveSideEffects()) {
2971 if (
StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2972 if (SI->isVolatile())
2974 }
else if (
LoadInst *
LI = dyn_cast<LoadInst>(BBI)) {
2975 if (
LI->isVolatile())
2977 }
else if (
AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2978 if (RMWI->isVolatile())
2981 if (CXI->isVolatile())
2983 }
else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2984 !isa<LandingPadInst>(BBI)) {
2994 if (!BBI->use_empty())
2996 BBI->eraseFromParent();
3002 if (&BB->
front() != UI)
return Changed;
3005 for (
unsigned i = 0, e = Preds.size(); i != e; ++i) {
3008 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3025 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3028 if (i.getCaseSuccessor() == BB) {
3037 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3040 std::pair<unsigned, unsigned> &entry =
3041 Popularity[i.getCaseSuccessor()];
3042 if (entry.first == 0) {
3044 entry.second = i.getCaseIndex();
3051 unsigned MaxPop = 0;
3052 unsigned MaxIndex = 0;
3054 for (std::map<
BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3055 I = Popularity.begin(), E = Popularity.end(); I != E; ++
I) {
3056 if (I->second.first > MaxPop ||
3057 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3058 MaxPop = I->second.first;
3059 MaxIndex = I->second.second;
3060 MaxBlock = I->first;
3071 if (isa<PHINode>(MaxBlock->
begin()))
3072 for (
unsigned i = 0; i != MaxPop-1; ++i)
3077 if (i.getCaseSuccessor() == MaxBlock) {
3083 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3119 assert(SI->
getNumCases() > 1 &&
"Degenerate switch?");
3131 assert(Cases.size() == SI->
getNumCases() &&
"Not all cases gathered");
3135 for (
unsigned I = 1, E = Cases.size(); I != E; ++
I) {
3136 if (Cases[I-1]->getValue() != Cases[
I]->getValue()+1)
3148 if (NumCases->isNullValue() && SI->
getNumCases() != 0)
3164 uint32_t NewTrueWeight = 0;
3165 for (
unsigned I = 1, E = Weights.
size(); I != E; ++
I)
3166 NewTrueWeight += (uint32_t)Weights[
I];
3169 createBranchWeights(NewTrueWeight,
3170 (uint32_t)Weights[0]));
3176 isa<PHINode>(BBI); ++BBI) {
3177 for (
unsigned I = 0, E = SI->
getNumCases()-1; I != E; ++
I)
3178 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
3190 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3196 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3197 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3199 DEBUG(
dbgs() <<
"SimplifyCFG: switch case '"
3200 << I.getCaseValue() <<
"' is dead.\n");
3212 for (
unsigned I = 0, E = DeadCases.
size(); I != E; ++
I) {
3215 "Case was not found. Probably mistake in DeadCases forming.");
3229 createBranchWeights(MDWeights));
3232 return !DeadCases.
empty();
3255 while (
PHINode *
PHI = dyn_cast<PHINode>(I++)) {
3256 int Idx =
PHI->getBasicBlockIndex(BB);
3257 assert(Idx >= 0 &&
"PHI has no entry for predecessor?");
3259 Value *InValue =
PHI->getIncomingValue(Idx);
3260 if (InValue != CaseValue)
continue;
3275 ForwardingNodesMap ForwardingNodes;
3286 ForwardingNodes[
PHI].push_back(PhiIndex);
3289 bool Changed =
false;
3291 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3292 E = ForwardingNodes.end(); I != E; ++
I) {
3296 if (Indexes.
size() < 2)
continue;
3298 for (
size_t I = 0, E = Indexes.
size(); I != E; ++
I)
3310 return CE->isGEPWithNoNotionalOverIndexing();
3312 return isa<ConstantFP>(
C) ||
3313 isa<ConstantInt>(C) ||
3314 isa<ConstantPointerNull>(
C) ||
3315 isa<GlobalValue>(C) ||
3323 if (
Constant *
C = dyn_cast<Constant>(V))
3325 return ConstantPool.
lookup(V);
3355 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I))
3384 if (
T->getNumSuccessors() != 1)
3387 CaseDest =
T->getSuccessor(0);
3388 }
else if (isa<DbgInfoIntrinsic>(I)) {
3393 ConstantPool.
insert(std::make_pair(I,
C));
3401 *CommonDest = CaseDest;
3403 if (CaseDest != *CommonDest)
3408 while (
PHINode *
PHI = dyn_cast<PHINode>(I++)) {
3409 int Idx =
PHI->getBasicBlockIndex(Pred);
3428 Res.push_back(std::make_pair(
PHI, ConstVal));
3437 class SwitchLookupTable {
3442 SwitchLookupTable(
Module &M,
3451 Value *BuildLookup(Value *Index,
IRBuilder<> &Builder);
3457 const Type *ElementType);
3489 SwitchLookupTable::SwitchLookupTable(
Module &M,
3495 : SingleValue(0), BitMap(0), BitMapElementTy(0), Array(0) {
3496 assert(Values.size() &&
"Can't build lookup table without values!");
3497 assert(TableSize >= Values.size() &&
"Can't fit values in table!");
3500 SingleValue = Values.begin()->second;
3504 for (
size_t I = 0, E = Values.size(); I != E; ++
I) {
3511 TableContents[Idx] = CaseRes;
3513 if (CaseRes != SingleValue)
3518 if (Values.size() < TableSize) {
3519 for (uint64_t I = 0; I < TableSize; ++
I) {
3520 if (!TableContents[I])
3521 TableContents[
I] = DefaultValue;
3524 if (DefaultValue != SingleValue)
3531 Kind = SingleValueKind;
3536 if (WouldFitInRegister(TD, TableSize, DefaultValue->
getType())) {
3539 for (uint64_t I = TableSize; I > 0; --
I) {
3542 if (!isa<UndefValue>(TableContents[I - 1])) {
3543 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3544 TableInt |= Val->
getValue().
zext(TableInt.getBitWidth());
3547 BitMap = ConstantInt::get(M.
getContext(), TableInt);
3548 BitMapElementTy =
IT;
3556 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3559 GlobalVariable::PrivateLinkage,
3562 Array->setUnnamedAddr(
true);
3566 Value *SwitchLookupTable::BuildLookup(Value *Index,
IRBuilder<> &Builder) {
3568 case SingleValueKind:
3581 ConstantInt::get(MapTy, BitMapElementTy->
getBitWidth()),
3585 Value *DownShifted = Builder.
CreateLShr(BitMap, ShiftAmt,
3586 "switch.downshift");
3588 return Builder.
CreateTrunc(DownShifted, BitMapElementTy,
3592 Value *GEPIndices[] = { Builder.
getInt32(0), Index };
3595 return Builder.
CreateLoad(GEP,
"switch.load");
3601 bool SwitchLookupTable::WouldFitInRegister(
const DataLayout *TD,
3603 const Type *ElementType) {
3626 if (SI->
getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3629 bool AllTablesFitInRegister =
true;
3630 bool HasIllegalType =
false;
3632 E = ResultTypes.
end(); I != E; ++
I) {
3633 Type *Ty = I->second;
3636 HasIllegalType = HasIllegalType || !TTI.
isTypeLegal(Ty);
3639 AllTablesFitInRegister = AllTablesFitInRegister &&
3640 SwitchLookupTable::WouldFitInRegister(TD, TableSize, Ty);
3645 if (HasIllegalType && !AllTablesFitInRegister)
3650 if (AllTablesFitInRegister)
3670 assert(SI->
getNumCases() > 1 &&
"Degenerate switch?");
3707 MinCaseVal = CaseVal;
3709 MaxCaseVal = CaseVal;
3714 if (!
GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3719 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++
I) {
3720 if (!ResultLists.
count(I->first))
3722 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3729 DefaultResultsList,
TD))
3731 for (
size_t I = 0, E = DefaultResultsList.size(); I != E; ++
I) {
3733 Constant *Result = DefaultResultsList[
I].second;
3734 DefaultResults[
PHI] = Result;
3758 uint64_t MaxTableSize = CaseSize > 63? UINT64_MAX : 1ULL << CaseSize;
3759 assert(MaxTableSize >= TableSize &&
3760 "It is impossible for a switch to have more entries than the max "
3761 "representable value of its input integer type's size.");
3767 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3768 if (GeneratingCoveredLookupTable) {
3772 Value *Cmp = Builder.
CreateICmpULT(TableIndex, ConstantInt::get(
3773 MinCaseVal->
getType(), TableSize));
3779 bool ReturnedEarly =
false;
3780 for (
size_t I = 0, E = PHIs.
size(); I != E; ++
I) {
3783 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3784 DefaultResults[PHI], TD);
3786 Value *Result = Table.BuildLookup(TableIndex, Builder);
3790 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->use_begin()) &&
3793 ReturnedEarly =
true;
3797 PHI->addIncoming(Result, LookupBB);
3820 if (isValueEqualityComparison(SI)) {
3824 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3836 while (isa<DbgInfoIntrinsic>(BBI))
3839 if (FoldValueComparisonIntoPredecessors(SI, Builder))
3862 bool Changed =
false;
3911 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3912 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3913 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
3915 if (I->isTerminator() &&
3934 if (isValueEqualityComparison(BI)) {
3939 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
3946 while (isa<DbgInfoIntrinsic>(I))
3949 if (FoldValueComparisonIntoPredecessors(BI, Builder))
3951 }
else if (&*I == cast<Instruction>(BI->
getCondition())){
3954 while (isa<DbgInfoIntrinsic>(I))
3956 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4007 if (
BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4031 if (i == I->
getParent()->
end() || i->mayHaveSideEffects())
4036 if (GEP->getPointerOperand() ==
I)
4045 if (!
LI->isVolatile())
4046 return LI->getPointerAddressSpace() == 0;
4049 if (
StoreInst *SI = dyn_cast<StoreInst>(Use))
4050 if (!SI->isVolatile())
4051 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() ==
I;
4065 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
4084 bool Changed =
false;
4086 assert(BB && BB->
getParent() &&
"Block not embedded in function!");
4087 assert(BB->
getTerminator() &&
"Degenerate basic block encountered!");
4094 DEBUG(
dbgs() <<
"Removing BB: \n" << *BB);
4121 if (PN->getNumIncomingValues() == 2)
4127 if (SimplifyUncondBranch(BI, Builder))
return true;
4129 if (SimplifyCondBranch(BI, Builder))
return true;
4132 if (SimplifyReturn(RI, Builder))
return true;
4134 if (SimplifyResume(RI, Builder))
return true;
4136 if (SimplifySwitch(SI, Builder))
return true;
4139 if (SimplifyUnreachable(UI))
return true;
4142 if (SimplifyIndirectBr(IBI))
return true;
4155 return SimplifyCFGOpt(TTI, TD).run(BB);
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *TD)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Value * getValueOperand()
void push_back(const T &Elt)
static ConstantInt * getFalse(LLVMContext &Context)
void FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P=0)
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=0)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
IntegerType * getType() const
class_match< Value > m_Value()
m_Value() - Match an arbitrary value and ignore it.
Abstract base class of comparison instructions.
static bool HasNoDuplicateCall(const BasicBlock *BB)
ConstantIntTy * getCaseValue()
Resolves case value for current case.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static IntegerType * getInt1Ty(LLVMContext &C)
LoadInst * CreateLoad(Value *Ptr, const char *Name)
void addIncoming(Value *V, BasicBlock *BB)
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1), cl::desc("Control the amount of phi node folding to perform (default = 1)"))
int remove(const char *path);
uint64_t getZExtValue() const
Get zero extended value.
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
void swapSuccessors()
Swap the successors of this branch instruction.
STATISTIC(NumBitMaps,"Number of switch instructions turned into bitmaps")
The main container class for the LLVM Intermediate Representation.
static unsigned ComputeSpeculationCost(const User *I)
bool hasFnAttr(Attribute::AttrKind A) const
Determine whether this call has the given attribute.
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool removeUndefIntroducingPredecessor(BasicBlock *BB)
unsigned getNumOperands() const
unsigned getNumOperands() const
getNumOperands - Return number of MDNode operands.
void DeleteDeadBlock(BasicBlock *BB)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Value * getValue() const
Convenience accessor.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=0)
Predicate getInversePredicate() const
Return the inverse of the instruction's predicate.
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
bool mayHaveSideEffects() const
static Constant * ConstantFold(Instruction *I, const SmallDenseMap< Value *, Constant * > &ConstantPool, const DataLayout *DL)
void operator<(const Optional< T > &X, const Optional< U > &Y)
Poison comparison between two Optional objects. Clients needs to explicitly compare the underlying va...
static void GetBranchWeights(TerminatorInst *TI, SmallVectorImpl< uint64_t > &Weights)
iterator insert(iterator I, const T &Elt)
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select)
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
MDNode - a tuple of other values.
reverse_iterator rbegin()
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void setDebugLoc(const DebugLoc &Loc)
setDebugLoc - Set the debug location information for this instruction.
ConstantInt * findCaseDest(BasicBlock *BB)
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LoopInfoBase< BlockT, LoopT > * LI
StringRef getName() const
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I)
Check if passing a value to an instruction will cause undefined behavior.
reverse_iterator rbegin()
void setCallingConv(CallingConv::ID CC)
Value * getOperand(unsigned i) const LLVM_READONLY
getOperand - Return specified operand.
APInt Not(const APInt &APIVal)
Bitwise complement function.
Instruction * getFirstNonPHIOrDbg()
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
static bool isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, Instruction *Cond, SmallVectorImpl< PHINode * > &PhiNodes)
bool match(Val *V, const Pattern &P)
static bool DominatesMergePoint(Value *V, BasicBlock *BB, SmallPtrSet< Instruction *, 4 > *AggressiveInsts, unsigned &CostRemaining)
bool isUnconditional() const
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
static bool SinkThenElseCodeToEnd(BranchInst *BI1)
bool isIdenticalTo(const Instruction *I) const
static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI)
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT,"arm-default-it","Generate IT block based on arch"), clEnumValN(RestrictedIT,"arm-restrict-it","Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT,"arm-no-restrict-it","Allow IT blocks based on ARMv7"), clEnumValEnd))
const APInt & getValue() const
Return the constant's value.
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
#define llvm_unreachable(msg)
static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, BasicBlock *TrueBB, BasicBlock *FalseBB, uint32_t TrueWeight, uint32_t FalseWeight)
static int ConstantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=0)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
const Value * getCalledValue() const
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc. to it.
void assign(unsigned NumElts, const T &Elt)
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI)
bool MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P=0)
Function must be in a unwind table.
void setName(const Twine &Name)
static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB)
Instruction * clone() const
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB)
Determine if we can hoist sink a sole store instruction out of a conditional block.
BasicBlock * getDestination(unsigned i)
getDestination - Return the specified destination.
static bool HoistThenElseCodeToIf(BranchInst *BI)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
This class represents a cast from a pointer to an integer.
Interval::succ_iterator succ_begin(Interval *I)
uint64_t getZExtValue() const
Return the zero extended value.
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB)
Speculate a conditional basic block flattening the CFG.
static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, const TargetTransformInfo &TTI, const DataLayout *TD)
static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, IRBuilder<> &Builder)
static Value * GatherConstantCompares(Value *V, std::vector< ConstantInt * > &Vals, Value *&Extra, const DataLayout *TD, bool isEQ, unsigned &UsedICmps)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
UnreachableInst * CreateUnreachable()
bool sgt(const APInt &RHS) const
Signed greather than comparison.
BasicBlock * getSuccessor(unsigned i) const
This class represents a no-op cast from one type to another.
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
class_match< ConstantInt > m_ConstantInt()
m_ConstantInt() - Match an arbitrary ConstantInt and ignore it.
void setSuccessor(unsigned idx, BasicBlock *B)
static void EliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
void replaceAllUsesWith(Value *V)
bool EliminateDuplicatePHINodes(BasicBlock *BB)
ConstantRange subtract(const APInt &CI) const
size_t size() const
size - Get the array size.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
BasicBlock * getNormalDest() const
void ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout *TD=0, unsigned Depth=0)
bool mayReadOrWriteMemory() const
bool ult(const APInt &RHS) const
Unsigned less than comparison.
unsigned getNumIncomingValues() const
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
InstListType::reverse_iterator reverse_iterator
unsigned getNumSuccessors() const
void intersectOptionalDataWith(const Value *V)
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, const DataLayout *TD=0)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
unsigned getCaseIndex() const
Returns number of current case.
bool isIdenticalToWhenDefined(const Instruction *I) const
static bool HasBranchWeights(const Instruction *I)
void insertBefore(Instruction *InsertPos)
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB)
Value * CreateNot(Value *V, const Twine &Name="")
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder)
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
LLVM Constant Representation.
const Value * getCondition() const
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Interval::pred_iterator pred_begin(Interval *I)
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=0)
BasicBlock * getIncomingBlock(unsigned i) const
const InstListType & getInstList() const
Return the underlying instruction list container.
Represent an integer comparison operator.
iterator insert(iterator where, NodeTy *New)
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
Integer representation type.
Predicate getPredicate() const
Return the predicate for this instruction.
bool count(const KeyT &Val) const
count - Return true if the specified key is in the map.
static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
static UndefValue * get(Type *T)
Value(Type *Ty, unsigned scid)
Value * SimplifyInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
Instruction * getFirstNonPHIOrDbgOrLifetime()
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
LLVMContext & getContext() const
All values hold a context through their type.
const Value * getTrueValue() const
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
void setMetadata(unsigned KindID, MDNode *Node)
CallingConv::ID getCallingConv() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool FoldBranchToCommonDest(BranchInst *BI)
bool isTerminator() const
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=0)
bool isConditional() const
bool isSafeToSpeculativelyExecute(const Value *V, const DataLayout *TD=0)
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
static bool ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout *TD, const SmallDenseMap< PHINode *, Type * > &ResultTypes)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
BasicBlock * getUnwindDest() const
unsigned getIntegerBitWidth() const
bool fitsInLegalInteger(unsigned Width) const
Class for constant integers.
bool slt(const APInt &RHS) const
Signed less than comparison.
Value * getIncomingValue(unsigned i) const
bool cannotDuplicate() const
Determine if the call cannot be duplicated.
unsigned getNumSuccessors() const
ConstantRange inverse() const
void eraseFromParent()
Unlink 'this' from the containing function and delete it.
MDNode * getMetadata(unsigned KindID) const
static bool ExtractBranchMetadata(BranchInst *BI, uint64_t &ProbTrue, uint64_t &ProbFalse)
Value * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
const APInt & getLower() const
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
BasicBlockTy * getCaseSuccessor()
Resolves successor for current case.
BasicBlock * getBasicBlock() const
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
std::reverse_iterator< iterator > reverse_iterator
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
const BasicBlock & getEntryBlock() const
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=0)
CaseIt findCaseValue(const ConstantInt *C)
static ConstantInt * getTrue(LLVMContext &Context)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void splice(iterator where, iplist &L2)
static void EraseTerminatorInstAndDCECond(TerminatorInst *TI)
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
bool isAllOnesValue() const
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
static cl::opt< bool > DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), cl::desc("Duplicate return instructions into unconditional branches"))
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="")
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
Value * getCondition() const
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
unsigned getOpcode() const
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store preceeds"))
BasicBlock * getSuccessor(unsigned idx) const
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy. Return the value untouched if the type of ...
Value * getCondition() const
const AttributeSet & getAttributes() const
BasicBlock * getDefaultDest() const
static ConstantRange makeICmpRegion(unsigned Pred, const ConstantRange &Other)
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=0, BasicBlock *InsertBefore=0)
Creates a new BasicBlock.
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred)
static bool ValuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
unsigned getPrimitiveSizeInBits() const
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
void removeCase(CaseIt i)
unsigned getNumCases() const
void setCondition(Value *V)
const APInt & getUpper() const
void setAttributes(const AttributeSet &Attrs)
static Constant * LookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
LLVMContext & getContext() const
Get the context in which this basic block lives.
static bool ForwardSwitchConditionToPHI(SwitchInst *SI)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
LLVM Value Representation.
ValueT lookup(const KeyT &Val) const
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
void setDefaultDest(BasicBlock *DefaultCase)
CallInst * CreateCall(Value *Callee, const Twine &Name="")
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2)
Constant * ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, ArrayRef< Constant * > Ops, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI, const DataLayout *TD)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
ItTy prior(ItTy it, Dist n)
static bool ValidLookupTableConstant(Constant *C)
static bool GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout *DL)
static PHINode * FindPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
const Value * getFalseValue() const
APInt LLVM_ATTRIBUTE_UNUSED_RESULT zext(unsigned width) const
Zero extend to a new width.
static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *TD, IRBuilder<> &Builder)
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
Determine if one instruction is the same operation as another.
bool operator==(uint64_t V1, const APInt &V2)
static void FitWeights(MutableArrayRef< uint64_t > Weights)
void setIncomingValue(unsigned i, Value *V)
static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *TD)
iterator find(const KeyT &Val)
Value * getPointerOperand()
static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred)
int getBasicBlockIndex(const BasicBlock *BB) const
unsigned getNumDestinations() const
void removeDestination(unsigned i)
const BasicBlock * getParent() const
InstListType::iterator iterator
Instruction iterators...
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
static ConstantInt * GetConstantInt(Value *V, const DataLayout *TD)
bool isOne() const
Determine if the value is one.
static bool EliminateDeadSwitchCases(SwitchInst *SI)
LLVMContext & getContext() const
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.