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 {
179 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
180 bool SimplifyEqualityComparisonWithOnlyPredecessor(
TerminatorInst *TI,
201 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
225 if (SI1Succs.
count(Succ))
227 PHINode *PN = cast<PHINode>(BBI);
231 FailBlocks->insert(Succ);
258 if (!(Cond->
getOperand(0) == Ci2->getOperand(0) &&
260 !(Cond->
getOperand(0) == Ci2->getOperand(1) &&
268 if (SI1Succs.
count(Succ))
270 PHINode *PN = cast<PHINode>(BBI);
286 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
296 "Instruction is not safe to speculatively execute!");
319 unsigned &CostRemaining,
321 unsigned Depth = 0) {
354 if (!AggressiveInsts)
358 if (AggressiveInsts->
count(I))
375 if (Cost > CostRemaining &&
380 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
389 AggressiveInsts->
insert(I);
406 if (isa<ConstantPointerNull>(V))
411 if (CE->getOpcode() == Instruction::IntToPtr)
412 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
417 return cast<ConstantInt>(
435 struct ConstantComparesGatherer {
439 Value *CompValue =
nullptr;
442 Value *Extra =
nullptr;
448 unsigned UsedICmps = 0;
455 ConstantComparesGatherer(
const ConstantComparesGatherer &) =
delete;
456 ConstantComparesGatherer &
457 operator=(
const ConstantComparesGatherer &) =
delete;
462 bool setValueOnce(
Value *NewVal) {
463 if (CompValue && CompValue != NewVal)
466 return (CompValue !=
nullptr);
480 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
537 if (!setValueOnce(RHSVal))
560 if (!setValueOnce(RHSVal))
589 CandidateVal = RHSVal;
604 if (!setValueOnce(CandidateVal))
620 void gather(
Value *V) {
622 bool isEQ = (I->
getOpcode() == Instruction::Or);
632 while (!DFT.
empty()) {
637 if (I->
getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
646 if (matchInstruction(I, isEQ))
671 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
672 if (BI->isConditional())
673 Cond = dyn_cast<Instruction>(BI->getCondition());
690 if (
SI->getNumSuccessors() *
pred_size(
SI->getParent()) <= 128)
691 CV =
SI->getCondition();
692 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI))
693 if (BI->isConditional() && BI->getCondition()->hasOneUse())
694 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
696 CV = ICI->getOperand(0);
702 Value *
Ptr = PTII->getPointerOperand();
703 if (PTII->getType() == DL.getIntPtrType(Ptr->
getType()))
712 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
713 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
715 Cases.reserve(
SI->getNumCases());
716 for (
auto Case :
SI->cases())
717 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
718 Case.getCaseSuccessor()));
719 return SI->getDefaultDest();
725 Cases.push_back(ValueEqualityComparisonCase(
734 std::vector<ValueEqualityComparisonCase> &Cases) {
735 Cases.erase(
std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
740 std::vector<ValueEqualityComparisonCase> &C2) {
741 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *
V2 = &C2;
744 if (V1->size() > V2->size())
749 if (V1->size() == 1) {
752 for (
unsigned i = 0, e = V2->size(); i != e; ++i)
753 if (TheVal == (*V2)[i].
Value)
760 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
761 while (i1 != e1 && i2 != e2) {
764 if ((*V1)[i1].Value < (*V2)[i2].Value)
787 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
791 if (TrueWeight || FalseWeight)
793 .createBranchWeights(TrueWeight, FalseWeight);
802 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
808 Value *ThisVal = isValueEqualityComparison(TI);
809 assert(ThisVal &&
"This isn't a value comparison!!");
810 if (ThisVal != PredVal)
817 std::vector<ValueEqualityComparisonCase> PredCases;
819 GetValueEqualityComparisonCases(Pred->
getTerminator(), PredCases);
823 std::vector<ValueEqualityComparisonCase> ThisCases;
824 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
836 if (isa<BranchInst>(TI)) {
839 assert(ThisCases.size() == 1 &&
"Branch can only have one case!");
845 ThisCases[0].Dest->removePredecessor(TI->
getParent());
848 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
858 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
859 DeadCases.
insert(PredCases[i].Value);
862 <<
"Through successor TI: " << *TI);
876 if (DeadCases.count(i->getCaseValue())) {
878 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
881 i->getCaseSuccessor()->removePredecessor(TI->
getParent());
885 if (HasWeight && Weights.size() >= 2)
896 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
897 if (PredCases[i].Dest == TIBB) {
900 TIV = PredCases[i].
Value;
902 assert(TIV &&
"No edge from pred to succ?");
907 for (
unsigned i = 0, e = ThisCases.size(); i != e; ++i)
908 if (ThisCases[i].
Value == TIV) {
909 TheRealDest = ThisCases[i].Dest;
915 TheRealDest = ThisDef;
920 if (Succ != CheckEdge)
930 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
942 struct ConstantIntOrdering {
963 return MDS->getString().equals(
"branch_weights");
983 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
985 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
993 uint64_t Max = *std::max_element(Weights.
begin(), Weights.
end());
994 if (Max > UINT_MAX) {
996 for (uint64_t &
I : Weights)
1005 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(
TerminatorInst *TI,
1008 Value *CV = isValueEqualityComparison(TI);
1009 assert(CV &&
"Not a comparison?");
1010 bool Changed =
false;
1013 while (!Preds.
empty()) {
1018 Value *PCV = isValueEqualityComparison(PTI);
1020 if (PCV == CV && TI != PTI) {
1023 for (
auto *Succ : FailBlocks) {
1030 std::vector<ValueEqualityComparisonCase> BBCases;
1031 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1033 std::vector<ValueEqualityComparisonCase> PredCases;
1034 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1046 if (PredHasWeights) {
1049 if (Weights.
size() != 1 + PredCases.size())
1050 PredHasWeights = SuccHasWeights =
false;
1051 }
else if (SuccHasWeights)
1055 Weights.
assign(1 + PredCases.size(), 1);
1058 if (SuccHasWeights) {
1061 if (SuccWeights.
size() != 1 + BBCases.size())
1062 PredHasWeights = SuccHasWeights =
false;
1063 }
else if (PredHasWeights)
1064 SuccWeights.
assign(1 + BBCases.size(), 1);
1066 if (PredDefault == BB) {
1069 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1070 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1071 if (PredCases[i].Dest != BB)
1072 PTIHandled.insert(PredCases[i].
Value);
1075 std::swap(PredCases[i], PredCases.back());
1077 if (PredHasWeights || SuccHasWeights) {
1079 Weights[0] += Weights[i + 1];
1084 PredCases.pop_back();
1090 if (PredDefault != BBDefault) {
1092 PredDefault = BBDefault;
1096 unsigned CasesFromPred = Weights.
size();
1097 uint64_t ValidTotalSuccWeight = 0;
1098 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1099 if (!PTIHandled.count(BBCases[i].Value) &&
1100 BBCases[i].Dest != BBDefault) {
1101 PredCases.push_back(BBCases[i]);
1102 NewSuccessors.
push_back(BBCases[i].Dest);
1103 if (SuccHasWeights || PredHasWeights) {
1107 Weights.
push_back(Weights[0] * SuccWeights[i + 1]);
1108 ValidTotalSuccWeight += SuccWeights[i + 1];
1112 if (SuccHasWeights || PredHasWeights) {
1113 ValidTotalSuccWeight += SuccWeights[0];
1115 for (
unsigned i = 1; i < CasesFromPred; ++i)
1116 Weights[i] *= ValidTotalSuccWeight;
1118 Weights[0] *= SuccWeights[0];
1124 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1125 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1126 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1127 if (PredCases[i].Dest == BB) {
1130 if (PredHasWeights || SuccHasWeights) {
1131 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1136 std::swap(PredCases[i], PredCases.back());
1137 PredCases.pop_back();
1144 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1145 if (PTIHandled.count(BBCases[i].Value)) {
1147 if (PredHasWeights || SuccHasWeights)
1149 PredCases.push_back(BBCases[i]);
1150 NewSuccessors.
push_back(BBCases[i].Dest);
1158 if (PredHasWeights || SuccHasWeights)
1160 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1168 for (
BasicBlock *NewSuccessor : NewSuccessors)
1182 for (ValueEqualityComparisonCase &V : PredCases)
1183 NewSI->
addCase(V.Value, V.Dest);
1185 if (PredHasWeights || SuccHasWeights) {
1202 if (!InfLoopBlock) {
1224 for (
const PHINode &PN : Succ->phis()) {
1225 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1226 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1227 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1258 while (isa<DbgInfoIntrinsic>(I1))
1260 while (isa<DbgInfoIntrinsic>(I2))
1269 bool Changed =
false;
1273 if (isa<TerminatorInst>(I1))
1274 goto HoistTerminator;
1284 if (C1->isMustTailCall() != C2->isMustTailCall())
1290 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1291 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1306 if (!I2->use_empty())
1307 I2->replaceAllUsesWith(I1);
1325 I2->eraseFromParent();
1335 while (isa<DbgInfoIntrinsic>(I1))
1337 while (isa<DbgInfoIntrinsic>(I2))
1350 for (
PHINode &PN : Succ->phis()) {
1351 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1352 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1374 I2->replaceAllUsesWith(NT);
1383 std::map<std::pair<Value *, Value *>,
SelectInst *> InsertedSelects;
1385 for (
PHINode &PN : Succ->phis()) {
1386 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1387 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1393 SelectInst *&
SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1395 SI = cast<SelectInst>(
1397 BB1V->
getName() +
"." + BB2V->getName(), BI));
1400 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1401 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1402 PN.setIncomingValue(i, SI);
1425 for (
auto *I : Insts) {
1427 if (isa<PHINode>(I) || I->
isEHPad() || isa<AllocaInst>(
I) ||
1434 if (
const auto *
C = dyn_cast<CallInst>(I))
1440 if (!isa<StoreInst>(I) && !I->
hasOneUse())
1445 for (
auto *I : Insts)
1453 if (!isa<StoreInst>(I0)) {
1457 auto *U = cast<Instruction>(*I->
user_begin());
1459 PNUse->getParent() == Succ &&
1460 PNUse->getIncomingValueForBlock(I->
getParent()) == I) ||
1483 for (
unsigned OI = 0, OE = I0->
getNumOperands(); OI != OE; ++OI) {
1492 if (!
all_of(Insts, SameAsI0)) {
1497 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
1501 for (
auto *I : Insts)
1512 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1517 for (
auto *BB : Blocks) {
1521 }
while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1522 if (!isa<DbgInfoIntrinsic>(I))
1531 if (!isa<StoreInst>(I0)) {
1534 auto *U = cast<Instruction>(*I->
user_begin());
1560 assert(!
Op->getType()->isTokenTy() &&
"Can't PHI tokens!");
1562 Op->getName() +
".sink", &BBEnd->front());
1563 for (
auto *I : Insts)
1572 I0->
moveBefore(&*BBEnd->getFirstInsertionPt());
1575 for (
auto *I : Insts)
1589 if (!isa<StoreInst>(I0)) {
1595 PN->replaceAllUsesWith(I0);
1596 PN->eraseFromParent();
1600 for (
auto *I : Insts)
1617 class LockstepReverseIterator {
1630 for (
auto *BB : Blocks) {
1632 for (Inst = Inst->
getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1643 bool isValid()
const {
1650 for (
auto *&Inst : Insts) {
1651 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1652 Inst = Inst->getPrevNode();
1717 auto *
T =
B->getTerminator();
1718 if (isa<BranchInst>(
T) && cast<BranchInst>(
T)->isUnconditional())
1720 else if ((isa<BranchInst>(
T) || isa<SwitchInst>(
T)) && !Cond)
1725 if (UnconditionalPreds.
size() < 2)
1728 bool Changed =
false;
1735 unsigned ScanIdx = 0;
1738 LockstepReverseIterator LRI(UnconditionalPreds);
1739 while (LRI.isValid() &&
1741 LLVM_DEBUG(
dbgs() <<
"SINK: instruction can be sunk: " << *(*LRI)[0]
1743 InstructionsToSink.
insert((*LRI).begin(), (*LRI).end());
1748 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1749 unsigned NumPHIdValues = 0;
1750 for (
auto *I : *LRI)
1751 for (
auto *V : PHIOperands[I])
1752 if (InstructionsToSink.
count(V) == 0)
1754 LLVM_DEBUG(
dbgs() <<
"SINK: #phid values: " << NumPHIdValues <<
"\n");
1755 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.
size();
1756 if ((NumPHIdValues % UnconditionalPreds.
size()) != 0)
1759 return NumPHIInsts <= 1;
1762 if (ScanIdx > 0 && Cond) {
1770 bool Profitable =
false;
1771 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1803 for (
unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1805 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1811 if (!ProfitableToSinkInstruction(LRI)) {
1814 dbgs() <<
"SINK: stopping here, too many PHIs would be created!\n");
1865 unsigned MaxNumInstToLookAt = 9;
1867 if (!MaxNumInstToLookAt)
1869 --MaxNumInstToLookAt;
1872 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1875 if (
auto *
SI = dyn_cast<StoreInst>(&CurI)) {
1877 if (
SI->getPointerOperand() == StorePtr)
1879 return SI->getValueOperand();
1928 if (isa<FCmpInst>(BrCond))
1936 bool Invert =
false;
1952 unsigned SpeculationCost = 0;
1953 Value *SpeculatedStoreValue =
nullptr;
1956 BBE = std::prev(ThenBB->
end());
1957 BBI != BBE; ++BBI) {
1960 if (isa<DbgInfoIntrinsic>(I)) {
1968 if (SpeculationCost > 1)
1974 I, BB, ThenBB, EndBB))))
1976 if (!SpeculatedStoreValue &&
1982 if (SpeculatedStoreValue)
1983 SpeculatedStore = cast<StoreInst>(
I);
1993 ++SinkCandidateUseCounts[OpI];
2001 I = SinkCandidateUseCounts.begin(),
2002 E = SinkCandidateUseCounts.end();
2006 if (SpeculationCost > 1)
2011 bool HaveRewritablePHIs =
false;
2013 Value *OrigV = PN.getIncomingValueForBlock(BB);
2014 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2026 HaveRewritablePHIs =
true;
2029 if (!OrigCE && !ThenCE)
2039 if (OrigCost + ThenCost > MaxCost)
2047 if (SpeculationCost > 1)
2053 if (!HaveRewritablePHIs && !(
HoistCondStores && SpeculatedStoreValue))
2057 LLVM_DEBUG(
dbgs() <<
"SPECULATIVELY EXECUTING BB" << *ThenBB <<
"\n";);
2060 if (SpeculatedStoreValue) {
2063 Value *FalseV = SpeculatedStoreValue;
2067 BrCond, TrueV, FalseV,
"spec.store.select", BI);
2075 for (
auto &I : *ThenBB)
2080 ThenBB->begin(), std::prev(ThenBB->end()));
2085 unsigned OrigI = PN.getBasicBlockIndex(BB);
2086 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2087 Value *OrigV = PN.getIncomingValue(OrigI);
2088 Value *ThenV = PN.getIncomingValue(ThenI);
2097 Value *TrueV = ThenV, *FalseV = OrigV;
2101 BrCond, TrueV, FalseV,
"spec.select", BI);
2102 PN.setIncomingValue(OrigI, V);
2103 PN.setIncomingValue(ThenI, V);
2129 if (UI->
getParent() != BB || isa<PHINode>(UI))
2204 if (
PHINode *PN = dyn_cast<PHINode>(BBI)) {
2211 N->
setName(BBI->getName() +
".c");
2216 if (PI != TranslateMap.
end())
2222 if (!BBI->use_empty())
2223 TranslateMap[&*BBI] = V;
2229 if (!BBI->use_empty())
2230 TranslateMap[&*BBI] = N;
2237 if (
auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2238 if (II->getIntrinsicID() == Intrinsic::assume)
2277 isa<ConstantInt>(IfCond))
2285 unsigned NumPhis = 0;
2300 PHINode *PN = cast<PHINode>(II++);
2308 MaxCostVal0, TTI) ||
2325 isa<BinaryOperator>(IfCond)))
2335 if (cast<BranchInst>(IfBlock1->
getTerminator())->isConditional()) {
2341 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2349 if (cast<BranchInst>(IfBlock2->
getTerminator())->isConditional()) {
2355 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2364 <<
" T: " << IfTrue->
getName()
2365 <<
" F: " << IfFalse->
getName() <<
"\n");
2375 for (
auto &I : *IfBlock1)
2378 IfBlock1->getInstList(), IfBlock1->begin(),
2379 IfBlock1->getTerminator()->getIterator());
2382 for (
auto &I : *IfBlock2)
2385 IfBlock2->getInstList(), IfBlock2->begin(),
2386 IfBlock2->getTerminator()->getIterator());
2418 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2424 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2433 if (FalseRet->getNumOperands() == 0) {
2434 TrueSucc->removePredecessor(BI->
getParent());
2444 Value *FalseValue = FalseRet->getReturnValue();
2447 if (
PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2448 if (TVPN->getParent() == TrueSucc)
2449 TrueValue = TVPN->getIncomingValueForBlock(BI->
getParent());
2450 if (
PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2451 if (FVPN->getParent() == FalseSucc)
2452 FalseValue = FVPN->getIncomingValueForBlock(BI->
getParent());
2459 if (
ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2462 if (
ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2468 TrueSucc->removePredecessor(BI->
getParent());
2475 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2476 }
else if (isa<UndefValue>(TrueValue)) {
2477 TrueValue = FalseValue;
2480 Builder.
CreateSelect(BrCond, TrueValue, FalseValue,
"retval", BI);
2489 LLVM_DEBUG(
dbgs() <<
"\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2490 <<
"\n " << *BI <<
"NewRet = " << *RI <<
"TRUEBLOCK: " 2491 << *TrueSucc <<
"FALSEBLOCK: " << *FalseSucc);
2501 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2519 uint64_t &PredTrueWeight,
2520 uint64_t &PredFalseWeight,
2521 uint64_t &SuccTrueWeight,
2522 uint64_t &SuccFalseWeight) {
2523 bool PredHasWeights =
2525 bool SuccHasWeights =
2527 if (PredHasWeights || SuccHasWeights) {
2528 if (!PredHasWeights)
2529 PredTrueWeight = PredFalseWeight = 1;
2530 if (!SuccHasWeights)
2531 SuccTrueWeight = SuccFalseWeight = 1;
2553 if (
BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2554 if (PBI->isConditional() &&
2561 if (isa<CmpInst>(Curr)) {
2575 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2583 while (isa<DbgInfoIntrinsic>(CondIt))
2594 unsigned NumBonusInsts = 0;
2595 for (
auto I = BB->
begin(); Cond != &*
I; ++
I) {
2597 if (isa<DbgInfoIntrinsic>(I))
2603 if (User ==
nullptr || User->
getParent() != BB)
2610 if (NumBonusInsts > BonusInstThreshold)
2626 if (TrueDest == BB || FalseDest == BB)
2645 bool InvertPredCond =
false;
2649 Opc = Instruction::Or;
2651 Opc = Instruction::And;
2653 Opc = Instruction::And;
2654 InvertPredCond =
true;
2656 Opc = Instruction::Or;
2657 InvertPredCond =
true;
2666 LLVM_DEBUG(
dbgs() <<
"FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2670 if (InvertPredCond) {
2673 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
2674 CmpInst *CI = cast<CmpInst>(NewCond);
2692 for (
auto BonusInst = BB->
begin(); Cond != &*BonusInst; ++BonusInst) {
2693 if (isa<DbgInfoIntrinsic>(BonusInst))
2698 VMap[&*BonusInst] = NewBonusInst;
2708 NewBonusInst->
takeName(&*BonusInst);
2709 BonusInst->setName(BonusInst->getName() +
".old");
2726 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2729 SuccTrueWeight, SuccFalseWeight);
2737 NewWeights.
push_back(PredTrueWeight * SuccTrueWeight);
2743 (SuccFalseWeight + SuccTrueWeight) +
2744 PredTrueWeight * SuccFalseWeight);
2756 (SuccFalseWeight + SuccTrueWeight) +
2757 PredFalseWeight * SuccTrueWeight);
2759 NewWeights.
push_back(PredFalseWeight * SuccFalseWeight);
2764 if (NewWeights.
size() == 2) {
2775 for (
unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2777 PHIs[i]->getIncomingValueForBlock(PBI->
getParent()));
2786 MergedCond = cast<Instruction>(
2787 Builder.
CreateBinOp(Instruction::And, NotCond, New,
"and.cond"));
2789 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2790 Instruction::Or, PBI->
getCondition(), MergedCond,
"or.cond"));
2795 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2796 Instruction::And, PBI->
getCondition(), New,
"and.cond"));
2797 if (PBI_C->
isOne()) {
2800 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2801 Instruction::Or, NotCond, MergedCond,
"or.cond"));
2805 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->
getParent()),
2824 if (isa<DbgInfoIntrinsic>(I))
2836 for (
auto *BB : {BB1, BB2}) {
2840 if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
2852 Value *AlternativeV =
nullptr) {
2870 for (
auto I = Succ->
begin(); isa<PHINode>(
I); ++
I)
2871 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2872 PHI = cast<PHINode>(
I);
2878 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2887 if (!AlternativeV &&
2888 (!isa<Instruction>(V) || cast<Instruction>(V)->
getParent() != BB))
2903 bool InvertPCond,
bool InvertQCond,
2905 auto IsaBitcastOfPointerType = [](
const Instruction &
I) {
2919 for (
auto &I : BB->instructionsWithoutDebug()) {
2921 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(
I) ||
2925 else if (isa<TerminatorInst>(I) || IsaBitcastOfPointerType(I))
2936 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2937 !IsWorthwhile(QFB)))
2947 if (!PStore || !QStore)
2968 for (
auto &I : *QFB)
2972 for (
auto &I : *QTB)
2999 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3009 Value *PPred = PStore->
getParent() == PTB ? PCond : QB.CreateNot(PCond);
3010 Value *QPred = QStore->
getParent() == QTB ? QCond : QB.CreateNot(QCond);
3013 PPred = QB.CreateNot(PPred);
3015 QPred = QB.CreateNot(QPred);
3016 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3020 QB.SetInsertPoint(
T);
3021 StoreInst *
SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3028 unsigned TypeAlignment =
3030 unsigned MinAlignment;
3031 unsigned MaxAlignment;
3032 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
3037 if (MinAlignment != 0) {
3040 }
else if (MaxAlignment != 0) {
3043 SI->
setAlignment(std::min(MaxAlignment, TypeAlignment));
3100 bool InvertPCond =
false, InvertQCond =
false;
3106 if (QFB == PostBB) {
3125 !HasOnePredAndOneSucc(QFB, QBI->
getParent(), PostBB))
3128 (QTB && !HasOnePredAndOneSucc(QTB, QBI->
getParent(), PostBB)))
3136 for (
auto *BB : {PTB, PFB}) {
3141 PStoreAddresses.
insert(
SI->getPointerOperand());
3143 for (
auto *BB : {QTB, QFB}) {
3148 QStoreAddresses.
insert(
SI->getPointerOperand());
3154 auto &CommonAddresses = PStoreAddresses;
3156 bool Changed =
false;
3157 for (
auto *
Address : CommonAddresses)
3159 PTB, PFB, QTB, QFB, PostBB,
Address, InvertPCond, InvertQCond, DL);
3179 if (BB->getSinglePredecessor()) {
3200 if ((PBI = dyn_cast<BranchInst>(P->
getTerminator())) && PBI != BI &&
3217 if (
auto *CE = dyn_cast<ConstantExpr>(BI->
getCondition()))
3232 if (&*BB->instructionsWithoutDebug().begin() != BI)
3267 unsigned NumPhis = 0;
3273 PHINode *PN = cast<PHINode>(II);
3299 if (OtherDest == BB) {
3305 OtherDest = InfLoopBlock;
3317 PBICond = Builder.
CreateNot(PBICond, PBICond->getName() +
".not");
3332 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3333 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3336 SuccTrueWeight, SuccFalseWeight);
3338 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3339 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3340 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3341 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3345 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3346 PredOther * SuccCommon,
3347 PredOther * SuccOther};
3363 Value *BIV = PN.getIncomingValueForBlock(BB);
3364 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->
getParent());
3365 Value *PBIV = PN.getIncomingValue(PBBIdx);
3370 PN.setIncomingValue(PBBIdx, NV);
3376 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3377 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3378 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3379 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3382 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3383 PredOther * SuccCommon};
3414 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB :
nullptr;
3419 if (Succ == KeepEdge1)
3420 KeepEdge1 =
nullptr;
3421 else if (Succ == KeepEdge2)
3422 KeepEdge2 =
nullptr;
3432 if (!KeepEdge1 && !KeepEdge2) {
3433 if (TrueBB == FalseBB)
3441 if (TrueWeight != FalseWeight)
3444 }
else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3472 if (!TrueVal || !FalseVal)
3481 uint32_t TrueWeight = 0, FalseWeight = 0;
3554 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3557 SwitchInst *
SI = cast<SwitchInst>(Pred->getTerminator());
3566 assert(VVal &&
"Should have a unique destination value");
3597 if (PHIUse ==
nullptr || PHIUse != &SuccBlock->
front() ||
3624 Weights[0] = (Weights[0] + 1) >> 1;
3625 Weights.push_back(Weights[0]);
3655 ConstantComparesGatherer ConstantCompare(Cond, DL);
3658 Value *CompVal = ConstantCompare.CompValue;
3659 unsigned UsedICmps = ConstantCompare.UsedICmps;
3660 Value *ExtraCase = ConstantCompare.Extra;
3670 bool TrueWhenEqual = (Cond->
getOpcode() == Instruction::Or);
3679 if (ExtraCase && Values.
size() < 2)
3694 <<
" cases into SWITCH. BB is:\n" 3718 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain unhandled condition: " << *ExtraCase
3719 <<
"\nEXTRABB = " << *BB);
3734 for (
unsigned i = 0, e = Values.
size(); i != e; ++i)
3735 New->
addCase(Values[i], EdgeBB);
3741 PHINode *PN = cast<PHINode>(BBI);
3743 for (
unsigned i = 0, e = Values.
size() - 1; i != e; ++i)
3750 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain result is:\n" << *BB <<
'\n');
3756 return SimplifyCommonResume(RI);
3760 return SimplifySingleResume(RI);
3766 bool SimplifyCFGOpt::SimplifyCommonResume(
ResumeInst *RI) {
3774 if (!isa<DbgInfoIntrinsic>(I))
3778 auto *PhiLPInst = cast<PHINode>(RI->
getValue());
3781 for (
unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3783 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3784 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3788 if (IncomingBB->getUniqueSuccessor() != BB)
3793 if (IncomingValue != LandingPad)
3796 bool isTrivial =
true;
3798 I = IncomingBB->getFirstNonPHI()->getIterator();
3799 E = IncomingBB->getTerminator()->getIterator();
3801 if (!isa<DbgInfoIntrinsic>(I)) {
3807 TrivialUnwindBlocks.
insert(IncomingBB);
3811 if (TrivialUnwindBlocks.
empty())
3815 for (
auto *TrivialBB : TrivialUnwindBlocks) {
3819 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3833 TrivialBB->getTerminator()->eraseFromParent();
3841 return !TrivialUnwindBlocks.empty();
3845 bool SimplifyCFGOpt::SimplifySingleResume(
ResumeInst *RI) {
3849 "Resume must unwind the exception that caused control to here");
3854 if (!isa<DbgInfoIntrinsic>(I))
3866 LoopHeaders->
erase(BB);
3898 switch (IntrinsicID) {
3899 case Intrinsic::dbg_declare:
3900 case Intrinsic::dbg_value:
3901 case Intrinsic::dbg_label:
3902 case Intrinsic::lifetime_end:
3925 PHINode *DestPN = cast<PHINode>(
I);
3947 if (SrcPN && SrcPN->
getParent() == BB) {
3952 SrcIdx != SrcE; ++SrcIdx) {
3973 PHINode *PN = cast<PHINode>(I++);
3993 if (UnwindDest ==
nullptr) {
4021 if (!SuccessorCleanupPad)
4030 SuccessorCleanupPad->eraseFromParent();
4066 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4067 if (BI->isUnconditional())
4076 while (!UncondBranchPreds.
empty()) {
4079 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
4088 LoopHeaders->
erase(BB);
4097 while (!CondBranchPreds.
empty()) {
4112 bool Changed =
false;
4122 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4125 if (BBI->mayHaveSideEffects()) {
4126 if (
auto *
SI = dyn_cast<StoreInst>(BBI)) {
4127 if (
SI->isVolatile())
4129 }
else if (
auto *LI = dyn_cast<LoadInst>(BBI)) {
4130 if (LI->isVolatile())
4132 }
else if (
auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4133 if (RMWI->isVolatile())
4135 }
else if (
auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4136 if (CXI->isVolatile())
4138 }
else if (isa<CatchPadInst>(BBI)) {
4146 }
else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4147 !isa<LandingPadInst>(BBI)) {
4157 if (!BBI->use_empty())
4159 BBI->eraseFromParent();
4165 if (&BB->
front() != UI)
4169 for (
unsigned i = 0, e = Preds.
size(); i != e; ++i) {
4172 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
4173 if (BI->isUnconditional()) {
4174 if (BI->getSuccessor(0) == BB) {
4180 if (BI->getSuccessor(0) == BB) {
4181 Builder.
CreateBr(BI->getSuccessor(1));
4183 }
else if (BI->getSuccessor(1) == BB) {
4184 Builder.
CreateBr(BI->getSuccessor(0));
4189 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TI)) {
4190 for (
auto i =
SI->case_begin(), e =
SI->case_end(); i != e;) {
4191 if (i->getCaseSuccessor() != BB) {
4196 i =
SI->removeCase(i);
4200 }
else if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4201 if (II->getUnwindDest() == BB) {
4205 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4206 if (CSI->getUnwindDest() == BB) {
4213 E = CSI->handler_end();
4216 CSI->removeHandler(I);
4222 if (CSI->getNumHandlers() == 0) {
4224 if (CSI->hasUnwindDest()) {
4238 }
else if (isa<CleanupReturnInst>(TI)) {
4250 LoopHeaders->
erase(BB);
4261 for (
size_t I = 1,
E = Cases.
size(); I !=
E; ++
I) {
4262 if (Cases[I - 1]->getValue() != Cases[
I]->getValue() + 1)
4282 for (
auto Case : SI->
cases()) {
4286 if (Dest == DestA) {
4292 if (Dest == DestB) {
4300 "Single-destination switch should have been folded.");
4303 assert(!CasesB.
empty() &&
"There must be non-default cases.");
4311 ContiguousCases = &CasesA;
4312 ContiguousDest = DestA;
4315 ContiguousCases = &CasesB;
4316 ContiguousDest = DestB;
4333 if (NumCases->isNullValue() && !ContiguousCases->empty())
4344 uint64_t TrueWeight = 0;
4345 uint64_t FalseWeight = 0;
4346 for (
size_t I = 0,
E = Weights.
size(); I !=
E; ++
I) {
4348 TrueWeight += Weights[I];
4350 FalseWeight += Weights[
I];
4352 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4361 for (
auto BBI = ContiguousDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4362 unsigned PreviousEdges = ContiguousCases->size();
4365 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4366 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4368 for (
auto BBI = OtherDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4369 unsigned PreviousEdges = SI->
getNumCases() - ContiguousCases->size();
4372 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4373 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4394 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4398 for (
auto &Case : SI->
cases()) {
4399 const APInt &CaseVal = Case.getCaseValue()->getValue();
4402 DeadCases.
push_back(Case.getCaseValue());
4414 const unsigned NumUnknownBits =
4416 assert(NumUnknownBits <= Bits);
4417 if (HasDefault && DeadCases.
empty() &&
4418 NumUnknownBits < 64 &&
4442 "Case was not found. Probably mistake in DeadCases forming.");
4444 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.
back());
4449 CaseI->getCaseSuccessor()->removePredecessor(SI->
getParent());
4452 if (HasWeight && Weights.
size() >= 2) {
4457 return !DeadCases.empty();
4479 int Idx = PHI.getBasicBlockIndex(BB);
4480 assert(Idx >= 0 &&
"PHI has no entry for predecessor?");
4482 Value *InValue = PHI.getIncomingValue(Idx);
4483 if (InValue != CaseValue)
4499 ForwardingNodesMap ForwardingNodes;
4501 bool Changed =
false;
4502 for (
auto &Case : SI->
cases()) {
4504 BasicBlock *CaseDest = Case.getCaseSuccessor();
4523 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4524 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4525 count(Phi.blocks(), SwitchBlock) == 1) {
4534 ForwardingNodes[Phi].push_back(PhiIdx);
4537 for (
auto &ForwardingNode : ForwardingNodes) {
4538 PHINode *Phi = ForwardingNode.first;
4540 if (Indexes.
size() < 2)
4543 for (
int Index : Indexes)
4559 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(
C) &&
4560 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(
C) &&
4561 !isa<UndefValue>(C) && !isa<ConstantExpr>(
C))
4565 if (!CE->isGEPWithNoNotionalOverIndexing())
4582 if (
Constant *
C = dyn_cast<Constant>(V))
4584 return ConstantPool.
lookup(V);
4613 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4640 if (
T->getNumSuccessors() != 1 ||
T->isExceptional())
4643 CaseDest =
T->getSuccessor(0);
4655 if (
PHINode *Phi = dyn_cast<PHINode>(User))
4656 if (Phi->getIncomingBlock(
Use) == CaseDest)
4661 ConstantPool.
insert(std::make_pair(&I,
C));
4669 *CommonDest = CaseDest;
4671 if (CaseDest != *CommonDest)
4675 for (
PHINode &PHI : (*CommonDest)->phis()) {
4676 int Idx = PHI.getBasicBlockIndex(Pred);
4689 Res.push_back(std::make_pair(&PHI, ConstVal));
4692 return Res.size() > 0;
4698 SwitchCaseResultVectorTy &UniqueResults,
4700 for (
auto &I : UniqueResults) {
4701 if (I.first == Result) {
4702 I.second.push_back(CaseVal);
4703 return I.second.size();
4706 UniqueResults.push_back(
4717 SwitchCaseResultVectorTy &UniqueResults,
4720 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
4721 for (
auto &I : SI->
cases()) {
4731 if (Results.size() > 1)
4735 const uintptr_t NumCasesForResult =
4739 if (NumCasesForResult > MaxCasesPerResult)
4743 if (UniqueResults.size() > MaxUniqueResults)
4748 PHI = Results[0].first;
4749 else if (PHI != Results[0].
first)
4760 DefaultResults.size() == 1 ? DefaultResults.begin()->second :
nullptr;
4761 if ((!DefaultResult &&
4782 assert(ResultVector.size() == 2 &&
4783 "We should have exactly two unique results at this point");
4786 if (ResultVector[0].
second.size() == 1 &&
4787 ResultVector[1].second.size() == 1) {
4788 ConstantInt *
const FirstCase = ResultVector[0].second[0];
4789 ConstantInt *
const SecondCase = ResultVector[1].second[0];
4791 bool DefaultCanTrigger = DefaultResult;
4792 Value *SelectValue = ResultVector[1].first;
4793 if (DefaultCanTrigger) {
4794 Value *
const ValueCompare =
4795 Builder.
CreateICmpEQ(Condition, SecondCase,
"switch.selectcmp");
4797 DefaultResult,
"switch.select");
4799 Value *
const ValueCompare =
4800 Builder.
CreateICmpEQ(Condition, FirstCase,
"switch.selectcmp");
4802 SelectValue,
"switch.select");
4841 SwitchCaseResultVectorTy UniqueResults;
4847 if (UniqueResults.size() != 2)
4849 assert(PHI !=
nullptr &&
"PHI for value select not found");
4852 Value *SelectValue =
4865 class SwitchLookupTable {
4880 static bool WouldFitInRegister(
const DataLayout &DL, uint64_t TableSize,
4923 SwitchLookupTable::SwitchLookupTable(
4927 assert(Values.size() &&
"Can't build lookup table without values!");
4928 assert(TableSize >= Values.size() &&
"Can't fit values in table!");
4931 SingleValue = Values.begin()->second;
4937 for (
size_t I = 0,
E = Values.size(); I !=
E; ++
I) {
4942 uint64_t Idx = (CaseVal->
getValue() - Offset->
getValue()).getLimitedValue();
4943 TableContents[Idx] = CaseRes;
4945 if (CaseRes != SingleValue)
4946 SingleValue =
nullptr;
4950 if (Values.size() < TableSize) {
4952 "Need a default value to fill the lookup table holes.");
4954 for (uint64_t I = 0; I < TableSize; ++
I) {
4955 if (!TableContents[I])
4956 TableContents[
I] = DefaultValue;
4959 if (DefaultValue != SingleValue)
4960 SingleValue =
nullptr;
4966 Kind = SingleValueKind;
4972 if (isa<IntegerType>(ValueType)) {
4973 bool LinearMappingPossible =
true;
4976 assert(TableSize >= 2 &&
"Should be a SingleValue table.");
4978 for (uint64_t I = 0; I < TableSize; ++
I) {
4983 LinearMappingPossible =
false;
4988 APInt Dist = Val - PrevVal;
4991 }
else if (Dist != DistToPrev) {
4992 LinearMappingPossible =
false;
4998 if (LinearMappingPossible) {
4999 LinearOffset = cast<ConstantInt>(TableContents[0]);
5001 Kind = LinearMapKind;
5008 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5011 for (uint64_t I = TableSize; I > 0; --
I) {
5014 if (!isa<UndefValue>(TableContents[I - 1])) {
5015 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5016 TableInt |= Val->
getValue().
zext(TableInt.getBitWidth());
5020 BitMapElementTy =
IT;
5032 "switch.table." + FuncName);
5039 case SingleValueKind:
5041 case LinearMapKind: {
5044 false,
"switch.idx.cast");
5045 if (!LinearMultiplier->isOne())
5046 Result = Builder.
CreateMul(Result, LinearMultiplier,
"switch.idx.mult");
5047 if (!LinearOffset->isZero())
5048 Result = Builder.
CreateAdd(Result, LinearOffset,
"switch.offset");
5066 Value *DownShifted =
5067 Builder.
CreateLShr(BitMap, ShiftAmt,
"switch.downshift");
5069 return Builder.
CreateTrunc(DownShifted, BitMapElementTy,
"switch.masked");
5074 uint64_t TableSize =
5075 Array->getInitializer()->getType()->getArrayNumElements();
5076 if (TableSize > (1ULL << (IT->
getBitWidth() - 1)))
5079 "switch.tableidx.zext");
5083 GEPIndices,
"switch.gep");
5084 return Builder.
CreateLoad(GEP,
"switch.load");
5090 bool SwitchLookupTable::WouldFitInRegister(
const DataLayout &DL,
5092 Type *ElementType) {
5100 if (TableSize >= UINT_MAX /
IT->getBitWidth())
5114 bool AllTablesFitInRegister =
true;
5115 bool HasIllegalType =
false;
5116 for (
const auto &I : ResultTypes) {
5117 Type *Ty = I.second;
5120 HasIllegalType = HasIllegalType || !TTI.
isTypeLegal(Ty);
5123 AllTablesFitInRegister =
5124 AllTablesFitInRegister &&
5125 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5130 if (HasIllegalType && !AllTablesFitInRegister)
5135 if (AllTablesFitInRegister)
5171 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5191 DefaultValue, CmpOp1,
true);
5192 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5197 for (
auto ValuePair : Values) {
5199 ValuePair.second, CmpOp1,
true);
5200 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5202 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5203 "Expect true or false as compare result.");
5217 if (DefaultConst == FalseConst) {
5220 ++NumTableCmpReuses;
5223 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5227 ++NumTableCmpReuses;
5243 (Fn->getFnAttribute(
"no-jump-tables").getValueAsString() ==
"true"))
5277 MinCaseVal = CaseVal;
5279 MaxCaseVal = CaseVal;
5284 if (!
GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5289 for (
const auto &I : Results) {
5292 if (!ResultLists.
count(PHI))
5294 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5300 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5303 uint64_t NumResults = ResultLists[PHIs[0]].
size();
5306 bool TableHasHoles = (NumResults < TableSize);
5311 bool HasDefaultResults =
5313 DefaultResultsList, DL, TTI);
5315 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5320 if (!DL.fitsInLegalInteger(TableSize))
5324 for (
const auto &I : DefaultResultsList) {
5327 DefaultResults[PHI] = Result;
5350 uint64_t MaxTableSize = CaseSize > 63 ?
UINT64_MAX : 1ULL << CaseSize;
5351 assert(MaxTableSize >= TableSize &&
5352 "It is impossible for a switch to have more entries than the max " 5353 "representable value of its input integer type's size.");
5358 const bool DefaultIsReachable =
5360 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5363 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5381 MaskBB->
setName(
"switch.hole_check");
5388 APInt MaskInt(TableSizePowOf2, 0);
5389 APInt One(TableSizePowOf2, 1);
5391 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5392 for (
size_t I = 0,
E = ResultList.size(); I !=
E; ++
I) {
5393 uint64_t Idx = (ResultList[
I].first->getValue() - MinCaseVal->
getValue())
5395 MaskInt |= One << Idx;
5405 Value *Shifted = Builder.
CreateLShr(TableMask, MaskIndex,
"switch.shifted");
5414 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5421 bool ReturnedEarly =
false;
5423 const ResultListTy &ResultList = ResultLists[PHI];
5426 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5428 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5431 Value *
Result = Table.BuildLookup(TableIndex, Builder);
5435 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5438 ReturnedEarly =
true;
5444 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5452 PHI->addIncoming(Result, LookupBB);
5470 ++NumLookupTablesHoles;
5476 uint64_t Diff = (uint64_t)Values.
back() - (uint64_t)Values.
front();
5477 uint64_t Range = Diff + 1;
5478 uint64_t NumCases = Values.
size();
5480 uint64_t MinDensity = 40;
5482 return NumCases * 100 >= Range * MinDensity;
5497 if (CondTy->getIntegerBitWidth() > 64 ||
5510 for (
auto &
C : SI->
cases())
5511 Values.
push_back(
C.getCaseValue()->getValue().getSExtValue());
5519 int64_t
Base = Values[0];
5520 for (
auto &V : Values)
5521 V -= (uint64_t)(Base);
5527 for (
auto &V : Values)
5542 unsigned Shift =
Log2_64(GCD);
5543 for (
auto &V : Values)
5544 V = (int64_t)((uint64_t)V >> Shift);
5564 auto *LShr = Builder.
CreateLShr(Sub, ShiftC);
5565 auto *Shl = Builder.
CreateShl(Sub, Ty->getBitWidth() - Shift);
5566 auto *Rot = Builder.
CreateOr(LShr, Shl);
5569 for (
auto Case : SI->
cases()) {
5570 auto *Orig = Case.getCaseValue();
5571 auto Sub = Orig->getValue() -
APInt(Ty->getBitWidth(), Base);
5581 if (isValueEqualityComparison(SI)) {
5585 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5596 if (FoldValueComparisonIntoPredecessors(SI, Builder))
5619 if (Options.ConvertSwitchToLookupTable &&
5631 bool Changed =
false;
5694 if (isa<PHINode>(*Succ->begin()))
5698 if (BB == OtherPred)
5704 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5717 "unexpected successor");
5723 for (
auto I = OtherPred->begin(),
E = OtherPred->end(); I !=
E;) {
5726 if (isa<DbgInfoIntrinsic>(Inst))
5733 Succ->removePredecessor(BB);
5744 bool SimplifyCFGOpt::SimplifyUncondBranch(
BranchInst *BI,
5756 bool NeedCanonicalLoop =
5757 Options.NeedCanonicalLoop &&
5759 (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5767 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5768 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5769 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5771 if (I->isTerminator() &&
5779 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5798 if (!PPred || (PredPred && PredPred != PPred))
5812 if (isValueEqualityComparison(BI)) {
5817 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5824 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5826 }
else if (&*I == cast<Instruction>(BI->
getCondition())) {
5828 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5841 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5842 if (PBI && PBI->isConditional() &&
5843 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
5844 assert(PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB);
5845 bool CondIsTrue = PBI->getSuccessor(0) == BB;
5847 PBI->getCondition(), BI->
getCondition(), DL, CondIsTrue);
5903 if (
BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5911 if (
BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5938 if (i == I->
getParent()->
end() || i->mayHaveSideEffects())
5943 if (
GEP->getPointerOperand() ==
I)
5951 if (
LoadInst *LI = dyn_cast<LoadInst>(Use))
5952 if (!LI->isVolatile())
5954 LI->getPointerAddressSpace());
5957 if (
StoreInst *SI = dyn_cast<StoreInst>(Use))
5958 if (!SI->isVolatile())
5960 SI->getPointerAddressSpace())) &&
5961 SI->getPointerOperand() ==
I;
5966 CS.getCalledValue() ==
I;
5975 for (
unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
5979 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
5998 bool Changed =
false;
6035 if (
auto *PN = dyn_cast<PHINode>(BB->
begin()))
6036 if (PN->getNumIncomingValues() == 2)
6042 if (SimplifyUncondBranch(BI, Builder))
6045 if (SimplifyCondBranch(BI, Builder))
6048 }
else if (
auto *RI = dyn_cast<ReturnInst>(BB->
getTerminator())) {
6049 if (SimplifyReturn(RI, Builder))
6051 }
else if (
auto *RI = dyn_cast<ResumeInst>(BB->
getTerminator())) {
6052 if (SimplifyResume(RI, Builder))
6054 }
else if (
auto *RI = dyn_cast<CleanupReturnInst>(BB->
getTerminator())) {
6055 if (SimplifyCleanupReturn(RI))
6057 }
else if (
auto *SI = dyn_cast<SwitchInst>(BB->
getTerminator())) {
6058 if (SimplifySwitch(SI, Builder))
6060 }
else if (
auto *UI = dyn_cast<UnreachableInst>(BB->
getTerminator())) {
6061 if (SimplifyUnreachable(UI))
6063 }
else if (
auto *IBI = dyn_cast<IndirectBrInst>(BB->
getTerminator())) {
6064 if (SimplifyIndirectBr(IBI))
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.
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...
void push_back(const T &Elt)
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.
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 MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr, DeferredDominance *DDT=nullptr)
Attempts to merge a block into its predecessor, if possible.
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.
iterator erase(iterator where)
Compute iterated dominance frontiers using a linear time algorithm.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
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="")
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.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
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 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
static void GetBranchWeights(TerminatorInst *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given TerminatorInst, the default weight is at the front of the vector.
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...
BasicBlock * getSuccessor(unsigned i) const
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...
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
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...
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)
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 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)
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...
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...
static bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI, const SimplifyCFGOptions &Options)
This is called when we find an icmp instruction (a seteq/setne with a constant) as the only instructi...
bool insert(const value_type &X)
Insert a new element into the SetVector.
static uintptr_t MapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
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.
bool cannotDuplicate() const
Determine if the invoke cannot be duplicated.
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.
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...
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 ...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
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.
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")
Subclasses of this class are all able to terminate a basic block.
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)
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
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.
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.
Interval::pred_iterator pred_end(Interval *I)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
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.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
const Value * getCondition() const
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.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
iterator erase(const_iterator CI)
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.
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
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...
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.
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.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return the number of times the sign bit of the register is replicated into the other bits...
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.
TerminatorInst * 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 ...
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.
void removeUnwindEdge(BasicBlock *BB, DeferredDominance *DDT=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
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.
static void EraseTerminatorInstAndDCECond(TerminatorInst *TI)
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 ...
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.
bool isConvergent() const
Determine if the invoke is convergent.
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.
unsigned getNumUses() const
This method computes the number of uses of this Value.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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)
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)
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...
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
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.
void combineMetadataForCSE(Instruction *K, const Instruction *J)
Combine the metadata of two instructions so that K can replace J.
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 ...
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
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()
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
Delete the specified block, which must have no predecessors.
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.
succ_range successors(BasicBlock *BB)
void setDefaultDest(BasicBlock *DefaultCase)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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 ...
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
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.
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.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.
static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
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)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
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 combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
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.