85 #define DEBUG_TYPE "simplifycfg" 94 "Control the amount of phi node folding to perform (default = 2)"));
98 cl::desc(
"Duplicate return instructions into unconditional branches"));
102 cl::desc(
"Sink common instructions down to the end block"));
106 cl::desc(
"Hoist conditional stores if an unconditional store precedes"));
110 cl::desc(
"Hoist conditional stores even if an unconditional store does not " 111 "precede - hoist multiple conditional stores into a single " 112 "predicated store"));
116 cl::desc(
"When merging conditional stores, do so even if the resultant " 117 "basic blocks are unlikely to be if-converted as a result"));
121 cl::desc(
"Allow exactly one expensive instruction to be speculatively " 126 cl::desc(
"Limit maximum recursion depth when calculating costs of " 127 "speculatively executed instructions"));
129 STATISTIC(NumBitMaps,
"Number of switch instructions turned into bitmaps");
131 "Number of switch instructions turned into linear mapping");
133 "Number of switch instructions turned into lookup tables");
135 NumLookupTablesHoles,
136 "Number of switch instructions turned into lookup tables (holes checked)");
137 STATISTIC(NumTableCmpReuses,
"Number of reused switch table lookup compares");
139 "Number of common instructions sunk down to the end block");
140 STATISTIC(NumSpeculations,
"Number of speculative executed instructions");
147 using SwitchCaseResultVectorTy =
156 struct ValueEqualityComparisonCase {
161 : Value(Value), Dest(Dest) {}
163 bool operator<(ValueEqualityComparisonCase RHS)
const {
165 return Value < RHS.Value;
171 class SimplifyCFGOpt {
180 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
181 bool SimplifyEqualityComparisonWithOnlyPredecessor(
Instruction *TI,
184 bool FoldValueComparisonIntoPredecessors(
Instruction *TI,
198 bool tryToSimplifyUncondBranchWithICmpInIt(
ICmpInst *ICI,
205 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
211 bool requestResimplify() {
236 if (SI1Succs.
count(Succ))
238 PHINode *PN = cast<PHINode>(BBI);
242 FailBlocks->insert(Succ);
269 if (!(Cond->
getOperand(0) == Ci2->getOperand(0) &&
271 !(Cond->
getOperand(0) == Ci2->getOperand(1) &&
279 if (SI1Succs.
count(Succ))
281 PHINode *PN = cast<PHINode>(BBI);
297 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
307 "Instruction is not safe to speculatively execute!");
330 unsigned &CostRemaining,
332 unsigned Depth = 0) {
364 if (AggressiveInsts.
count(I))
381 if (Cost > CostRemaining &&
386 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
395 AggressiveInsts.
insert(I);
412 if (isa<ConstantPointerNull>(V))
417 if (CE->getOpcode() == Instruction::IntToPtr)
418 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
423 return cast<ConstantInt>(
441 struct ConstantComparesGatherer {
445 Value *CompValue =
nullptr;
448 Value *Extra =
nullptr;
454 unsigned UsedICmps = 0;
461 ConstantComparesGatherer(
const ConstantComparesGatherer &) =
delete;
462 ConstantComparesGatherer &
463 operator=(
const ConstantComparesGatherer &) =
delete;
468 bool setValueOnce(
Value *NewVal) {
469 if (CompValue && CompValue != NewVal)
472 return (CompValue !=
nullptr);
486 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
543 if (!setValueOnce(RHSVal))
566 if (!setValueOnce(RHSVal))
595 CandidateVal = RHSVal;
610 if (!setValueOnce(CandidateVal))
626 void gather(
Value *V) {
628 bool isEQ = (I->
getOpcode() == Instruction::Or);
638 while (!DFT.
empty()) {
643 if (I->
getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
652 if (matchInstruction(I, isEQ))
677 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
678 if (BI->isConditional())
679 Cond = dyn_cast<Instruction>(BI->getCondition());
696 if (!
SI->getParent()->hasNPredecessorsOrMore(128 /
SI->getNumSuccessors()))
697 CV =
SI->getCondition();
698 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI))
699 if (BI->isConditional() && BI->getCondition()->hasOneUse())
700 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
702 CV = ICI->getOperand(0);
708 Value *Ptr = PTII->getPointerOperand();
709 if (PTII->getType() == DL.getIntPtrType(Ptr->
getType()))
718 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
719 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
721 Cases.reserve(
SI->getNumCases());
722 for (
auto Case :
SI->cases())
723 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
724 Case.getCaseSuccessor()));
725 return SI->getDefaultDest();
731 Cases.push_back(ValueEqualityComparisonCase(
740 std::vector<ValueEqualityComparisonCase> &Cases) {
741 Cases.erase(
std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
746 std::vector<ValueEqualityComparisonCase> &C2) {
747 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *
V2 = &C2;
750 if (V1->size() > V2->size())
755 if (V1->size() == 1) {
758 for (
unsigned i = 0, e = V2->size(); i != e; ++i)
759 if (TheVal == (*V2)[i].
Value)
766 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
767 while (i1 != e1 && i2 != e2) {
770 if ((*V1)[i1].Value < (*V2)[i2].Value)
793 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
797 if (TrueWeight || FalseWeight)
799 .createBranchWeights(TrueWeight, FalseWeight);
808 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
814 Value *ThisVal = isValueEqualityComparison(TI);
815 assert(ThisVal &&
"This isn't a value comparison!!");
816 if (ThisVal != PredVal)
823 std::vector<ValueEqualityComparisonCase> PredCases;
825 GetValueEqualityComparisonCases(Pred->
getTerminator(), PredCases);
829 std::vector<ValueEqualityComparisonCase> ThisCases;
830 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
842 if (isa<BranchInst>(TI)) {
845 assert(ThisCases.size() == 1 &&
"Branch can only have one case!");
851 ThisCases[0].Dest->removePredecessor(TI->
getParent());
854 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
864 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
865 DeadCases.
insert(PredCases[i].Value);
868 <<
"Through successor TI: " << *TI);
882 if (DeadCases.count(i->getCaseValue())) {
884 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
887 i->getCaseSuccessor()->removePredecessor(TI->
getParent());
891 if (HasWeight && Weights.size() >= 2)
902 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
903 if (PredCases[i].Dest == TIBB) {
906 TIV = PredCases[i].
Value;
908 assert(TIV &&
"No edge from pred to succ?");
913 for (
unsigned i = 0, e = ThisCases.size(); i != e; ++i)
914 if (ThisCases[i].
Value == TIV) {
915 TheRealDest = ThisCases[i].Dest;
921 TheRealDest = ThisDef;
926 if (Succ != CheckEdge)
936 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
948 struct ConstantIntOrdering {
969 return MDS->getString().equals(
"branch_weights");
989 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
991 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
999 uint64_t Max = *std::max_element(Weights.
begin(), Weights.
end());
1000 if (Max > UINT_MAX) {
1002 for (uint64_t &
I : Weights)
1011 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(
Instruction *TI,
1014 Value *CV = isValueEqualityComparison(TI);
1015 assert(CV &&
"Not a comparison?");
1016 bool Changed =
false;
1019 while (!Preds.
empty()) {
1024 Value *PCV = isValueEqualityComparison(PTI);
1026 if (PCV == CV && TI != PTI) {
1029 for (
auto *Succ : FailBlocks) {
1036 std::vector<ValueEqualityComparisonCase> BBCases;
1037 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1039 std::vector<ValueEqualityComparisonCase> PredCases;
1040 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1052 if (PredHasWeights) {
1055 if (Weights.
size() != 1 + PredCases.size())
1056 PredHasWeights = SuccHasWeights =
false;
1057 }
else if (SuccHasWeights)
1061 Weights.
assign(1 + PredCases.size(), 1);
1064 if (SuccHasWeights) {
1067 if (SuccWeights.
size() != 1 + BBCases.size())
1068 PredHasWeights = SuccHasWeights =
false;
1069 }
else if (PredHasWeights)
1070 SuccWeights.
assign(1 + BBCases.size(), 1);
1072 if (PredDefault == BB) {
1075 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1076 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1077 if (PredCases[i].Dest != BB)
1078 PTIHandled.insert(PredCases[i].
Value);
1081 std::swap(PredCases[i], PredCases.back());
1083 if (PredHasWeights || SuccHasWeights) {
1085 Weights[0] += Weights[i + 1];
1090 PredCases.pop_back();
1096 if (PredDefault != BBDefault) {
1098 PredDefault = BBDefault;
1102 unsigned CasesFromPred = Weights.
size();
1103 uint64_t ValidTotalSuccWeight = 0;
1104 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1105 if (!PTIHandled.count(BBCases[i].Value) &&
1106 BBCases[i].Dest != BBDefault) {
1107 PredCases.push_back(BBCases[i]);
1108 NewSuccessors.
push_back(BBCases[i].Dest);
1109 if (SuccHasWeights || PredHasWeights) {
1113 Weights.
push_back(Weights[0] * SuccWeights[i + 1]);
1114 ValidTotalSuccWeight += SuccWeights[i + 1];
1118 if (SuccHasWeights || PredHasWeights) {
1119 ValidTotalSuccWeight += SuccWeights[0];
1121 for (
unsigned i = 1; i < CasesFromPred; ++i)
1122 Weights[i] *= ValidTotalSuccWeight;
1124 Weights[0] *= SuccWeights[0];
1130 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1131 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1132 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1133 if (PredCases[i].Dest == BB) {
1136 if (PredHasWeights || SuccHasWeights) {
1137 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1142 std::swap(PredCases[i], PredCases.back());
1143 PredCases.pop_back();
1150 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1151 if (PTIHandled.count(BBCases[i].Value)) {
1153 if (PredHasWeights || SuccHasWeights)
1155 PredCases.push_back(BBCases[i]);
1156 NewSuccessors.
push_back(BBCases[i].Dest);
1164 if (PredHasWeights || SuccHasWeights)
1166 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1174 for (
BasicBlock *NewSuccessor : NewSuccessors)
1188 for (ValueEqualityComparisonCase &V : PredCases)
1189 NewSI->
addCase(V.Value, V.Dest);
1191 if (PredHasWeights || SuccHasWeights) {
1208 if (!InfLoopBlock) {
1230 for (
const PHINode &PN : Succ->phis()) {
1231 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1232 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1233 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1264 while (isa<DbgInfoIntrinsic>(I1))
1266 while (isa<DbgInfoIntrinsic>(I2))
1275 bool Changed =
false;
1280 goto HoistTerminator;
1290 if (C1->isMustTailCall() != C2->isMustTailCall())
1296 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1297 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1312 if (!I2->use_empty())
1313 I2->replaceAllUsesWith(I1);
1332 I2->eraseFromParent();
1342 while (isa<DbgInfoIntrinsic>(I1))
1344 while (isa<DbgInfoIntrinsic>(I2))
1357 for (
PHINode &PN : Succ->phis()) {
1358 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1359 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1381 I2->replaceAllUsesWith(NT);
1396 std::map<std::pair<Value *, Value *>,
SelectInst *> InsertedSelects;
1398 for (
PHINode &PN : Succ->phis()) {
1399 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1400 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1406 SelectInst *&
SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1408 SI = cast<SelectInst>(
1410 BB1V->
getName() +
"." + BB2V->getName(), BI));
1413 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1414 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1415 PN.setIncomingValue(i, SI);
1438 for (
auto *I : Insts) {
1440 if (isa<PHINode>(I) || I->
isEHPad() || isa<AllocaInst>(
I) ||
1447 if (
const auto *
C = dyn_cast<CallInst>(I))
1453 if (!isa<StoreInst>(I) && !I->
hasOneUse())
1458 for (
auto *I : Insts)
1466 if (!isa<StoreInst>(I0)) {
1470 auto *U = cast<Instruction>(*I->
user_begin());
1472 PNUse->getParent() == Succ &&
1473 PNUse->getIncomingValueForBlock(I->
getParent()) == I) ||
1496 for (
unsigned OI = 0, OE = I0->
getNumOperands(); OI != OE; ++OI) {
1505 if (!
all_of(Insts, SameAsI0)) {
1510 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
1514 for (
auto *I : Insts)
1525 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1530 for (
auto *BB : Blocks) {
1534 }
while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1535 if (!isa<DbgInfoIntrinsic>(I))
1544 if (!isa<StoreInst>(I0)) {
1547 auto *U = cast<Instruction>(*I->
user_begin());
1573 assert(!
Op->getType()->isTokenTy() &&
"Can't PHI tokens!");
1575 Op->getName() +
".sink", &BBEnd->front());
1576 for (
auto *I : Insts)
1585 I0->
moveBefore(&*BBEnd->getFirstInsertionPt());
1588 for (
auto *I : Insts)
1602 if (!isa<StoreInst>(I0)) {
1608 PN->replaceAllUsesWith(I0);
1609 PN->eraseFromParent();
1613 for (
auto *I : Insts)
1630 class LockstepReverseIterator {
1643 for (
auto *BB : Blocks) {
1645 for (Inst = Inst->
getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1656 bool isValid()
const {
1663 for (
auto *&Inst : Insts) {
1664 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1665 Inst = Inst->getPrevNode();
1730 auto *
T =
B->getTerminator();
1731 if (isa<BranchInst>(
T) && cast<BranchInst>(
T)->isUnconditional())
1733 else if ((isa<BranchInst>(
T) || isa<SwitchInst>(
T)) && !Cond)
1738 if (UnconditionalPreds.
size() < 2)
1741 bool Changed =
false;
1748 unsigned ScanIdx = 0;
1751 LockstepReverseIterator LRI(UnconditionalPreds);
1752 while (LRI.isValid() &&
1754 LLVM_DEBUG(
dbgs() <<
"SINK: instruction can be sunk: " << *(*LRI)[0]
1756 InstructionsToSink.
insert((*LRI).begin(), (*LRI).end());
1761 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1762 unsigned NumPHIdValues = 0;
1763 for (
auto *I : *LRI)
1764 for (
auto *V : PHIOperands[I])
1765 if (InstructionsToSink.
count(V) == 0)
1767 LLVM_DEBUG(
dbgs() <<
"SINK: #phid values: " << NumPHIdValues <<
"\n");
1768 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.
size();
1769 if ((NumPHIdValues % UnconditionalPreds.
size()) != 0)
1772 return NumPHIInsts <= 1;
1775 if (ScanIdx > 0 && Cond) {
1783 bool Profitable =
false;
1784 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1816 for (
unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1818 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1824 if (!ProfitableToSinkInstruction(LRI)) {
1827 dbgs() <<
"SINK: stopping here, too many PHIs would be created!\n");
1878 unsigned MaxNumInstToLookAt = 9;
1880 if (!MaxNumInstToLookAt)
1882 --MaxNumInstToLookAt;
1885 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1888 if (
auto *
SI = dyn_cast<StoreInst>(&CurI)) {
1890 if (
SI->getPointerOperand() == StorePtr)
1892 return SI->getValueOperand();
1941 if (isa<FCmpInst>(BrCond))
1949 bool Invert =
false;
1965 unsigned SpeculationCost = 0;
1966 Value *SpeculatedStoreValue =
nullptr;
1969 BBE = std::prev(ThenBB->
end());
1970 BBI != BBE; ++BBI) {
1973 if (isa<DbgInfoIntrinsic>(I)) {
1981 if (SpeculationCost > 1)
1987 I, BB, ThenBB, EndBB))))
1989 if (!SpeculatedStoreValue &&
1995 if (SpeculatedStoreValue)
1996 SpeculatedStore = cast<StoreInst>(
I);
2006 ++SinkCandidateUseCounts[OpI];
2014 I = SinkCandidateUseCounts.begin(),
2015 E = SinkCandidateUseCounts.end();
2017 if (I->first->
hasNUses(I->second)) {
2019 if (SpeculationCost > 1)
2024 bool HaveRewritablePHIs =
false;
2026 Value *OrigV = PN.getIncomingValueForBlock(BB);
2027 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2039 HaveRewritablePHIs =
true;
2042 if (!OrigCE && !ThenCE)
2052 if (OrigCost + ThenCost > MaxCost)
2060 if (SpeculationCost > 1)
2066 if (!HaveRewritablePHIs && !(
HoistCondStores && SpeculatedStoreValue))
2070 LLVM_DEBUG(
dbgs() <<
"SPECULATIVELY EXECUTING BB" << *ThenBB <<
"\n";);
2073 if (SpeculatedStoreValue) {
2076 Value *FalseV = SpeculatedStoreValue;
2080 BrCond, TrueV, FalseV,
"spec.store.select", BI);
2088 for (
auto &I : *ThenBB)
2093 ThenBB->begin(), std::prev(ThenBB->end()));
2098 unsigned OrigI = PN.getBasicBlockIndex(BB);
2099 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2100 Value *OrigV = PN.getIncomingValue(OrigI);
2101 Value *ThenV = PN.getIncomingValue(ThenI);
2110 Value *TrueV = ThenV, *FalseV = OrigV;
2114 BrCond, TrueV, FalseV,
"spec.select", BI);
2115 PN.setIncomingValue(OrigI, V);
2116 PN.setIncomingValue(ThenI, V);
2142 if (UI->
getParent() != BB || isa<PHINode>(UI))
2217 if (
PHINode *PN = dyn_cast<PHINode>(BBI)) {
2224 N->
setName(BBI->getName() +
".c");
2229 if (PI != TranslateMap.
end())
2235 if (!BBI->use_empty())
2236 TranslateMap[&*BBI] = V;
2242 if (!BBI->use_empty())
2243 TranslateMap[&*BBI] = N;
2250 if (
auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2290 isa<ConstantInt>(IfCond))
2298 unsigned NumPhis = 0;
2313 PHINode *PN = cast<PHINode>(II++);
2321 MaxCostVal0, TTI) ||
2338 isa<BinaryOperator>(IfCond)))
2348 if (cast<BranchInst>(IfBlock1->
getTerminator())->isConditional()) {
2353 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2361 if (cast<BranchInst>(IfBlock2->
getTerminator())->isConditional()) {
2366 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2375 <<
" T: " << IfTrue->
getName()
2376 <<
" F: " << IfFalse->
getName() <<
"\n");
2419 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2425 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2434 if (FalseRet->getNumOperands() == 0) {
2435 TrueSucc->removePredecessor(BI->
getParent());
2445 Value *FalseValue = FalseRet->getReturnValue();
2448 if (
PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2449 if (TVPN->getParent() == TrueSucc)
2450 TrueValue = TVPN->getIncomingValueForBlock(BI->
getParent());
2451 if (
PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2452 if (FVPN->getParent() == FalseSucc)
2453 FalseValue = FVPN->getIncomingValueForBlock(BI->
getParent());
2460 if (
ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2463 if (
ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2469 TrueSucc->removePredecessor(BI->
getParent());
2476 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2477 }
else if (isa<UndefValue>(TrueValue)) {
2478 TrueValue = FalseValue;
2481 Builder.
CreateSelect(BrCond, TrueValue, FalseValue,
"retval", BI);
2490 LLVM_DEBUG(
dbgs() <<
"\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2491 <<
"\n " << *BI <<
"NewRet = " << *RI <<
"TRUEBLOCK: " 2492 << *TrueSucc <<
"FALSEBLOCK: " << *FalseSucc);
2502 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2520 uint64_t &PredTrueWeight,
2521 uint64_t &PredFalseWeight,
2522 uint64_t &SuccTrueWeight,
2523 uint64_t &SuccFalseWeight) {
2524 bool PredHasWeights =
2526 bool SuccHasWeights =
2528 if (PredHasWeights || SuccHasWeights) {
2529 if (!PredHasWeights)
2530 PredTrueWeight = PredFalseWeight = 1;
2531 if (!SuccHasWeights)
2532 SuccTrueWeight = SuccFalseWeight = 1;
2545 const unsigned PredCount =
pred_size(BB);
2556 if (
BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2557 if (PBI->isConditional() &&
2564 if (isa<CmpInst>(Curr)) {
2578 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2586 while (isa<DbgInfoIntrinsic>(CondIt))
2598 unsigned NumBonusInsts = 0;
2599 for (
auto I = BB->
begin(); Cond != &*
I; ++
I) {
2601 if (isa<DbgInfoIntrinsic>(I))
2607 if (User ==
nullptr || User->
getParent() != BB)
2615 NumBonusInsts += PredCount;
2617 if (NumBonusInsts > BonusInstThreshold)
2633 if (TrueDest == BB || FalseDest == BB)
2652 bool InvertPredCond =
false;
2656 Opc = Instruction::Or;
2658 Opc = Instruction::And;
2660 Opc = Instruction::And;
2661 InvertPredCond =
true;
2663 Opc = Instruction::Or;
2664 InvertPredCond =
true;
2673 LLVM_DEBUG(
dbgs() <<
"FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2677 if (InvertPredCond) {
2680 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
2681 CmpInst *CI = cast<CmpInst>(NewCond);
2699 for (
auto BonusInst = BB->
begin(); Cond != &*BonusInst; ++BonusInst) {
2700 if (isa<DbgInfoIntrinsic>(BonusInst))
2705 VMap[&*BonusInst] = NewBonusInst;
2715 NewBonusInst->
takeName(&*BonusInst);
2716 BonusInst->setName(BonusInst->getName() +
".old");
2733 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2736 SuccTrueWeight, SuccFalseWeight);
2744 NewWeights.
push_back(PredTrueWeight * SuccTrueWeight);
2750 (SuccFalseWeight + SuccTrueWeight) +
2751 PredTrueWeight * SuccFalseWeight);
2763 (SuccFalseWeight + SuccTrueWeight) +
2764 PredFalseWeight * SuccTrueWeight);
2766 NewWeights.
push_back(PredFalseWeight * SuccFalseWeight);
2771 if (NewWeights.
size() == 2) {
2782 for (
unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2784 PHIs[i]->getIncomingValueForBlock(PBI->
getParent()));
2793 MergedCond = cast<Instruction>(
2794 Builder.
CreateBinOp(Instruction::And, NotCond, CondInPred,
2797 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2798 Instruction::Or, PBI->
getCondition(), MergedCond,
"or.cond"));
2803 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2804 Instruction::And, PBI->
getCondition(), CondInPred,
"and.cond"));
2805 if (PBI_C->
isOne()) {
2808 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2809 Instruction::Or, NotCond, MergedCond,
"or.cond"));
2813 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->
getParent()),
2832 if (isa<DbgInfoIntrinsic>(I))
2844 for (
auto *BB : {BB1, BB2}) {
2848 if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
2860 Value *AlternativeV =
nullptr) {
2878 for (
auto I = Succ->
begin(); isa<PHINode>(
I); ++
I)
2879 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2880 PHI = cast<PHINode>(
I);
2886 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2895 if (!AlternativeV &&
2896 (!isa<Instruction>(V) || cast<Instruction>(V)->
getParent() != BB))
2911 bool InvertPCond,
bool InvertQCond,
2913 auto IsaBitcastOfPointerType = [](
const Instruction &
I) {
2927 for (
auto &I : BB->instructionsWithoutDebug()) {
2929 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(
I) ||
2933 else if (I.
isTerminator() || IsaBitcastOfPointerType(I))
2944 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2945 !IsWorthwhile(QFB)))
2955 if (!PStore || !QStore)
2976 for (
auto &I : *QFB)
2980 for (
auto &I : *QTB)
3007 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3017 Value *PPred = PStore->
getParent() == PTB ? PCond : QB.CreateNot(PCond);
3018 Value *QPred = QStore->
getParent() == QTB ? QCond : QB.CreateNot(QCond);
3021 PPred = QB.CreateNot(PPred);
3023 QPred = QB.CreateNot(QPred);
3024 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3028 QB.SetInsertPoint(
T);
3029 StoreInst *
SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3036 unsigned TypeAlignment =
3038 unsigned MinAlignment;
3039 unsigned MaxAlignment;
3040 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
3045 if (MinAlignment != 0) {
3048 }
else if (MaxAlignment != 0) {
3051 SI->
setAlignment(std::min(MaxAlignment, TypeAlignment));
3108 bool InvertPCond =
false, InvertQCond =
false;
3114 if (QFB == PostBB) {
3133 !HasOnePredAndOneSucc(QFB, QBI->
getParent(), PostBB))
3136 (QTB && !HasOnePredAndOneSucc(QTB, QBI->
getParent(), PostBB)))
3144 for (
auto *BB : {PTB, PFB}) {
3149 PStoreAddresses.
insert(
SI->getPointerOperand());
3151 for (
auto *BB : {QTB, QFB}) {
3156 QStoreAddresses.
insert(
SI->getPointerOperand());
3162 auto &CommonAddresses = PStoreAddresses;
3164 bool Changed =
false;
3165 for (
auto *
Address : CommonAddresses)
3167 PTB, PFB, QTB, QFB, PostBB,
Address, InvertPCond, InvertQCond, DL);
3187 if (BB->getSinglePredecessor()) {
3208 if ((PBI = dyn_cast<BranchInst>(P->
getTerminator())) && PBI != BI &&
3225 if (
auto *CE = dyn_cast<ConstantExpr>(BI->
getCondition()))
3240 if (&*BB->instructionsWithoutDebug().begin() != BI)
3275 unsigned NumPhis = 0;
3281 PHINode *PN = cast<PHINode>(II);
3307 if (OtherDest == BB) {
3313 OtherDest = InfLoopBlock;
3325 PBICond = Builder.
CreateNot(PBICond, PBICond->getName() +
".not");
3340 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3341 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3344 SuccTrueWeight, SuccFalseWeight);
3346 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3347 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3348 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3349 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3353 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3354 PredOther * SuccCommon,
3355 PredOther * SuccOther};
3371 Value *BIV = PN.getIncomingValueForBlock(BB);
3372 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->
getParent());
3373 Value *PBIV = PN.getIncomingValue(PBBIdx);
3378 PN.setIncomingValue(PBBIdx, NV);
3384 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3385 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3386 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3387 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3390 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3391 PredOther * SuccCommon};
3422 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB :
nullptr;
3427 if (Succ == KeepEdge1)
3428 KeepEdge1 =
nullptr;
3429 else if (Succ == KeepEdge2)
3430 KeepEdge2 =
nullptr;
3440 if (!KeepEdge1 && !KeepEdge2) {
3441 if (TrueBB == FalseBB)
3449 if (TrueWeight != FalseWeight)
3452 }
else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3480 if (!TrueVal || !FalseVal)
3489 uint32_t TrueWeight = 0, FalseWeight = 0;
3545 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
3561 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3564 SwitchInst *
SI = cast<SwitchInst>(Pred->getTerminator());
3573 assert(VVal &&
"Should have a unique destination value");
3581 return requestResimplify();
3597 return requestResimplify();
3604 if (PHIUse ==
nullptr || PHIUse != &SuccBlock->
front() ||
3631 Weights[0] = (Weights[0] + 1) >> 1;
3632 Weights.push_back(Weights[0]);
3662 ConstantComparesGatherer ConstantCompare(Cond, DL);
3665 Value *CompVal = ConstantCompare.CompValue;
3666 unsigned UsedICmps = ConstantCompare.UsedICmps;
3667 Value *ExtraCase = ConstantCompare.Extra;
3677 bool TrueWhenEqual = (Cond->
getOpcode() == Instruction::Or);
3686 if (ExtraCase && Values.
size() < 2)
3701 <<
" cases into SWITCH. BB is:\n" 3725 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain unhandled condition: " << *ExtraCase
3726 <<
"\nEXTRABB = " << *BB);
3741 for (
unsigned i = 0, e = Values.
size(); i != e; ++i)
3742 New->
addCase(Values[i], EdgeBB);
3748 PHINode *PN = cast<PHINode>(BBI);
3750 for (
unsigned i = 0, e = Values.
size() - 1; i != e; ++i)
3757 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain result is:\n" << *BB <<
'\n');
3763 return SimplifyCommonResume(RI);
3767 return SimplifySingleResume(RI);
3773 bool SimplifyCFGOpt::SimplifyCommonResume(
ResumeInst *RI) {
3781 if (!isa<DbgInfoIntrinsic>(I))
3785 auto *PhiLPInst = cast<PHINode>(RI->
getValue());
3788 for (
unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3790 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3791 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3795 if (IncomingBB->getUniqueSuccessor() != BB)
3800 if (IncomingValue != LandingPad)
3805 I = IncomingBB->getFirstNonPHI()->getIterator();
3806 E = IncomingBB->getTerminator()->getIterator();
3808 if (!isa<DbgInfoIntrinsic>(I)) {
3814 TrivialUnwindBlocks.
insert(IncomingBB);
3818 if (TrivialUnwindBlocks.
empty())
3822 for (
auto *TrivialBB : TrivialUnwindBlocks) {
3826 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3840 TrivialBB->getTerminator()->eraseFromParent();
3848 return !TrivialUnwindBlocks.empty();
3852 bool SimplifyCFGOpt::SimplifySingleResume(
ResumeInst *RI) {
3856 "Resume must unwind the exception that caused control to here");
3861 if (!isa<DbgInfoIntrinsic>(I))
3872 LoopHeaders->erase(BB);
3905 switch (IntrinsicID) {
3932 PHINode *DestPN = cast<PHINode>(
I);
3954 if (SrcPN && SrcPN->
getParent() == BB) {
3959 SrcIdx != SrcE; ++SrcIdx) {
3980 PHINode *PN = cast<PHINode>(I++);
4000 if (UnwindDest ==
nullptr) {
4028 if (!SuccessorCleanupPad)
4037 SuccessorCleanupPad->eraseFromParent();
4073 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4074 if (BI->isUnconditional())
4083 while (!UncondBranchPreds.
empty()) {
4086 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
4094 LoopHeaders->erase(BB);
4104 while (!CondBranchPreds.
empty()) {
4119 bool Changed =
false;
4129 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4132 if (BBI->mayHaveSideEffects()) {
4133 if (
auto *
SI = dyn_cast<StoreInst>(BBI)) {
4134 if (
SI->isVolatile())
4136 }
else if (
auto *LI = dyn_cast<LoadInst>(BBI)) {
4137 if (LI->isVolatile())
4139 }
else if (
auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4140 if (RMWI->isVolatile())
4142 }
else if (
auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4143 if (CXI->isVolatile())
4145 }
else if (isa<CatchPadInst>(BBI)) {
4153 }
else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4154 !isa<LandingPadInst>(BBI)) {
4164 if (!BBI->use_empty())
4166 BBI->eraseFromParent();
4172 if (&BB->
front() != UI)
4176 for (
unsigned i = 0, e = Preds.
size(); i != e; ++i) {
4179 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
4180 if (BI->isUnconditional()) {
4181 if (BI->getSuccessor(0) == BB) {
4187 if (BI->getSuccessor(0) == BB) {
4188 Builder.
CreateBr(BI->getSuccessor(1));
4190 }
else if (BI->getSuccessor(1) == BB) {
4191 Builder.
CreateBr(BI->getSuccessor(0));
4196 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TI)) {
4197 for (
auto i =
SI->case_begin(), e =
SI->case_end(); i != e;) {
4198 if (i->getCaseSuccessor() != BB) {
4203 i =
SI->removeCase(i);
4207 }
else if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4208 if (II->getUnwindDest() == BB) {
4212 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4213 if (CSI->getUnwindDest() == BB) {
4220 E = CSI->handler_end();
4223 CSI->removeHandler(I);
4229 if (CSI->getNumHandlers() == 0) {
4231 if (CSI->hasUnwindDest()) {
4245 }
else if (isa<CleanupReturnInst>(TI)) {
4256 LoopHeaders->erase(BB);
4268 for (
size_t I = 1,
E = Cases.
size(); I !=
E; ++
I) {
4269 if (Cases[I - 1]->getValue() != Cases[
I]->getValue() + 1)
4289 for (
auto Case : SI->
cases()) {
4293 if (Dest == DestA) {
4299 if (Dest == DestB) {
4307 "Single-destination switch should have been folded.");
4310 assert(!CasesB.
empty() &&
"There must be non-default cases.");
4318 ContiguousCases = &CasesA;
4319 ContiguousDest = DestA;
4322 ContiguousCases = &CasesB;
4323 ContiguousDest = DestB;
4340 if (NumCases->isNullValue() && !ContiguousCases->empty())
4351 uint64_t TrueWeight = 0;
4352 uint64_t FalseWeight = 0;
4353 for (
size_t I = 0,
E = Weights.
size(); I !=
E; ++
I) {
4355 TrueWeight += Weights[I];
4357 FalseWeight += Weights[
I];
4359 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4368 for (
auto BBI = ContiguousDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4369 unsigned PreviousEdges = ContiguousCases->size();
4372 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4373 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4375 for (
auto BBI = OtherDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4376 unsigned PreviousEdges = SI->
getNumCases() - ContiguousCases->size();
4379 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4380 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4401 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4405 for (
auto &Case : SI->
cases()) {
4406 const APInt &CaseVal = Case.getCaseValue()->getValue();
4409 DeadCases.
push_back(Case.getCaseValue());
4421 const unsigned NumUnknownBits =
4423 assert(NumUnknownBits <= Bits);
4424 if (HasDefault && DeadCases.
empty() &&
4425 NumUnknownBits < 64 &&
4449 "Case was not found. Probably mistake in DeadCases forming.");
4451 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.
back());
4456 CaseI->getCaseSuccessor()->removePredecessor(SI->
getParent());
4459 if (HasWeight && Weights.
size() >= 2) {
4464 return !DeadCases.empty();
4486 int Idx = PHI.getBasicBlockIndex(BB);
4487 assert(Idx >= 0 &&
"PHI has no entry for predecessor?");
4489 Value *InValue = PHI.getIncomingValue(Idx);
4490 if (InValue != CaseValue)
4506 ForwardingNodesMap ForwardingNodes;
4508 bool Changed =
false;
4509 for (
auto &Case : SI->
cases()) {
4511 BasicBlock *CaseDest = Case.getCaseSuccessor();
4530 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4531 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4532 count(Phi.blocks(), SwitchBlock) == 1) {
4541 ForwardingNodes[Phi].push_back(PhiIdx);
4544 for (
auto &ForwardingNode : ForwardingNodes) {
4545 PHINode *Phi = ForwardingNode.first;
4547 if (Indexes.
size() < 2)
4550 for (
int Index : Indexes)
4566 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(
C) &&
4567 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(
C) &&
4568 !isa<UndefValue>(C) && !isa<ConstantExpr>(
C))
4572 if (!CE->isGEPWithNoNotionalOverIndexing())
4589 if (
Constant *
C = dyn_cast<Constant>(V))
4591 return ConstantPool.
lookup(V);
4620 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4662 if (
PHINode *Phi = dyn_cast<PHINode>(User))
4663 if (Phi->getIncomingBlock(
Use) == CaseDest)
4668 ConstantPool.
insert(std::make_pair(&I,
C));
4676 *CommonDest = CaseDest;
4678 if (CaseDest != *CommonDest)
4682 for (
PHINode &PHI : (*CommonDest)->phis()) {
4683 int Idx = PHI.getBasicBlockIndex(Pred);
4696 Res.push_back(std::make_pair(&PHI, ConstVal));
4699 return Res.size() > 0;
4705 SwitchCaseResultVectorTy &UniqueResults,
4707 for (
auto &I : UniqueResults) {
4708 if (I.first == Result) {
4709 I.second.push_back(CaseVal);
4710 return I.second.size();
4713 UniqueResults.push_back(
4724 SwitchCaseResultVectorTy &UniqueResults,
4727 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
4728 for (
auto &I : SI->
cases()) {
4738 if (Results.size() > 1)
4742 const uintptr_t NumCasesForResult =
4746 if (NumCasesForResult > MaxCasesPerResult)
4750 if (UniqueResults.size() > MaxUniqueResults)
4755 PHI = Results[0].first;
4756 else if (PHI != Results[0].
first)
4767 DefaultResults.size() == 1 ? DefaultResults.begin()->second :
nullptr;
4768 if ((!DefaultResult &&
4789 assert(ResultVector.size() == 2 &&
4790 "We should have exactly two unique results at this point");
4793 if (ResultVector[0].
second.size() == 1 &&
4794 ResultVector[1].second.size() == 1) {
4795 ConstantInt *
const FirstCase = ResultVector[0].second[0];
4796 ConstantInt *
const SecondCase = ResultVector[1].second[0];
4798 bool DefaultCanTrigger = DefaultResult;
4799 Value *SelectValue = ResultVector[1].first;
4800 if (DefaultCanTrigger) {
4801 Value *
const ValueCompare =
4802 Builder.
CreateICmpEQ(Condition, SecondCase,
"switch.selectcmp");
4804 DefaultResult,
"switch.select");
4806 Value *
const ValueCompare =
4807 Builder.
CreateICmpEQ(Condition, FirstCase,
"switch.selectcmp");
4809 SelectValue,
"switch.select");
4848 SwitchCaseResultVectorTy UniqueResults;
4854 if (UniqueResults.size() != 2)
4856 assert(PHI !=
nullptr &&
"PHI for value select not found");
4859 Value *SelectValue =
4872 class SwitchLookupTable {
4887 static bool WouldFitInRegister(
const DataLayout &DL, uint64_t TableSize,
4930 SwitchLookupTable::SwitchLookupTable(
4934 assert(Values.size() &&
"Can't build lookup table without values!");
4935 assert(TableSize >= Values.size() &&
"Can't fit values in table!");
4938 SingleValue = Values.begin()->second;
4944 for (
size_t I = 0,
E = Values.size(); I !=
E; ++
I) {
4949 uint64_t Idx = (CaseVal->
getValue() - Offset->
getValue()).getLimitedValue();
4950 TableContents[Idx] = CaseRes;
4952 if (CaseRes != SingleValue)
4953 SingleValue =
nullptr;
4957 if (Values.size() < TableSize) {
4959 "Need a default value to fill the lookup table holes.");
4961 for (uint64_t I = 0; I < TableSize; ++
I) {
4962 if (!TableContents[I])
4963 TableContents[
I] = DefaultValue;
4966 if (DefaultValue != SingleValue)
4967 SingleValue =
nullptr;
4973 Kind = SingleValueKind;
4979 if (isa<IntegerType>(ValueType)) {
4980 bool LinearMappingPossible =
true;
4983 assert(TableSize >= 2 &&
"Should be a SingleValue table.");
4985 for (uint64_t I = 0; I < TableSize; ++
I) {
4990 LinearMappingPossible =
false;
4995 APInt Dist = Val - PrevVal;
4998 }
else if (Dist != DistToPrev) {
4999 LinearMappingPossible =
false;
5005 if (LinearMappingPossible) {
5006 LinearOffset = cast<ConstantInt>(TableContents[0]);
5008 Kind = LinearMapKind;
5015 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5018 for (uint64_t I = TableSize; I > 0; --
I) {
5021 if (!isa<UndefValue>(TableContents[I - 1])) {
5022 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5023 TableInt |= Val->
getValue().
zext(TableInt.getBitWidth());
5027 BitMapElementTy =
IT;
5039 "switch.table." + FuncName);
5049 case SingleValueKind:
5051 case LinearMapKind: {
5054 false,
"switch.idx.cast");
5055 if (!LinearMultiplier->isOne())
5056 Result = Builder.
CreateMul(Result, LinearMultiplier,
"switch.idx.mult");
5057 if (!LinearOffset->isZero())
5058 Result = Builder.
CreateAdd(Result, LinearOffset,
"switch.offset");
5076 Value *DownShifted =
5077 Builder.
CreateLShr(BitMap, ShiftAmt,
"switch.downshift");
5079 return Builder.
CreateTrunc(DownShifted, BitMapElementTy,
"switch.masked");
5084 uint64_t TableSize =
5085 Array->getInitializer()->getType()->getArrayNumElements();
5086 if (TableSize > (1ULL << (IT->
getBitWidth() - 1)))
5089 "switch.tableidx.zext");
5093 GEPIndices,
"switch.gep");
5094 return Builder.
CreateLoad(GEP,
"switch.load");
5100 bool SwitchLookupTable::WouldFitInRegister(
const DataLayout &DL,
5102 Type *ElementType) {
5110 if (TableSize >= UINT_MAX /
IT->getBitWidth())
5124 bool AllTablesFitInRegister =
true;
5125 bool HasIllegalType =
false;
5126 for (
const auto &I : ResultTypes) {
5127 Type *Ty = I.second;
5130 HasIllegalType = HasIllegalType || !TTI.
isTypeLegal(Ty);
5133 AllTablesFitInRegister =
5134 AllTablesFitInRegister &&
5135 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5140 if (HasIllegalType && !AllTablesFitInRegister)
5145 if (AllTablesFitInRegister)
5181 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5201 DefaultValue, CmpOp1,
true);
5202 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5207 for (
auto ValuePair : Values) {
5209 ValuePair.second, CmpOp1,
true);
5210 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5212 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5213 "Expect true or false as compare result.");
5227 if (DefaultConst == FalseConst) {
5230 ++NumTableCmpReuses;
5233 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5237 ++NumTableCmpReuses;
5253 (Fn->getFnAttribute(
"no-jump-tables").getValueAsString() ==
"true"))
5287 MinCaseVal = CaseVal;
5289 MaxCaseVal = CaseVal;
5294 if (!
GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5299 for (
const auto &I : Results) {
5302 if (!ResultLists.
count(PHI))
5304 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5310 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5313 uint64_t NumResults = ResultLists[PHIs[0]].
size();
5316 bool TableHasHoles = (NumResults < TableSize);
5321 bool HasDefaultResults =
5323 DefaultResultsList, DL, TTI);
5325 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5330 if (!DL.fitsInLegalInteger(TableSize))
5334 for (
const auto &I : DefaultResultsList) {
5337 DefaultResults[PHI] = Result;
5360 uint64_t MaxTableSize = CaseSize > 63 ?
UINT64_MAX : 1ULL << CaseSize;
5361 assert(MaxTableSize >= TableSize &&
5362 "It is impossible for a switch to have more entries than the max " 5363 "representable value of its input integer type's size.");
5368 const bool DefaultIsReachable =
5370 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5373 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5391 MaskBB->
setName(
"switch.hole_check");
5398 APInt MaskInt(TableSizePowOf2, 0);
5399 APInt One(TableSizePowOf2, 1);
5401 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5402 for (
size_t I = 0,
E = ResultList.size(); I !=
E; ++
I) {
5403 uint64_t Idx = (ResultList[
I].first->getValue() - MinCaseVal->
getValue())
5405 MaskInt |= One << Idx;
5415 Value *Shifted = Builder.
CreateLShr(TableMask, MaskIndex,
"switch.shifted");
5424 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5431 bool ReturnedEarly =
false;
5433 const ResultListTy &ResultList = ResultLists[PHI];
5436 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5438 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5441 Value *Result = Table.BuildLookup(TableIndex, Builder);
5445 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5448 ReturnedEarly =
true;
5454 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5462 PHI->addIncoming(Result, LookupBB);
5480 ++NumLookupTablesHoles;
5486 uint64_t Diff = (uint64_t)Values.
back() - (uint64_t)Values.
front();
5487 uint64_t Range = Diff + 1;
5488 uint64_t NumCases = Values.
size();
5490 uint64_t MinDensity = 40;
5492 return NumCases * 100 >= Range * MinDensity;
5507 if (CondTy->getIntegerBitWidth() > 64 ||
5520 for (
auto &
C : SI->
cases())
5521 Values.
push_back(
C.getCaseValue()->getValue().getSExtValue());
5529 int64_t
Base = Values[0];
5530 for (
auto &V : Values)
5531 V -= (uint64_t)(Base);
5537 for (
auto &V : Values)
5552 unsigned Shift =
Log2_64(GCD);
5553 for (
auto &V : Values)
5554 V = (int64_t)((uint64_t)V >> Shift);
5574 auto *LShr = Builder.
CreateLShr(Sub, ShiftC);
5575 auto *Shl = Builder.
CreateShl(Sub, Ty->getBitWidth() - Shift);
5576 auto *Rot = Builder.
CreateOr(LShr, Shl);
5579 for (
auto Case : SI->
cases()) {
5580 auto *Orig = Case.getCaseValue();
5581 auto Sub = Orig->getValue() -
APInt(Ty->getBitWidth(), Base);
5591 if (isValueEqualityComparison(SI)) {
5595 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5596 return requestResimplify();
5601 return requestResimplify();
5606 if (FoldValueComparisonIntoPredecessors(SI, Builder))
5607 return requestResimplify();
5612 return requestResimplify();
5616 return requestResimplify();
5619 return requestResimplify();
5622 return requestResimplify();
5629 if (Options.ConvertSwitchToLookupTable &&
5631 return requestResimplify();
5634 return requestResimplify();
5641 bool Changed =
false;
5672 return requestResimplify();
5704 if (isa<PHINode>(*Succ->begin()))
5708 if (BB == OtherPred)
5714 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5727 "unexpected successor");
5733 for (
auto I = OtherPred->begin(),
E = OtherPred->end(); I !=
E;) {
5736 if (isa<DbgInfoIntrinsic>(Inst))
5743 Succ->removePredecessor(BB);
5754 bool SimplifyCFGOpt::SimplifyUncondBranch(
BranchInst *BI,
5766 bool NeedCanonicalLoop =
5767 Options.NeedCanonicalLoop &&
5769 (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5777 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5779 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5781 if (I->isTerminator() &&
5782 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
5789 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5800 return requestResimplify();
5808 if (!PPred || (PredPred && PredPred != PPred))
5822 if (isValueEqualityComparison(BI)) {
5827 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5828 return requestResimplify();
5834 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5835 return requestResimplify();
5836 }
else if (&*I == cast<Instruction>(BI->
getCondition())) {
5838 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5839 return requestResimplify();
5857 return requestResimplify();
5864 return requestResimplify();
5873 return requestResimplify();
5881 return requestResimplify();
5890 return requestResimplify();
5898 return requestResimplify();
5902 if (
BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5905 return requestResimplify();
5910 if (
BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5913 return requestResimplify();
5937 if (i == I->
getParent()->
end() || i->mayHaveSideEffects())
5942 if (
GEP->getPointerOperand() ==
I)
5950 if (
LoadInst *LI = dyn_cast<LoadInst>(Use))
5951 if (!LI->isVolatile())
5953 LI->getPointerAddressSpace());
5956 if (
StoreInst *SI = dyn_cast<StoreInst>(Use))
5957 if (!SI->isVolatile())
5959 SI->getPointerAddressSpace())) &&
5960 SI->getPointerOperand() ==
I;
5965 CS.getCalledValue() ==
I;
5974 for (
unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
5976 Instruction *
T = PHI.getIncomingBlock(i)->getTerminator();
5978 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
5996 bool SimplifyCFGOpt::simplifyOnce(
BasicBlock *BB) {
5997 bool Changed =
false;
6034 if (
auto *PN = dyn_cast<PHINode>(BB->
begin()))
6035 if (PN->getNumIncomingValues() == 2)
6041 if (SimplifyUncondBranch(BI, Builder))
6044 if (SimplifyCondBranch(BI, Builder))
6047 }
else if (
auto *RI = dyn_cast<ReturnInst>(BB->
getTerminator())) {
6048 if (SimplifyReturn(RI, Builder))
6050 }
else if (
auto *RI = dyn_cast<ResumeInst>(BB->
getTerminator())) {
6051 if (SimplifyResume(RI, Builder))
6053 }
else if (
auto *RI = dyn_cast<CleanupReturnInst>(BB->
getTerminator())) {
6054 if (SimplifyCleanupReturn(RI))
6056 }
else if (
auto *SI = dyn_cast<SwitchInst>(BB->
getTerminator())) {
6057 if (SimplifySwitch(SI, Builder))
6059 }
else if (
auto *UI = dyn_cast<UnreachableInst>(BB->
getTerminator())) {
6060 if (SimplifyUnreachable(UI))
6062 }
else if (
auto *IBI = dyn_cast<IndirectBrInst>(BB->
getTerminator())) {
6063 if (SimplifyIndirectBr(IBI))
6071 bool Changed =
false;
6079 Changed |= simplifyOnce(BB);
6080 }
while (Resimplify);
const T & front() const
front - Get the first element.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Return a value (possibly void), from a function.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Value * getValueOperand()
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
bool cannotDuplicate() const
Determine if the invoke cannot be duplicated.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
This class is the base class for the comparison instructions.
iterator_range< use_iterator > uses()
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
static IntegerType * getInt1Ty(LLVMContext &C)
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
CleanupPadInst * getCleanupPad() const
Convenience accessor.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
uint64_t getZExtValue() const
Get zero extended value.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
const T & back() const
back - Get the last element.
DiagnosticInfoOptimizationBase::Argument NV
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B)
Return the greatest common divisor of the values using Euclid's algorithm.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
This class represents lattice values for constants.
const APInt & getUpper() const
Return the upper value for this range.
void swapSuccessors()
Swap the successors of this branch instruction.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr)
Attempts to merge a block into its predecessor, if possible.
bool isConvergent() const
Determine if the invoke is convergent.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
Optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
static bool isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, Instruction *Cond, SmallVectorImpl< PHINode *> &PhiNodes)
Return true if it is safe and profitable to merge these two terminator instructions together...
static bool removeUndefIntroducingPredecessor(BasicBlock *BB)
If BB has an incoming value that will always trigger undefined behavior (eg.
void push_back(const T &Elt)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
APInt zext(unsigned width) const
Zero extend to a new width.
bool slt(const APInt &RHS) const
Signed less than comparison.
This class represents a function call, abstracting a target machine's calling convention.
static bool GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant *>> &Res, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to determine the resulting constant values in phi nodes at the common destination basic block...
bool isSizeLargerThan(uint64_t MaxSize) const
Value * getCondition() const
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static bool mergeCleanupPad(CleanupReturnInst *RI)
const Value * getTrueValue() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
A cache of @llvm.assume calls within a function.
Like Internal, but omit from symbol table.
Function Alias Analysis Results
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Delete the specified block, which must have no predecessors.
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, const DataLayout &DL)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
void deleteValue()
Delete a pointer to a generic Value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool sgt(const APInt &RHS) const
Signed greather than comparison.
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select)
const Use & getOperandUse(unsigned i) const
static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
static unsigned ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
const MDOperand & getOperand(unsigned I) const
An instruction for reading from memory.
Value * getCondition() const
BasicBlock * getUnwindDest() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
This defines the Use class.
std::size_t countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1...
LLVMContext & getContext() const
Get the context in which this basic block lives.
static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C...
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}{Tru...
static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, const DataLayout &DL)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static ConstantInt * GetConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I)
Check if passing a value to an instruction will cause undefined behavior.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Value * CreateNot(Value *V, const Twine &Name="")
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
bool match(Val *V, const Pattern &P)
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, const TargetTransformInfo &TTI, uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult)
static void GetBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static int ConstantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB)
Return true if we can thread a branch across this block.
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)
Return the specified destination.
APInt operator*(APInt a, uint64_t RHS)
This file implements a class to represent arbitrary precision integral constant values and operations...
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)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
void assign(size_type NumElts, const T &Elt)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void setUnwindDest(BasicBlock *B)
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
A constant value that is initialized with an expression using other constant values.
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
static bool isSwitchDense(ArrayRef< int64_t > Values)
Type * getType() const
All values are typed, get the type of this value.
static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, IRBuilder<> &Builder)
If we found a conditional branch that goes to two returning blocks, try to merge them together into o...
bool insert(const value_type &X)
Insert a new element into the SetVector.
static uintptr_t MapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
unsigned getNumSuccessors() const
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Class to represent array types.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
static void setBranchWeights(SwitchInst *SI, ArrayRef< uint32_t > Weights)
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"))
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
const APInt & getValue() const
Return the constant as an APInt value reference.
static Value * ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
BasicBlock * getBasicBlock() const
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static void EliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block...
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
BasicBlock * getSuccessor(unsigned idx) const
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
static bool SinkCommonCodeFromPredecessors(BasicBlock *BB)
Check whether BB's predecessors end with unconditional branches.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
bool isThreadDependent() const
Return true if the value can vary between threads.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB)
Return true if the given instruction is available in its predecessor block.
bool FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static bool sinkLastInstruction(ArrayRef< BasicBlock *> Blocks)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
bool isIdenticalToWhenDefined(const Instruction *I) const
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags, which may specify conditions under which the instruction's result is undefined.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
static bool HasBranchWeights(const Instruction *I)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
UnreachableInst * CreateUnreachable()
Conditional or Unconditional Branch instruction.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder)
Turn a switch with two reachable destinations into an integer range comparison and branch...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
size_t size() const
size - Get the array size.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Resume the propagation of an exception.
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
Indirect Branch Instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
BasicBlock * getDefaultDest() const
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond, BasicBlock *TrueBB, BasicBlock *FalseBB, uint32_t TrueWeight, uint32_t FalseWeight)
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
Class to represent integer types.
static cl::opt< bool > MergeCondStores("simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores even if an unconditional store does not " "precede - hoist multiple conditional stores into a single " "predicated store"))
bool pred_empty(const BasicBlock *BB)
static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, const DataLayout &DL)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it...
const Function * getFunction() const
Return the function this instruction belongs to.
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
const Value * getCondition() const
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
iterator erase(const_iterator CI)
bool isExceptionalTerminator() const
Value(Type *Ty, unsigned scid)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void sort(IteratorTy Start, IteratorTy End)
static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, AssumptionCache *AC)
If we have a conditional branch on a PHI node value that is defined in the same block as the branch a...
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool isEmptySet() const
Return true if this set contains no members.
static Constant * ConstantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant *> &ConstantPool)
Try to fold instruction I into a constant.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
BasicBlock * getNormalDest() const
const InstListType & getInstList() const
Return the underlying instruction list container.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
This is the shared class of boolean and integer constants.
static bool SafeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, const DataLayout &DL)
The specified branch is a conditional branch.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
This class represents a range of values.
This is the common base class for debug info intrinsics.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Value * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant *>> &Values)
Try to reuse the switch table index compare.
static bool canSinkInstructions(ArrayRef< Instruction *> Insts, DenseMap< Instruction *, SmallVector< Value *, 4 >> &PHIOperands)
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
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 setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
static bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI)
Given a conditional branch that goes to BB1 and BB2, hoist any common code in the two blocks up into ...
void removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
static cl::opt< bool > DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), cl::desc("Duplicate return instructions into unconditional branches"))
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static bool CasesAreContiguous(SmallVectorImpl< ConstantInt *> &Cases)
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
InstListType::iterator iterator
Instruction iterators...
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
iterator insert(iterator I, T &&Elt)
const Value * getFalseValue() const
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
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")))
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static bool isTrivial(const DICompositeType *DCTy)
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, const DataLayout &DL)
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
bool isTokenTy() const
Return true if this is 'token'.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
const APInt & getLower() const
Return the lower value for this range.
Value * getValue() const
Convenience accessor.
bool empty() const
Determine if the SetVector is empty or not.
static bool removeEmptyCleanup(CleanupReturnInst *RI)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool DominatesMergePoint(Value *V, BasicBlock *BB, SmallPtrSetImpl< Instruction *> &AggressiveInsts, unsigned &CostRemaining, const TargetTransformInfo &TTI, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
static bool ValuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, const TargetTransformInfo &TTI)
Speculate a conditional basic block flattening the CFG.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
If the switch is only used to initialize one or more phi nodes in a common successor block with only ...
void setCondition(Value *V)
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
user_iterator user_begin()
LLVM_NODISCARD char front() const
front - Get the first character in the string.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool operator<(int64_t V1, const APSInt &V2)
BasicBlock * getUnwindDest() const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
static bool ForwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void setAlignment(unsigned Align)
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setDefaultDest(BasicBlock *DefaultCase)
succ_range successors(Instruction *I)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static PHINode * FindPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i...
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
bool fitsInLegalInteger(unsigned Width) const
Returns true if the specified type fits in a native integer type supported by the CPU...
bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, const SimplifyCFGOptions &Options={}, SmallPtrSetImpl< BasicBlock *> *LoopHeaders=nullptr)
This function is used to do simplification of a CFG.
static void EraseTerminatorAndDCECond(Instruction *TI)
A set of parameters used to control the transforms in the SimplifyCFG pass.
bool operator==(uint64_t V1, const APInt &V2)
static void FitWeights(MutableArrayRef< uint64_t > Weights)
Keep halving the weights until all can fit in uint32_t.
void setIncomingValue(unsigned i, Value *V)
unsigned getNumOperands() const
Return number of MDNode operands.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
static bool ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallDenseMap< PHINode *, Type *> &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases...
static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block...
void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, BasicBlock *BB)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
static Constant * LookupConstant(Value *V, const SmallDenseMap< Value *, Constant *> &ConstantPool)
If V is a Constant, return it.