80 using namespace PatternMatch;
82 #define DEBUG_TYPE "simplifycfg"
91 "Control the amount of phi node folding to perform (default = 2)"));
95 cl::desc(
"Duplicate return instructions into unconditional branches"));
99 cl::desc(
"Sink common instructions down to the end block"));
103 cl::desc(
"Hoist conditional stores if an unconditional store precedes"));
107 cl::desc(
"Hoist conditional stores even if an unconditional store does not "
108 "precede - hoist multiple conditional stores into a single "
109 "predicated store"));
113 cl::desc(
"When merging conditional stores, do so even if the resultant "
114 "basic blocks are unlikely to be if-converted as a result"));
118 cl::desc(
"Allow exactly one expensive instruction to be speculatively "
123 cl::desc(
"Limit maximum recursion depth when calculating costs of "
124 "speculatively executed instructions"));
126 STATISTIC(NumBitMaps,
"Number of switch instructions turned into bitmaps");
128 "Number of switch instructions turned into linear mapping");
130 "Number of switch instructions turned into lookup tables");
132 NumLookupTablesHoles,
133 "Number of switch instructions turned into lookup tables (holes checked)");
134 STATISTIC(NumTableCmpReuses,
"Number of reused switch table lookup compares");
136 "Number of common instructions sunk down to the end block");
137 STATISTIC(NumSpeculations,
"Number of speculative executed instructions");
145 SwitchCaseResultVectorTy;
152 struct ValueEqualityComparisonCase {
157 : Value(Value), Dest(Dest) {}
159 bool operator<(ValueEqualityComparisonCase RHS)
const {
161 return Value < RHS.Value;
167 class SimplifyCFGOpt {
170 unsigned BonusInstThreshold;
174 bool LateSimplifyCFG;
177 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
178 bool SimplifyEqualityComparisonWithOnlyPredecessor(
TerminatorInst *TI,
199 bool LateSimplifyCFG)
200 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC),
201 LoopHeaders(LoopHeaders), LateSimplifyCFG(LateSimplifyCFG) {}
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);
285 if (!isa<PHINode>(Succ->
begin()))
300 "Instruction is not safe to speculatively execute!");
323 unsigned &CostRemaining,
325 unsigned Depth = 0) {
358 if (!AggressiveInsts)
362 if (AggressiveInsts->
count(I))
379 if (Cost > CostRemaining &&
384 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
393 AggressiveInsts->
insert(I);
410 if (isa<ConstantPointerNull>(V))
415 if (CE->getOpcode() == Instruction::IntToPtr)
416 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
421 return cast<ConstantInt>(
439 struct ConstantComparesGatherer {
448 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
453 ConstantComparesGatherer(
const ConstantComparesGatherer &) =
delete;
454 ConstantComparesGatherer &
455 operator=(
const ConstantComparesGatherer &) =
delete;
460 bool setValueOnce(
Value *NewVal) {
461 if (CompValue && CompValue != NewVal)
464 return (CompValue !=
nullptr);
478 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
536 if (!setValueOnce(RHSVal))
559 if (!setValueOnce(RHSVal))
588 CandidateVal = RHSVal;
603 if (!setValueOnce(CandidateVal))
619 void gather(
Value *V) {
621 bool isEQ = (I->
getOpcode() == Instruction::Or);
631 while (!DFT.
empty()) {
636 if (I->
getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
645 if (matchInstruction(I, isEQ))
670 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
671 if (BI->isConditional())
672 Cond = dyn_cast<Instruction>(BI->getCondition());
686 if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
689 if (
SI->getNumSuccessors() * std::distance(
pred_begin(
SI->getParent()),
692 CV =
SI->getCondition();
693 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI))
694 if (BI->isConditional() && BI->getCondition()->hasOneUse())
695 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
703 Value *
Ptr = PTII->getPointerOperand();
713 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
714 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
715 if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
716 Cases.reserve(
SI->getNumCases());
717 for (
auto Case :
SI->cases())
718 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
719 Case.getCaseSuccessor()));
720 return SI->getDefaultDest();
726 Cases.push_back(ValueEqualityComparisonCase(
735 std::vector<ValueEqualityComparisonCase> &Cases) {
736 Cases.erase(
std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
741 std::vector<ValueEqualityComparisonCase> &C2) {
742 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *
V2 = &C2;
745 if (V1->size() > V2->size())
750 if (V1->size() == 1) {
753 for (
unsigned i = 0, e = V2->size(); i != e; ++i)
754 if (TheVal == (*V2)[i].
Value)
761 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
762 while (i1 != e1 && i2 != e2) {
765 if ((*V1)[i1].Value < (*V2)[i2].Value)
778 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
784 Value *ThisVal = isValueEqualityComparison(TI);
785 assert(ThisVal &&
"This isn't a value comparison!!");
786 if (ThisVal != PredVal)
793 std::vector<ValueEqualityComparisonCase> PredCases;
795 GetValueEqualityComparisonCases(Pred->
getTerminator(), PredCases);
799 std::vector<ValueEqualityComparisonCase> ThisCases;
800 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
812 if (isa<BranchInst>(TI)) {
815 assert(ThisCases.size() == 1 &&
"Branch can only have one case!");
821 ThisCases[0].Dest->removePredecessor(TI->
getParent());
824 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
834 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
835 DeadCases.
insert(PredCases[i].Value);
838 <<
"Through successor TI: " << *TI);
852 if (DeadCases.count(i->getCaseValue())) {
854 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
857 i->getCaseSuccessor()->removePredecessor(TI->
getParent());
861 if (HasWeight && Weights.size() >= 2)
864 .createBranchWeights(Weights));
866 DEBUG(
dbgs() <<
"Leaving: " << *TI <<
"\n");
874 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
875 if (PredCases[i].Dest == TIBB) {
878 TIV = PredCases[i].
Value;
880 assert(TIV &&
"No edge from pred to succ?");
885 for (
unsigned i = 0, e = ThisCases.size(); i != e; ++i)
886 if (ThisCases[i].
Value == TIV) {
887 TheRealDest = ThisCases[i].Dest;
893 TheRealDest = ThisDef;
898 if (Succ != CheckEdge)
908 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
920 struct ConstantIntOrdering {
941 return MDS->getString().equals(
"branch_weights");
961 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
971 uint64_t Max = *std::max_element(Weights.
begin(), Weights.
end());
972 if (Max > UINT_MAX) {
974 for (uint64_t &I : Weights)
983 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(
TerminatorInst *TI,
986 Value *CV = isValueEqualityComparison(TI);
987 assert(CV &&
"Not a comparison?");
988 bool Changed =
false;
991 while (!Preds.empty()) {
996 Value *PCV = isValueEqualityComparison(PTI);
998 if (PCV == CV && TI != PTI) {
1001 for (
auto *Succ : FailBlocks) {
1008 std::vector<ValueEqualityComparisonCase> BBCases;
1009 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1011 std::vector<ValueEqualityComparisonCase> PredCases;
1012 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1024 if (PredHasWeights) {
1027 if (Weights.
size() != 1 + PredCases.size())
1028 PredHasWeights = SuccHasWeights =
false;
1029 }
else if (SuccHasWeights)
1033 Weights.
assign(1 + PredCases.size(), 1);
1036 if (SuccHasWeights) {
1039 if (SuccWeights.
size() != 1 + BBCases.size())
1040 PredHasWeights = SuccHasWeights =
false;
1041 }
else if (PredHasWeights)
1042 SuccWeights.
assign(1 + BBCases.size(), 1);
1044 if (PredDefault == BB) {
1047 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1048 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1049 if (PredCases[i].Dest != BB)
1050 PTIHandled.insert(PredCases[i].
Value);
1053 std::swap(PredCases[i], PredCases.back());
1055 if (PredHasWeights || SuccHasWeights) {
1057 Weights[0] += Weights[i + 1];
1062 PredCases.pop_back();
1068 if (PredDefault != BBDefault) {
1070 PredDefault = BBDefault;
1074 unsigned CasesFromPred = Weights.
size();
1075 uint64_t ValidTotalSuccWeight = 0;
1076 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1077 if (!PTIHandled.count(BBCases[i].Value) &&
1078 BBCases[i].Dest != BBDefault) {
1079 PredCases.push_back(BBCases[i]);
1080 NewSuccessors.
push_back(BBCases[i].Dest);
1081 if (SuccHasWeights || PredHasWeights) {
1085 Weights.
push_back(Weights[0] * SuccWeights[i + 1]);
1086 ValidTotalSuccWeight += SuccWeights[i + 1];
1090 if (SuccHasWeights || PredHasWeights) {
1091 ValidTotalSuccWeight += SuccWeights[0];
1093 for (
unsigned i = 1; i < CasesFromPred; ++i)
1094 Weights[i] *= ValidTotalSuccWeight;
1096 Weights[0] *= SuccWeights[0];
1102 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1103 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1104 for (
unsigned i = 0, e = PredCases.size(); i != e; ++i)
1105 if (PredCases[i].Dest == BB) {
1106 PTIHandled.
insert(PredCases[i].Value);
1108 if (PredHasWeights || SuccHasWeights) {
1109 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1114 std::swap(PredCases[i], PredCases.back());
1115 PredCases.pop_back();
1122 for (
unsigned i = 0, e = BBCases.size(); i != e; ++i)
1123 if (PTIHandled.count(BBCases[i].Value)) {
1125 if (PredHasWeights || SuccHasWeights)
1126 Weights.
push_back(WeightsForHandled[BBCases[i].Value]);
1127 PredCases.push_back(BBCases[i]);
1128 NewSuccessors.
push_back(BBCases[i].Dest);
1136 if (PredHasWeights || SuccHasWeights)
1137 Weights.
push_back(WeightsForHandled[I]);
1138 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1146 for (
BasicBlock *NewSuccessor : NewSuccessors)
1160 for (ValueEqualityComparisonCase &V : PredCases)
1163 if (PredHasWeights || SuccHasWeights) {
1182 if (!InfLoopBlock) {
1209 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1240 while (isa<DbgInfoIntrinsic>(I1))
1242 while (isa<DbgInfoIntrinsic>(I2))
1251 bool Changed =
false;
1255 if (isa<TerminatorInst>(I1))
1256 goto HoistTerminator;
1265 if (!I2->use_empty())
1266 I2->replaceAllUsesWith(I1);
1282 if (!isa<CallInst>(I1))
1286 I2->eraseFromParent();
1295 while (isa<DbgInfoIntrinsic>(I1))
1297 while (isa<DbgInfoIntrinsic>(I2))
1336 I2->replaceAllUsesWith(NT);
1345 std::map<std::pair<Value *, Value *>,
SelectInst *> InsertedSelects;
1357 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1359 SI = cast<SelectInst>(
1361 BB1V->
getName() +
"." + BB2V->getName(), BI));
1389 for (
auto *I : Insts) {
1391 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(
I) ||
1392 I->getType()->isTokenTy())
1398 if (
const auto *C = dyn_cast<CallInst>(I))
1399 if (C->isInlineAsm())
1404 if (!isa<StoreInst>(I) && !I->hasOneUse())
1409 for (
auto *I : Insts)
1410 if (!I->isSameOperationAs(I0))
1417 if (!isa<StoreInst>(I0)) {
1421 auto *U = cast<Instruction>(*I->
user_begin());
1423 PNUse->getParent() == Succ &&
1424 PNUse->getIncomingValueForBlock(I->
getParent()) == I) ||
1447 for (
unsigned OI = 0, OE = I0->
getNumOperands(); OI != OE; ++OI) {
1456 if (!
all_of(Insts, SameAsI0)) {
1461 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
1465 for (
auto *I : Insts)
1476 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1481 for (
auto *BB : Blocks) {
1485 }
while (isa<DbgInfoIntrinsic>(I) && I != &BB->
front());
1486 if (!isa<DbgInfoIntrinsic>(I))
1495 if (!isa<StoreInst>(I0)) {
1498 auto *U = cast<Instruction>(*I->
user_begin());
1524 assert(!
Op->getType()->isTokenTy() &&
"Can't PHI tokens!");
1526 Op->getName() +
".sink", &BBEnd->front());
1527 for (
auto *I : Insts)
1536 I0->
moveBefore(&*BBEnd->getFirstInsertionPt());
1544 for (
auto *I : Insts)
1550 if (!isa<CallInst>(I0))
1553 if (!isa<StoreInst>(I0)) {
1559 PN->replaceAllUsesWith(I0);
1560 PN->eraseFromParent();
1564 for (
auto *I : Insts)
1566 I->eraseFromParent();
1581 class LockstepReverseIterator {
1594 for (
auto *BB : Blocks) {
1596 for (Inst = Inst->
getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1603 Insts.push_back(Inst);
1611 void operator -- () {
1614 for (
auto *&Inst : Insts) {
1615 for (Inst = Inst->
getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1684 auto *
T =
B->getTerminator();
1685 if (isa<BranchInst>(
T) && cast<BranchInst>(
T)->isUnconditional())
1687 else if ((isa<BranchInst>(
T) || isa<SwitchInst>(
T)) && !Cond)
1692 if (UnconditionalPreds.
size() < 2)
1695 bool Changed =
false;
1702 unsigned ScanIdx = 0;
1705 LockstepReverseIterator LRI(UnconditionalPreds);
1706 while (LRI.isValid() &&
1708 DEBUG(
dbgs() <<
"SINK: instruction can be sunk: " << *(*LRI)[0] <<
"\n");
1709 InstructionsToSink.
insert((*LRI).begin(), (*LRI).end());
1714 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1715 unsigned NumPHIdValues = 0;
1716 for (
auto *I : *LRI)
1717 for (
auto *V : PHIOperands[I])
1718 if (InstructionsToSink.
count(V) == 0)
1720 DEBUG(
dbgs() <<
"SINK: #phid values: " << NumPHIdValues <<
"\n");
1721 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.
size();
1722 if ((NumPHIdValues % UnconditionalPreds.
size()) != 0)
1725 return NumPHIInsts <= 1;
1728 if (ScanIdx > 0 && Cond) {
1736 bool Profitable =
false;
1737 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1748 DEBUG(
dbgs() <<
"SINK: Splitting edge\n");
1770 for (
unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1772 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1778 if (!ProfitableToSinkInstruction(LRI)) {
1780 DEBUG(
dbgs() <<
"SINK: stopping here, too many PHIs would be created!\n");
1831 unsigned MaxNumInstToLookAt = 9;
1833 if (!MaxNumInstToLookAt)
1836 if (isa<DbgInfoIntrinsic>(CurI))
1838 --MaxNumInstToLookAt;
1841 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1844 if (
auto *SI = dyn_cast<StoreInst>(&CurI)) {
1846 if (SI->getPointerOperand() == StorePtr)
1848 return SI->getValueOperand();
1897 if (isa<FCmpInst>(BrCond))
1905 bool Invert =
false;
1919 unsigned SpeculationCost = 0;
1920 Value *SpeculatedStoreValue =
nullptr;
1923 BBE = std::prev(ThenBB->
end());
1924 BBI != BBE; ++BBI) {
1927 if (isa<DbgInfoIntrinsic>(I))
1933 if (SpeculationCost > 1)
1939 I, BB, ThenBB, EndBB))))
1941 if (!SpeculatedStoreValue &&
1947 if (SpeculatedStoreValue)
1948 SpeculatedStore = cast<StoreInst>(
I);
1958 ++SinkCandidateUseCounts[OpI];
1966 I = SinkCandidateUseCounts.
begin(),
1967 E = SinkCandidateUseCounts.end();
1969 if (I->first->getNumUses() == I->second) {
1971 if (SpeculationCost > 1)
1976 bool HaveRewritablePHIs =
false;
1992 HaveRewritablePHIs =
true;
1995 if (!OrigCE && !ThenCE)
2005 if (OrigCost + ThenCost > MaxCost)
2013 if (SpeculationCost > 1)
2019 if (!HaveRewritablePHIs && !(
HoistCondStores && SpeculatedStoreValue))
2023 DEBUG(
dbgs() <<
"SPECULATIVELY EXECUTING BB" << *ThenBB <<
"\n";);
2026 if (SpeculatedStoreValue) {
2029 Value *FalseV = SpeculatedStoreValue;
2033 BrCond, TrueV, FalseV, TrueV->
getName() +
"." + FalseV->
getName(), BI);
2042 for (
auto &I : *ThenBB)
2043 I.dropUnknownNonDebugMetadata();
2047 ThenBB->begin(), std::prev(ThenBB->end()));
2065 Value *TrueV = ThenV, *FalseV = OrigV;
2069 BrCond, TrueV, FalseV, TrueV->
getName() +
"." + FalseV->getName(), BI);
2084 if (isa<DbgInfoIntrinsic>(BBI))
2094 if (UI->
getParent() != BB || isa<PHINode>(UI))
2169 if (
PHINode *PN = dyn_cast<PHINode>(BBI)) {
2176 N->
setName(BBI->getName() +
".c");
2181 if (PI != TranslateMap.
end())
2187 if (!BBI->use_empty())
2188 TranslateMap[&*BBI] = V;
2194 if (!BBI->use_empty())
2195 TranslateMap[&*BBI] = N;
2202 if (
auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2203 if (II->getIntrinsicID() == Intrinsic::assume)
2238 isa<ConstantInt>(IfCond))
2246 unsigned NumPhis = 0;
2261 PHINode *PN = cast<PHINode>(II++);
2269 MaxCostVal0, TTI) ||
2286 isa<BinaryOperator>(IfCond)))
2296 if (cast<BranchInst>(IfBlock1->
getTerminator())->isConditional()) {
2302 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2310 if (cast<BranchInst>(IfBlock2->
getTerminator())->isConditional()) {
2316 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2324 DEBUG(
dbgs() <<
"FOUND IF CONDITION! " << *IfCond <<
" T: "
2335 for (
auto &I : *IfBlock1)
2336 I.dropUnknownNonDebugMetadata();
2338 IfBlock1->getInstList(), IfBlock1->begin(),
2339 IfBlock1->getTerminator()->getIterator());
2342 for (
auto &I : *IfBlock2)
2343 I.dropUnknownNonDebugMetadata();
2345 IfBlock2->getInstList(), IfBlock2->begin(),
2346 IfBlock2->getTerminator()->getIterator());
2354 Value *Sel = Builder.
CreateSelect(IfCond, TrueVal, FalseVal,
"", InsertPt);
2378 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2384 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2393 if (FalseRet->getNumOperands() == 0) {
2394 TrueSucc->removePredecessor(BI->
getParent());
2404 Value *FalseValue = FalseRet->getReturnValue();
2407 if (
PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2408 if (TVPN->getParent() == TrueSucc)
2409 TrueValue = TVPN->getIncomingValueForBlock(BI->
getParent());
2410 if (
PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2411 if (FVPN->getParent() == FalseSucc)
2412 FalseValue = FVPN->getIncomingValueForBlock(BI->
getParent());
2419 if (
ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2422 if (
ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2428 TrueSucc->removePredecessor(BI->
getParent());
2435 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2436 }
else if (isa<UndefValue>(TrueValue)) {
2437 TrueValue = FalseValue;
2440 Builder.
CreateSelect(BrCond, TrueValue, FalseValue,
"retval", BI);
2449 DEBUG(
dbgs() <<
"\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2450 <<
"\n " << *BI <<
"NewRet = " << *RI
2451 <<
"TRUEBLOCK: " << *TrueSucc <<
"FALSEBLOCK: " << *FalseSucc);
2461 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2479 uint64_t &PredTrueWeight,
2480 uint64_t &PredFalseWeight,
2481 uint64_t &SuccTrueWeight,
2482 uint64_t &SuccFalseWeight) {
2483 bool PredHasWeights =
2485 bool SuccHasWeights =
2487 if (PredHasWeights || SuccHasWeights) {
2488 if (!PredHasWeights)
2489 PredTrueWeight = PredFalseWeight = 1;
2490 if (!SuccHasWeights)
2491 SuccTrueWeight = SuccFalseWeight = 1;
2513 if (
BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2514 if (PBI->isConditional() &&
2519 if (isa<CmpInst>(Curr)) {
2533 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2541 while (isa<DbgInfoIntrinsic>(CondIt))
2552 unsigned NumBonusInsts = 0;
2553 for (
auto I = BB->
begin(); Cond != &*
I; ++
I) {
2555 if (isa<DbgInfoIntrinsic>(I))
2561 if (User ==
nullptr || User->
getParent() != BB)
2568 if (NumBonusInsts > BonusInstThreshold)
2584 if (TrueDest == BB || FalseDest == BB)
2603 bool InvertPredCond =
false;
2607 Opc = Instruction::Or;
2609 Opc = Instruction::And;
2611 Opc = Instruction::And;
2612 InvertPredCond =
true;
2614 Opc = Instruction::Or;
2615 InvertPredCond =
true;
2624 DEBUG(
dbgs() <<
"FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2628 if (InvertPredCond) {
2631 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
2632 CmpInst *CI = cast<CmpInst>(NewCond);
2650 for (
auto BonusInst = BB->
begin(); Cond != &*BonusInst; ++BonusInst) {
2651 if (isa<DbgInfoIntrinsic>(BonusInst))
2656 VMap[&*BonusInst] = NewBonusInst;
2666 NewBonusInst->
takeName(&*BonusInst);
2667 BonusInst->setName(BonusInst->getName() +
".old");
2684 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2687 SuccTrueWeight, SuccFalseWeight);
2695 NewWeights.
push_back(PredTrueWeight * SuccTrueWeight);
2701 (SuccFalseWeight + SuccTrueWeight) +
2702 PredTrueWeight * SuccFalseWeight);
2714 (SuccFalseWeight + SuccTrueWeight) +
2715 PredFalseWeight * SuccTrueWeight);
2717 NewWeights.
push_back(PredFalseWeight * SuccFalseWeight);
2722 if (NewWeights.
size() == 2) {
2735 for (
unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2737 PHIs[i]->getIncomingValueForBlock(PBI->
getParent()));
2746 MergedCond = cast<Instruction>(
2747 Builder.
CreateBinOp(Instruction::And, NotCond, New,
"and.cond"));
2749 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2750 Instruction::Or, PBI->
getCondition(), MergedCond,
"or.cond"));
2755 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2756 Instruction::And, PBI->
getCondition(), New,
"and.cond"));
2757 if (PBI_C->
isOne()) {
2760 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2761 Instruction::Or, NotCond, MergedCond,
"or.cond"));
2765 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->
getParent()),
2784 if (isa<DbgInfoIntrinsic>(I))
2785 I.clone()->insertBefore(PBI);
2796 for (
auto *BB : {BB1, BB2}) {
2800 if (
auto *SI = dyn_cast<StoreInst>(&I)) {
2812 Value *AlternativeV =
nullptr) {
2830 for (
auto I = Succ->
begin(); isa<PHINode>(
I); ++
I)
2831 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2832 PHI = cast<PHINode>(
I);
2838 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2847 if (!AlternativeV &&
2848 (!isa<Instruction>(V) || cast<Instruction>(V)->
getParent() != BB))
2863 bool InvertPCond,
bool InvertQCond) {
2864 auto IsaBitcastOfPointerType = [](
const Instruction &
I) {
2866 I.getType()->isPointerTy();
2878 for (
auto &I : *BB) {
2880 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(
I) ||
2884 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(
I) ||
2885 IsaBitcastOfPointerType(I))
2894 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2895 !IsWorthwhile(QFB)))
2905 if (!PStore || !QStore)
2924 if (I.mayReadOrWriteMemory())
2926 for (
auto &I : *QFB)
2930 for (
auto &I : *QTB)
2942 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2952 Value *PPred = PStore->
getParent() == PTB ? PCond : QB.CreateNot(PCond);
2953 Value *QPred = QStore->
getParent() == QTB ? QCond : QB.CreateNot(QCond);
2956 PPred = QB.CreateNot(PPred);
2958 QPred = QB.CreateNot(QPred);
2959 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2963 QB.SetInsertPoint(
T);
2964 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3020 bool InvertPCond =
false, InvertQCond =
false;
3026 if (QFB == PostBB) {
3045 !HasOnePredAndOneSucc(QFB, QBI->
getParent(), PostBB))
3048 (QTB && !HasOnePredAndOneSucc(QTB, QBI->
getParent(), PostBB)))
3056 for (
auto *BB : {PTB, PFB}) {
3060 if (
StoreInst *SI = dyn_cast<StoreInst>(&I))
3061 PStoreAddresses.
insert(SI->getPointerOperand());
3063 for (
auto *BB : {QTB, QFB}) {
3067 if (
StoreInst *SI = dyn_cast<StoreInst>(&I))
3068 QStoreAddresses.
insert(SI->getPointerOperand());
3074 auto &CommonAddresses = PStoreAddresses;
3076 bool Changed =
false;
3077 for (
auto *
Address : CommonAddresses)
3079 PTB, PFB, QTB, QFB, PostBB,
Address, InvertPCond, InvertQCond);
3099 if (BB->getSinglePredecessor()) {
3120 if ((PBI = dyn_cast<BranchInst>(P->
getTerminator())) && PBI != BI &&
3137 if (
auto *CE = dyn_cast<ConstantExpr>(BI->
getCondition()))
3152 while (isa<DbgInfoIntrinsic>(BBI))
3189 unsigned NumPhis = 0;
3195 PHINode *PN = cast<PHINode>(II);
3221 if (OtherDest == BB) {
3227 OtherDest = InfLoopBlock;
3239 PBICond = Builder.
CreateNot(PBICond, PBICond->getName() +
".not");
3246 Value *Cond = Builder.
CreateOr(PBICond, BICond,
"brmerge");
3254 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3255 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3258 SuccTrueWeight, SuccFalseWeight);
3260 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3261 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3262 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3263 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3267 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3268 PredOther * SuccCommon,
3269 PredOther * SuccOther};
3275 .createBranchWeights(NewWeights[0], NewWeights[1]));
3290 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->
getParent());
3291 Value *PBIV = PN->getIncomingValue(PBBIdx);
3296 PN->setIncomingValue(PBBIdx, NV);
3302 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3303 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3304 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3305 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3308 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3309 PredOther * SuccCommon};
3315 .createBranchWeights(NewWeights[0], NewWeights[1]));
3342 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB :
nullptr;
3347 if (Succ == KeepEdge1)
3348 KeepEdge1 =
nullptr;
3349 else if (Succ == KeepEdge2)
3350 KeepEdge2 =
nullptr;
3360 if (!KeepEdge1 && !KeepEdge2) {
3361 if (TrueBB == FalseBB)
3369 if (TrueWeight != FalseWeight)
3372 .createBranchWeights(TrueWeight, FalseWeight));
3374 }
else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3402 if (!TrueVal || !FalseVal)
3411 uint32_t TrueWeight = 0, FalseWeight = 0;
3485 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3488 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3497 assert(VVal &&
"Should have a unique destination value");
3505 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
3521 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
3528 if (PHIUse ==
nullptr || PHIUse != &SuccBlock->
front() ||
3555 Weights[0] = (Weights[0] + 1) >> 1;
3556 Weights.push_back(Weights[0]);
3588 ConstantComparesGatherer ConstantCompare(Cond, DL);
3591 Value *CompVal = ConstantCompare.CompValue;
3592 unsigned UsedICmps = ConstantCompare.UsedICmps;
3593 Value *ExtraCase = ConstantCompare.Extra;
3603 bool TrueWhenEqual = (Cond->
getOpcode() == Instruction::Or);
3612 if (ExtraCase && Values.
size() < 2)
3626 DEBUG(
dbgs() <<
"Converting 'icmp' chain with " << Values.
size()
3627 <<
" cases into SWITCH. BB is:\n"
3651 DEBUG(
dbgs() <<
" ** 'icmp' chain unhandled condition: " << *ExtraCase
3652 <<
"\nEXTRABB = " << *BB);
3667 for (
unsigned i = 0, e = Values.
size(); i != e; ++i)
3668 New->
addCase(Values[i], EdgeBB);
3674 PHINode *PN = cast<PHINode>(BBI);
3676 for (
unsigned i = 0, e = Values.
size() - 1; i != e; ++i)
3683 DEBUG(
dbgs() <<
" ** 'icmp' chain result is:\n" << *BB <<
'\n');
3689 return SimplifyCommonResume(RI);
3693 return SimplifySingleResume(RI);
3699 bool SimplifyCFGOpt::SimplifyCommonResume(
ResumeInst *RI) {
3707 if (!isa<DbgInfoIntrinsic>(I))
3711 auto *PhiLPInst = cast<PHINode>(RI->
getValue());
3714 for (
unsigned Idx = 0,
End = PhiLPInst->getNumIncomingValues(); Idx !=
End;
3716 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3717 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3721 if (IncomingBB->getUniqueSuccessor() != BB)
3726 if (IncomingValue != LandingPad)
3729 bool isTrivial =
true;
3731 I = IncomingBB->getFirstNonPHI()->getIterator();
3732 E = IncomingBB->getTerminator()->getIterator();
3734 if (!isa<DbgInfoIntrinsic>(I)) {
3740 TrivialUnwindBlocks.
insert(IncomingBB);
3744 if (TrivialUnwindBlocks.
empty())
3748 for (
auto *TrivialBB : TrivialUnwindBlocks) {
3752 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3766 TrivialBB->getTerminator()->eraseFromParent();
3774 return !TrivialUnwindBlocks.empty();
3778 bool SimplifyCFGOpt::SimplifySingleResume(
ResumeInst *RI) {
3782 "Resume must unwind the exception that caused control to here");
3787 if (!isa<DbgInfoIntrinsic>(I))
3799 LoopHeaders->
erase(BB);
3831 switch (IntrinsicID) {
3832 case Intrinsic::dbg_declare:
3833 case Intrinsic::dbg_value:
3834 case Intrinsic::lifetime_end:
3857 PHINode *DestPN = cast<PHINode>(
I);
3879 if (SrcPN && SrcPN->
getParent() == BB) {
3884 SrcIdx != SrcE; ++SrcIdx) {
3905 PHINode *PN = cast<PHINode>(I++);
3925 if (UnwindDest ==
nullptr) {
3953 if (!SuccessorCleanupPad)
3962 SuccessorCleanupPad->eraseFromParent();
3998 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4008 while (!UncondBranchPreds.
empty()) {
4011 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
4020 LoopHeaders->
erase(BB);
4029 while (!CondBranchPreds.
empty()) {
4044 bool Changed =
false;
4054 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4057 if (BBI->mayHaveSideEffects()) {
4058 if (
auto *SI = dyn_cast<StoreInst>(BBI)) {
4059 if (SI->isVolatile())
4061 }
else if (
auto *LI = dyn_cast<LoadInst>(BBI)) {
4062 if (LI->isVolatile())
4064 }
else if (
auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4065 if (RMWI->isVolatile())
4067 }
else if (
auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4068 if (CXI->isVolatile())
4070 }
else if (isa<CatchPadInst>(BBI)) {
4078 }
else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4079 !isa<LandingPadInst>(BBI)) {
4089 if (!BBI->use_empty())
4091 BBI->eraseFromParent();
4097 if (&BB->
front() != UI)
4101 for (
unsigned i = 0, e = Preds.size(); i != e; ++i) {
4104 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
4121 }
else if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
4123 if (i->getCaseSuccessor() != BB) {
4132 }
else if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4133 if (II->getUnwindDest() == BB) {
4137 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4138 if (CSI->getUnwindDest() == BB) {
4145 E = CSI->handler_end();
4148 CSI->removeHandler(I);
4154 if (CSI->getNumHandlers() == 0) {
4156 if (CSI->hasUnwindDest()) {
4170 }
else if (isa<CleanupReturnInst>(TI)) {
4182 LoopHeaders->
erase(BB);
4193 for (
size_t I = 1,
E = Cases.
size(); I !=
E; ++
I) {
4194 if (Cases[I - 1]->getValue() != Cases[
I]->getValue() + 1)
4214 for (
auto Case : SI->
cases()) {
4218 if (Dest == DestA) {
4224 if (Dest == DestB) {
4232 "Single-destination switch should have been folded.");
4235 assert(!CasesB.
empty() &&
"There must be non-default cases.");
4243 ContiguousCases = &CasesA;
4244 ContiguousDest = DestA;
4247 ContiguousCases = &CasesB;
4248 ContiguousDest = DestB;
4265 if (NumCases->isNullValue() && !ContiguousCases->empty())
4276 uint64_t TrueWeight = 0;
4277 uint64_t FalseWeight = 0;
4278 for (
size_t I = 0,
E = Weights.
size(); I !=
E; ++
I) {
4280 TrueWeight += Weights[I];
4282 FalseWeight += Weights[
I];
4284 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4290 .createBranchWeights((
uint32_t)TrueWeight,
4296 for (
auto BBI = ContiguousDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4297 unsigned PreviousEdges = ContiguousCases->size();
4300 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4301 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4303 for (
auto BBI = OtherDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4304 unsigned PreviousEdges = SI->
getNumCases() - ContiguousCases->size();
4307 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4308 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4329 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4333 for (
auto &Case : SI->
cases()) {
4334 const APInt &CaseVal = Case.getCaseValue()->getValue();
4337 DeadCases.
push_back(Case.getCaseValue());
4338 DEBUG(
dbgs() <<
"SimplifyCFG: switch case " << CaseVal <<
" is dead.\n");
4348 const unsigned NumUnknownBits =
4350 assert(NumUnknownBits <= Bits);
4351 if (HasDefault && DeadCases.
empty() &&
4352 NumUnknownBits < 64 &&
4354 DEBUG(
dbgs() <<
"SimplifyCFG: switch default is dead.\n");
4376 "Case was not found. Probably mistake in DeadCases forming.");
4378 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.
back());
4383 CaseI->getCaseSuccessor()->removePredecessor(SI->
getParent());
4386 if (HasWeight && Weights.
size() >= 2) {
4390 .createBranchWeights(MDWeights));
4393 return !DeadCases.empty();
4415 while (
PHINode *PHI = dyn_cast<PHINode>(I++)) {
4416 int Idx = PHI->getBasicBlockIndex(BB);
4417 assert(Idx >= 0 &&
"PHI has no entry for predecessor?");
4419 Value *InValue = PHI->getIncomingValue(Idx);
4420 if (InValue != CaseValue)
4436 ForwardingNodesMap ForwardingNodes;
4438 for (
auto Case : SI->
cases()) {
4440 BasicBlock *CaseDest = Case.getCaseSuccessor();
4448 ForwardingNodes[PHI].push_back(PhiIndex);
4451 bool Changed =
false;
4453 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
4454 E = ForwardingNodes.end();
4459 if (Indexes.
size() < 2)
4462 for (
size_t I = 0,
E = Indexes.
size(); I !=
E; ++
I)
4478 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(
C) &&
4479 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(
C) &&
4480 !isa<UndefValue>(C) && !isa<ConstantExpr>(
C))
4484 if (!CE->isGEPWithNoNotionalOverIndexing())
4501 if (
Constant *C = dyn_cast<Constant>(V))
4503 return ConstantPool.
lookup(V);
4532 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4560 if (
T->getNumSuccessors() != 1 ||
T->isExceptional())
4563 CaseDest =
T->getSuccessor(0);
4564 }
else if (isa<DbgInfoIntrinsic>(I)) {
4576 if (I->getParent() == CaseDest)
4578 if (
PHINode *Phi = dyn_cast<PHINode>(User))
4579 if (Phi->getIncomingBlock(
Use) == CaseDest)
4584 ConstantPool.
insert(std::make_pair(&*I, C));
4592 *CommonDest = CaseDest;
4594 if (CaseDest != *CommonDest)
4599 while (
PHINode *PHI = dyn_cast<PHINode>(I++)) {
4600 int Idx = PHI->getBasicBlockIndex(Pred);
4613 Res.push_back(std::make_pair(PHI, ConstVal));
4616 return Res.size() > 0;
4622 SwitchCaseResultVectorTy &UniqueResults,
4624 for (
auto &I : UniqueResults) {
4625 if (I.first == Result) {
4626 I.second.push_back(CaseVal);
4630 UniqueResults.push_back(
4640 SwitchCaseResultVectorTy &UniqueResults,
4644 for (
auto &I : SI->
cases()) {
4654 if (Results.size() > 1)
4660 PHI = Results[0].first;
4661 else if (PHI != Results[0].
first)
4672 DefaultResults.size() == 1 ? DefaultResults.begin()->second :
nullptr;
4673 if ((!DefaultResult &&
4692 Constant *DefaultResult, Value *Condition,
4694 assert(ResultVector.size() == 2 &&
4695 "We should have exactly two unique results at this point");
4698 if (ResultVector[0].
second.size() == 1 &&
4699 ResultVector[1].second.size() == 1) {
4700 ConstantInt *
const FirstCase = ResultVector[0].second[0];
4701 ConstantInt *
const SecondCase = ResultVector[1].second[0];
4703 bool DefaultCanTrigger = DefaultResult;
4704 Value *SelectValue = ResultVector[1].first;
4705 if (DefaultCanTrigger) {
4706 Value *
const ValueCompare =
4707 Builder.
CreateICmpEQ(Condition, SecondCase,
"switch.selectcmp");
4709 DefaultResult,
"switch.select");
4711 Value *
const ValueCompare =
4712 Builder.
CreateICmpEQ(Condition, FirstCase,
"switch.selectcmp");
4714 SelectValue,
"switch.select");
4753 SwitchCaseResultVectorTy UniqueResults;
4759 if (UniqueResults.size() != 2)
4761 assert(PHI !=
nullptr &&
"PHI for value select not found");
4764 Value *SelectValue =
4777 class SwitchLookupTable {
4788 Value *BuildLookup(Value *Index,
IRBuilder<> &Builder);
4792 static bool WouldFitInRegister(
const DataLayout &DL, uint64_t TableSize,
4835 SwitchLookupTable::SwitchLookupTable(
4839 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
4840 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
4841 assert(Values.size() &&
"Can't build lookup table without values!");
4842 assert(TableSize >= Values.size() &&
"Can't fit values in table!");
4845 SingleValue = Values.begin()->second;
4851 for (
size_t I = 0,
E = Values.size(); I !=
E; ++
I) {
4856 uint64_t Idx = (CaseVal->
getValue() - Offset->
getValue()).getLimitedValue();
4857 TableContents[Idx] = CaseRes;
4859 if (CaseRes != SingleValue)
4860 SingleValue =
nullptr;
4864 if (Values.size() < TableSize) {
4866 "Need a default value to fill the lookup table holes.");
4868 for (uint64_t I = 0; I < TableSize; ++
I) {
4869 if (!TableContents[I])
4870 TableContents[
I] = DefaultValue;
4873 if (DefaultValue != SingleValue)
4874 SingleValue =
nullptr;
4880 Kind = SingleValueKind;
4886 if (isa<IntegerType>(ValueType)) {
4887 bool LinearMappingPossible =
true;
4890 assert(TableSize >= 2 &&
"Should be a SingleValue table.");
4892 for (uint64_t I = 0; I < TableSize; ++
I) {
4897 LinearMappingPossible =
false;
4902 APInt Dist = Val - PrevVal;
4905 }
else if (Dist != DistToPrev) {
4906 LinearMappingPossible =
false;
4912 if (LinearMappingPossible) {
4913 LinearOffset = cast<ConstantInt>(TableContents[0]);
4914 LinearMultiplier = ConstantInt::get(M.
getContext(), DistToPrev);
4915 Kind = LinearMapKind;
4922 if (WouldFitInRegister(DL, TableSize, ValueType)) {
4925 for (uint64_t I = TableSize; I > 0; --
I) {
4928 if (!isa<UndefValue>(TableContents[I - 1])) {
4929 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4930 TableInt |= Val->
getValue().
zext(TableInt.getBitWidth());
4933 BitMap = ConstantInt::get(M.
getContext(), TableInt);
4934 BitMapElementTy =
IT;
4941 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4942 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4945 GlobalVariable::PrivateLinkage, Initializer,
4946 "switch.table." + FuncName);
4947 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
4951 Value *SwitchLookupTable::BuildLookup(Value *Index,
IRBuilder<> &Builder) {
4953 case SingleValueKind:
4955 case LinearMapKind: {
4958 false,
"switch.idx.cast");
4959 if (!LinearMultiplier->isOne())
4960 Result = Builder.
CreateMul(Result, LinearMultiplier,
"switch.idx.mult");
4961 if (!LinearOffset->isZero())
4962 Result = Builder.
CreateAdd(Result, LinearOffset,
"switch.offset");
4976 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->
getBitWidth()),
4980 Value *DownShifted =
4981 Builder.
CreateLShr(BitMap, ShiftAmt,
"switch.downshift");
4983 return Builder.
CreateTrunc(DownShifted, BitMapElementTy,
"switch.masked");
4988 uint64_t TableSize =
4990 if (TableSize > (1ULL << (IT->
getBitWidth() - 1)))
4993 "switch.tableidx.zext");
4995 Value *GEPIndices[] = {Builder.
getInt32(0), Index};
4997 GEPIndices,
"switch.gep");
4998 return Builder.
CreateLoad(GEP,
"switch.load");
5004 bool SwitchLookupTable::WouldFitInRegister(
const DataLayout &DL,
5006 Type *ElementType) {
5025 if (SI->
getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5028 bool AllTablesFitInRegister =
true;
5029 bool HasIllegalType =
false;
5030 for (
const auto &I : ResultTypes) {
5031 Type *Ty = I.second;
5034 HasIllegalType = HasIllegalType || !TTI.
isTypeLegal(Ty);
5037 AllTablesFitInRegister =
5038 AllTablesFitInRegister &&
5039 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5044 if (HasIllegalType && !AllTablesFitInRegister)
5049 if (AllTablesFitInRegister)
5085 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5106 DefaultValue, CmpOp1,
true);
5107 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5112 for (
auto ValuePair : Values) {
5114 ValuePair.second, CmpOp1,
true);
5115 if (!CaseConst || CaseConst == DefaultConst)
5117 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5118 "Expect true or false as compare result.");
5132 if (DefaultConst == FalseConst) {
5135 ++NumTableCmpReuses;
5138 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5139 RangeCmp, ConstantInt::get(RangeCmp->
getType(), 1),
"inverted.cmp",
5142 ++NumTableCmpReuses;
5188 MinCaseVal = CaseVal;
5190 MaxCaseVal = CaseVal;
5195 if (!
GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5200 for (
const auto &I : Results) {
5203 if (!ResultLists.
count(PHI))
5205 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5211 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5214 uint64_t NumResults = ResultLists[PHIs[0]].
size();
5217 bool TableHasHoles = (NumResults < TableSize);
5222 bool HasDefaultResults =
5224 DefaultResultsList,
DL, TTI);
5226 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5231 if (!DL.fitsInLegalInteger(TableSize))
5235 for (
const auto &I : DefaultResultsList) {
5238 DefaultResults[PHI] = Result;
5257 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5258 assert(MaxTableSize >= TableSize &&
5259 "It is impossible for a switch to have more entries than the max "
5260 "representable value of its input integer type's size.");
5265 const bool DefaultIsReachable =
5267 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5270 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5276 TableIndex, ConstantInt::get(MinCaseVal->
getType(), TableSize));
5289 MaskBB->
setName(
"switch.hole_check");
5290 LookupBB = BasicBlock::Create(Mod.
getContext(),
"switch.lookup",
5296 APInt MaskInt(TableSizePowOf2, 0);
5297 APInt One(TableSizePowOf2, 1);
5299 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5300 for (
size_t I = 0,
E = ResultList.size(); I !=
E; ++
I) {
5301 uint64_t Idx = (ResultList[
I].first->getValue() - MinCaseVal->
getValue())
5303 MaskInt |= One << Idx;
5313 Value *Shifted = Builder.
CreateLShr(TableMask, MaskIndex,
"switch.shifted");
5315 Shifted, Type::getInt1Ty(Mod.
getContext()),
"switch.lobit");
5322 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5329 bool ReturnedEarly =
false;
5330 for (
size_t I = 0,
E = PHIs.size(); I !=
E; ++
I) {
5332 const ResultListTy &ResultList = ResultLists[PHI];
5335 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5337 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5340 Value *Result = Table.BuildLookup(TableIndex, Builder);
5347 ReturnedEarly =
true;
5353 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5379 ++NumLookupTablesHoles;
5385 uint64_t Diff = (uint64_t)Values.
back() - (uint64_t)Values.
front();
5386 uint64_t Range = Diff + 1;
5387 uint64_t NumCases = Values.
size();
5389 uint64_t MinDensity = 40;
5391 return NumCases * 100 >= Range * MinDensity;
5406 if (CondTy->getIntegerBitWidth() > 64 ||
5419 for (
auto &C : SI->
cases())
5428 int64_t
Base = Values[0];
5429 for (
auto &V : Values)
5436 for (
auto &V : Values)
5451 unsigned Shift =
Log2_64(GCD);
5452 for (
auto &V : Values)
5453 V = (int64_t)((uint64_t)V >> Shift);
5471 auto *ShiftC = ConstantInt::get(Ty, Shift);
5473 auto *LShr = Builder.
CreateLShr(Sub, ShiftC);
5474 auto *Shl = Builder.
CreateShl(Sub, Ty->getBitWidth() - Shift);
5475 auto *Rot = Builder.
CreateOr(LShr, Shl);
5478 for (
auto Case : SI->
cases()) {
5479 auto *Orig = Case.getCaseValue();
5480 auto Sub = Orig->getValue() -
APInt(Ty->getBitWidth(), Base);
5482 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5490 if (isValueEqualityComparison(SI)) {
5494 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5495 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5500 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5506 while (isa<DbgInfoIntrinsic>(BBI))
5509 if (FoldValueComparisonIntoPredecessors(SI, Builder))
5510 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5515 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5519 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5522 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5525 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5533 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5536 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5543 bool Changed =
false;
5574 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5606 if (isa<PHINode>(*Succ->begin()))
5610 if (BB == OtherPred)
5616 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I) {
5629 "unexpected successor");
5635 for (
auto I = OtherPred->begin(),
E = OtherPred->end(); I !=
E;) {
5638 if (isa<DbgInfoIntrinsic>(Inst))
5645 Succ->removePredecessor(BB);
5656 bool SimplifyCFGOpt::SimplifyUncondBranch(
BranchInst *BI,
5669 bool NeedCanonicalLoop =
5671 (LoopHeaders && (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5679 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5680 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5681 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5683 if (I->isTerminator() &&
5685 BonusInstThreshold, AC))
5692 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I) {
5703 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5711 if (!PPred || (PredPred && PredPred != PPred))
5722 if (isValueEqualityComparison(BI)) {
5727 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5728 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5734 while (isa<DbgInfoIntrinsic>(I))
5737 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5738 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5739 }
else if (&*I == cast<Instruction>(BI->
getCondition())) {
5742 while (isa<DbgInfoIntrinsic>(I))
5744 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5745 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5757 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5772 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5781 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5790 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5798 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5807 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5815 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5819 if (
BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5822 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5827 if (
BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5830 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) |
true;
5854 if (i == I->
getParent()->
end() || i->mayHaveSideEffects())
5859 if (
GEP->getPointerOperand() ==
I)
5867 if (
LoadInst *LI = dyn_cast<LoadInst>(Use))
5868 if (!LI->isVolatile())
5869 return LI->getPointerAddressSpace() == 0;
5872 if (
StoreInst *SI = dyn_cast<StoreInst>(Use))
5873 if (!SI->isVolatile())
5874 return SI->getPointerAddressSpace() == 0 &&
5875 SI->getPointerOperand() ==
I;
5879 return CS.getCalledValue() ==
I;
5893 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
5912 bool Changed =
false;
5921 DEBUG(
dbgs() <<
"Removing BB: \n" << *BB);
5948 if (PN->getNumIncomingValues() == 2)
5954 if (SimplifyUncondBranch(BI, Builder))
5957 if (SimplifyCondBranch(BI, Builder))
5961 if (SimplifyReturn(RI, Builder))
5964 if (SimplifyResume(RI, Builder))
5968 if (SimplifyCleanupReturn(RI))
5971 if (SimplifySwitch(SI, Builder))
5975 if (SimplifyUnreachable(UI))
5979 if (SimplifyIndirectBr(IBI))
5994 bool LateSimplifyCFG) {
5996 BonusInstThreshold, AC, LoopHeaders, LateSimplifyCFG)
const Use & getOperandUse(unsigned i) const
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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")))
Return a value (possibly void), from a function.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
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.
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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 * 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.
bool isSizeLargerThan(uint64_t MaxSize) const
uint64_t getZExtValue() const
Get zero extended value.
DiagnosticInfoOptimizationBase::Argument NV
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.
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
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...
void swapSuccessors()
Swap the successors of this branch instruction.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
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.
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"))
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
const T & front() const
front - Get the first element.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
static bool removeUndefIntroducingPredecessor(BasicBlock *BB)
If BB has an incoming value that will always trigger undefined behavior (eg.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
void DeleteDeadBlock(BasicBlock *BB)
Delete the specified block, which must have no predecessors.
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
Value * getValue() const
Convenience accessor.
This class represents a function call, abstracting a target machine's calling convention.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
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)"))
static bool mergeCleanupPad(CleanupReturnInst *RI)
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
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.
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 isTokenTy() const
Return true if this is 'token'.
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select)
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.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
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...
static unsigned ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
const Instruction & front() const
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
An instruction for reading from memory.
CleanupPadInst * getCleanupPad() const
Convenience accessor.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
static Constant * getTrue(Type *Ty)
For a boolean type or a vector of boolean type, return true or a vector with every element true...
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...
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...
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 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...
uint64_t getArrayNumElements() const
static ConstantInt * GetConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
StringRef getName() const
Return a constant reference to the value's name.
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I)
Check if passing a value to an instruction will cause undefined behavior.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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...
The address of a basic block.
bool match(Val *V, const Pattern &P)
bool isUnconditional() const
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, AssumptionCache *AC, 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 ...
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
static bool SinkThenElseCodeToEnd(BranchInst *BI1)
Given an unconditional branch that goes to BBEnd, check whether BBEnd has only two predecessors and t...
This class represents the LLVM 'select' instruction.
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond)
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
const APInt & getValue() const
Return the constant as an APInt value reference.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
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...
A Use represents the edge between a Value definition and its users.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
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.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static const DILocation * getMergedLocation(const DILocation *LocA, const DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
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.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
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.
LLVM_NODISCARD bool empty() const
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...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
void assign(size_type NumElts, const T &Elt)
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
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)
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 bool isSwitchDense(ArrayRef< int64_t > Values)
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.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static void MapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
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...
bool sgt(const APInt &RHS) const
Signed greather than comparison.
BasicBlock * getSuccessor(unsigned i) const
This class represents a no-op cast from one type to another.
bool empty() const
Determine if the SetVector is empty or not.
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static Value * ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder)
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.
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"))
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
LLVM_NODISCARD char front() const
front - Get the first character in the string.
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
void takeName(Value *V)
Transfer the name from V to this value.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
size_t size() const
size - Get the array size.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
BasicBlock * getNormalDest() const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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)
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.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
initializer< Ty > init(const Ty &Val)
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...
Subclasses of this class are all able to terminate a basic block.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
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)
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.
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<&g...
static bool HasBranchWeights(const Instruction *I)
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)
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
UnreachableInst * CreateUnreachable()
Conditional or Unconditional Branch instruction.
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder)
Turn a switch with two reachable destinations into an integer range comparison and branch...
This function has undefined behavior.
This is an important base class in LLVM.
const Value * getCondition() 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?
int64_t getSExtValue() const
Get sign extended value.
static bool CasesAreContiguous(SmallVectorImpl< ConstantInt * > &Cases)
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
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)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
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.
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...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
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.)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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...
const InstListType & getInstList() const
Return the underlying instruction list container.
static bool canSinkInstructions(ArrayRef< Instruction * > Insts, DenseMap< Instruction *, SmallVector< Value *, 4 >> &PHIOperands)
This instruction compares its operands according to the predicate given to the constructor.
static const unsigned End
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
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.
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="")
self_iterator getIterator()
unsigned getIntegerBitWidth() const
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Predicate getPredicate() const
Return the predicate for this instruction.
bool pred_empty(const BasicBlock *BB)
static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB)
Return true if the given instruction is available in its predecessor block.
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
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...
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
LLVM_NODISCARD bool empty() const
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"))
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 isPointerTy() const
True if this is an instance of PointerType.
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)
LLVMContext & getContext() const
All values hold a context through their type.
static bool sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
const Value * getTrueValue() const
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...
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
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="")
const T & back() const
back - Get the last element.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
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...
bool isTerminator() const
BasicBlock * getUnwindDest() const
bool isConditional() const
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...
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
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"))
BasicBlock * getUnwindDest() 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.
bool fitsInLegalInteger(unsigned Width) const
Returns true if the specified type fits in a native integer type supported by the CPU...
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...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool cannotDuplicate() const
Determine if the call cannot be duplicated.
unsigned getNumSuccessors() const
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.
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
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.
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
This class represents a range of values.
This is the common base class for debug info intrinsics.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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 ...
const APInt & getLower() const
Return the lower value for this range.
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.
BasicBlock * getBasicBlock() const
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)
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...
pred_range predecessors(BasicBlock *BB)
const BasicBlock & getEntryBlock() const
bool isConvergent() const
Determine if the call is convergent.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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.
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false...
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"))
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
True if this is an instance of IntegerType.
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.
Value * getCondition() const
iterator insert(iterator I, T &&Elt)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void removeUnwindEdge(BasicBlock *BB)
Replace 'BB's terminator with one that does not have an unwind successor block.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
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 Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
BasicBlock * getSuccessor(unsigned idx) const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
iterator insert(iterator where, pointer New)
BasicBlock * getDefaultDest() const
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr)
Attempts to merge a block into its predecessor, if possible.
void registerAssumption(CallInst *CI)
Add an .assume intrinsic to this function's cache.
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool removeEmptyCleanup(CleanupReturnInst *RI)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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.
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
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.
static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder)
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, const TargetTransformInfo &TTI)
Speculate a conditional basic block flattening the CFG.
static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, const TargetTransformInfo &TTI)
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...
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
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...
void setCondition(Value *V)
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
const APInt & getUpper() const
Return the upper value for this range.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Constant * LookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
If V is a Constant, return it.
user_iterator user_begin()
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...
LLVMContext & getContext() const
Get the context in which this basic block lives.
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)
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.
succ_range successors(BasicBlock *BB)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDefaultDest(BasicBlock *DefaultCase)
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)
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsFalse=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if RHS is known to be implied true by LHS.
static PHINode * FindPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i...
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
APInt zext(unsigned width) const
Zero extend to a new width.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
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)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, unsigned BonusInstThreshold, AssumptionCache *AC=nullptr, SmallPtrSetImpl< BasicBlock * > *LoopHeaders=nullptr, bool LateSimplifyCFG=false)
This function is used to do simplification of a CFG.
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.
static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI)
static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI, unsigned BonusInstThreshold, AssumptionCache *AC)
This is called when we find an icmp instruction (a seteq/setne with a constant) as the only instructi...
bool isThreadDependent() const
Return true if the value can vary between threads.
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 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...
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
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.
const BasicBlock * getParent() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
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...
A wrapper class for inspecting calls to intrinsic functions.
LLVMContext & getContext() const
Get the global data context.
bool isVoidTy() const
Return true if this is 'void'.
bool slt(const APInt &RHS) const
Signed less than comparison.
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...