1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetOperations.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/NoFolder.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/PatternMatch.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/ValueMapper.h"
53 using namespace PatternMatch;
55 #define DEBUG_TYPE "simplifycfg"
57 // Chosen as 2 so as to be cheap, but still to have enough power to fold
58 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59 // To catch this, we need to fold a compare and a select, hence '2' being the
60 // minimum reasonable default.
61 static cl::opt<unsigned>
62 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
66 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
70 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
73 static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
77 static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
83 static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
88 static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
93 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
94 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
95 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
96 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
97 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
98 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
99 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
102 // The first field contains the value that the switch produces when a certain
103 // case group is selected, and the second field is a vector containing the
104 // cases composing the case group.
105 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
106 SwitchCaseResultVectorTy;
107 // The first field contains the phi node that generates a result of the switch
108 // and the second field contains the value generated for a certain case in the
109 // switch for that PHI.
110 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
112 /// ValueEqualityComparisonCase - Represents a case of a switch.
113 struct ValueEqualityComparisonCase {
117 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
118 : Value(Value), Dest(Dest) {}
120 bool operator<(ValueEqualityComparisonCase RHS) const {
121 // Comparing pointers is ok as we only rely on the order for uniquing.
122 return Value < RHS.Value;
125 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
128 class SimplifyCFGOpt {
129 const TargetTransformInfo &TTI;
130 const DataLayout &DL;
131 unsigned BonusInstThreshold;
133 Value *isValueEqualityComparison(TerminatorInst *TI);
134 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
135 std::vector<ValueEqualityComparisonCase> &Cases);
136 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
138 IRBuilder<> &Builder);
139 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
140 IRBuilder<> &Builder);
142 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
143 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
144 bool SimplifySingleResume(ResumeInst *RI);
145 bool SimplifyCommonResume(ResumeInst *RI);
146 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
147 bool SimplifyUnreachable(UnreachableInst *UI);
148 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
149 bool SimplifyIndirectBr(IndirectBrInst *IBI);
150 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
151 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
154 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
155 unsigned BonusInstThreshold, AssumptionCache *AC)
156 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
157 bool run(BasicBlock *BB);
161 /// Return true if it is safe to merge these two
162 /// terminator instructions together.
163 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
164 if (SI1 == SI2) return false; // Can't merge with self!
166 // It is not safe to merge these two switch instructions if they have a common
167 // successor, and if that successor has a PHI node, and if *that* PHI node has
168 // conflicting incoming values from the two switch blocks.
169 BasicBlock *SI1BB = SI1->getParent();
170 BasicBlock *SI2BB = SI2->getParent();
171 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
173 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
174 if (SI1Succs.count(*I))
175 for (BasicBlock::iterator BBI = (*I)->begin();
176 isa<PHINode>(BBI); ++BBI) {
177 PHINode *PN = cast<PHINode>(BBI);
178 if (PN->getIncomingValueForBlock(SI1BB) !=
179 PN->getIncomingValueForBlock(SI2BB))
186 /// Return true if it is safe and profitable to merge these two terminator
187 /// instructions together, where SI1 is an unconditional branch. PhiNodes will
188 /// store all PHI nodes in common successors.
189 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
192 SmallVectorImpl<PHINode*> &PhiNodes) {
193 if (SI1 == SI2) return false; // Can't merge with self!
194 assert(SI1->isUnconditional() && SI2->isConditional());
196 // We fold the unconditional branch if we can easily update all PHI nodes in
197 // common successors:
198 // 1> We have a constant incoming value for the conditional branch;
199 // 2> We have "Cond" as the incoming value for the unconditional branch;
200 // 3> SI2->getCondition() and Cond have same operands.
201 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
202 if (!Ci2) return false;
203 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
204 Cond->getOperand(1) == Ci2->getOperand(1)) &&
205 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
206 Cond->getOperand(1) == Ci2->getOperand(0)))
209 BasicBlock *SI1BB = SI1->getParent();
210 BasicBlock *SI2BB = SI2->getParent();
211 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
212 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
213 if (SI1Succs.count(*I))
214 for (BasicBlock::iterator BBI = (*I)->begin();
215 isa<PHINode>(BBI); ++BBI) {
216 PHINode *PN = cast<PHINode>(BBI);
217 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
218 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
220 PhiNodes.push_back(PN);
225 /// Update PHI nodes in Succ to indicate that there will now be entries in it
226 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
227 /// will be the same as those coming in from ExistPred, an existing predecessor
229 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
230 BasicBlock *ExistPred) {
231 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
234 for (BasicBlock::iterator I = Succ->begin();
235 (PN = dyn_cast<PHINode>(I)); ++I)
236 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
239 /// Compute an abstract "cost" of speculating the given instruction,
240 /// which is assumed to be safe to speculate. TCC_Free means cheap,
241 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
243 static unsigned ComputeSpeculationCost(const User *I,
244 const TargetTransformInfo &TTI) {
245 assert(isSafeToSpeculativelyExecute(I) &&
246 "Instruction is not safe to speculatively execute!");
247 return TTI.getUserCost(I);
250 /// If we have a merge point of an "if condition" as accepted above,
251 /// return true if the specified value dominates the block. We
252 /// don't handle the true generality of domination here, just a special case
253 /// which works well enough for us.
255 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
256 /// see if V (which must be an instruction) and its recursive operands
257 /// that do not dominate BB have a combined cost lower than CostRemaining and
258 /// are non-trapping. If both are true, the instruction is inserted into the
259 /// set and true is returned.
261 /// The cost for most non-trapping instructions is defined as 1 except for
262 /// Select whose cost is 2.
264 /// After this function returns, CostRemaining is decreased by the cost of
265 /// V plus its non-dominating operands. If that cost is greater than
266 /// CostRemaining, false is returned and CostRemaining is undefined.
267 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
268 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
269 unsigned &CostRemaining,
270 const TargetTransformInfo &TTI,
271 unsigned Depth = 0) {
272 Instruction *I = dyn_cast<Instruction>(V);
274 // Non-instructions all dominate instructions, but not all constantexprs
275 // can be executed unconditionally.
276 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
281 BasicBlock *PBB = I->getParent();
283 // We don't want to allow weird loops that might have the "if condition" in
284 // the bottom of this block.
285 if (PBB == BB) return false;
287 // If this instruction is defined in a block that contains an unconditional
288 // branch to BB, then it must be in the 'conditional' part of the "if
289 // statement". If not, it definitely dominates the region.
290 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
291 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
294 // If we aren't allowing aggressive promotion anymore, then don't consider
295 // instructions in the 'if region'.
296 if (!AggressiveInsts) return false;
298 // If we have seen this instruction before, don't count it again.
299 if (AggressiveInsts->count(I)) return true;
301 // Okay, it looks like the instruction IS in the "condition". Check to
302 // see if it's a cheap instruction to unconditionally compute, and if it
303 // only uses stuff defined outside of the condition. If so, hoist it out.
304 if (!isSafeToSpeculativelyExecute(I))
307 unsigned Cost = ComputeSpeculationCost(I, TTI);
309 // Allow exactly one instruction to be speculated regardless of its cost
310 // (as long as it is safe to do so).
311 // This is intended to flatten the CFG even if the instruction is a division
312 // or other expensive operation. The speculation of an expensive instruction
313 // is expected to be undone in CodeGenPrepare if the speculation has not
314 // enabled further IR optimizations.
315 if (Cost > CostRemaining &&
316 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
319 // Avoid unsigned wrap.
320 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
322 // Okay, we can only really hoist these out if their operands do
323 // not take us over the cost threshold.
324 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
325 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
328 // Okay, it's safe to do this! Remember this instruction.
329 AggressiveInsts->insert(I);
333 /// Extract ConstantInt from value, looking through IntToPtr
334 /// and PointerNullValue. Return NULL if value is not a constant int.
335 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
336 // Normal constant int.
337 ConstantInt *CI = dyn_cast<ConstantInt>(V);
338 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
341 // This is some kind of pointer constant. Turn it into a pointer-sized
342 // ConstantInt if possible.
343 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
345 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
346 if (isa<ConstantPointerNull>(V))
347 return ConstantInt::get(PtrTy, 0);
349 // IntToPtr const int.
350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
351 if (CE->getOpcode() == Instruction::IntToPtr)
352 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
353 // The constant is very likely to have the right type already.
354 if (CI->getType() == PtrTy)
357 return cast<ConstantInt>
358 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
365 /// Given a chain of or (||) or and (&&) comparison of a value against a
366 /// constant, this will try to recover the information required for a switch
368 /// It will depth-first traverse the chain of comparison, seeking for patterns
369 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
370 /// representing the different cases for the switch.
371 /// Note that if the chain is composed of '||' it will build the set of elements
372 /// that matches the comparisons (i.e. any of this value validate the chain)
373 /// while for a chain of '&&' it will build the set elements that make the test
375 struct ConstantComparesGatherer {
376 const DataLayout &DL;
377 Value *CompValue; /// Value found for the switch comparison
378 Value *Extra; /// Extra clause to be checked before the switch
379 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
380 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
382 /// Construct and compute the result for the comparison instruction Cond
383 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
384 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
389 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
390 ConstantComparesGatherer &
391 operator=(const ConstantComparesGatherer &) = delete;
395 /// Try to set the current value used for the comparison, it succeeds only if
396 /// it wasn't set before or if the new value is the same as the old one
397 bool setValueOnce(Value *NewVal) {
398 if(CompValue && CompValue != NewVal) return false;
400 return (CompValue != nullptr);
403 /// Try to match Instruction "I" as a comparison against a constant and
404 /// populates the array Vals with the set of values that match (or do not
405 /// match depending on isEQ).
406 /// Return false on failure. On success, the Value the comparison matched
407 /// against is placed in CompValue.
408 /// If CompValue is already set, the function is expected to fail if a match
409 /// is found but the value compared to is different.
410 bool matchInstruction(Instruction *I, bool isEQ) {
411 // If this is an icmp against a constant, handle this as one of the cases.
414 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
415 (C = GetConstantInt(I->getOperand(1), DL)))) {
422 // Pattern match a special case
423 // (x & ~2^x) == y --> x == y || x == y|2^x
424 // This undoes a transformation done by instcombine to fuse 2 compares.
425 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
426 if (match(ICI->getOperand(0),
427 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
428 APInt Not = ~RHSC->getValue();
429 if (Not.isPowerOf2()) {
430 // If we already have a value for the switch, it has to match!
431 if(!setValueOnce(RHSVal))
435 Vals.push_back(ConstantInt::get(C->getContext(),
436 C->getValue() | Not));
442 // If we already have a value for the switch, it has to match!
443 if(!setValueOnce(ICI->getOperand(0)))
448 return ICI->getOperand(0);
451 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
452 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
453 ICI->getPredicate(), C->getValue());
455 // Shift the range if the compare is fed by an add. This is the range
456 // compare idiom as emitted by instcombine.
457 Value *CandidateVal = I->getOperand(0);
458 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
459 Span = Span.subtract(RHSC->getValue());
460 CandidateVal = RHSVal;
463 // If this is an and/!= check, then we are looking to build the set of
464 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
467 Span = Span.inverse();
469 // If there are a ton of values, we don't want to make a ginormous switch.
470 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
474 // If we already have a value for the switch, it has to match!
475 if(!setValueOnce(CandidateVal))
478 // Add all values from the range to the set
479 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
480 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
487 /// Given a potentially 'or'd or 'and'd together collection of icmp
488 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
489 /// the value being compared, and stick the list constants into the Vals
491 /// One "Extra" case is allowed to differ from the other.
492 void gather(Value *V) {
493 Instruction *I = dyn_cast<Instruction>(V);
494 bool isEQ = (I->getOpcode() == Instruction::Or);
496 // Keep a stack (SmallVector for efficiency) for depth-first traversal
497 SmallVector<Value *, 8> DFT;
502 while(!DFT.empty()) {
503 V = DFT.pop_back_val();
505 if (Instruction *I = dyn_cast<Instruction>(V)) {
506 // If it is a || (or && depending on isEQ), process the operands.
507 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
508 DFT.push_back(I->getOperand(1));
509 DFT.push_back(I->getOperand(0));
513 // Try to match the current instruction
514 if (matchInstruction(I, isEQ))
515 // Match succeed, continue the loop
519 // One element of the sequence of || (or &&) could not be match as a
520 // comparison against the same value as the others.
521 // We allow only one "Extra" case to be checked before the switch
526 // Failed to parse a proper sequence, abort now
535 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
536 Instruction *Cond = nullptr;
537 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
538 Cond = dyn_cast<Instruction>(SI->getCondition());
539 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
540 if (BI->isConditional())
541 Cond = dyn_cast<Instruction>(BI->getCondition());
542 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
543 Cond = dyn_cast<Instruction>(IBI->getAddress());
546 TI->eraseFromParent();
547 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
550 /// Return true if the specified terminator checks
551 /// to see if a value is equal to constant integer value.
552 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 // Do not permit merging of large switch instructions into their
556 // predecessors unless there is only one predecessor.
557 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
558 pred_end(SI->getParent())) <= 128)
559 CV = SI->getCondition();
560 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
561 if (BI->isConditional() && BI->getCondition()->hasOneUse())
562 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
563 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
564 CV = ICI->getOperand(0);
567 // Unwrap any lossless ptrtoint cast.
569 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
570 Value *Ptr = PTII->getPointerOperand();
571 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
578 /// Given a value comparison instruction,
579 /// decode all of the 'cases' that it represents and return the 'default' block.
580 BasicBlock *SimplifyCFGOpt::
581 GetValueEqualityComparisonCases(TerminatorInst *TI,
582 std::vector<ValueEqualityComparisonCase>
584 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
585 Cases.reserve(SI->getNumCases());
586 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
587 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
588 i.getCaseSuccessor()));
589 return SI->getDefaultDest();
592 BranchInst *BI = cast<BranchInst>(TI);
593 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
594 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
595 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
598 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
602 /// Given a vector of bb/value pairs, remove any entries
603 /// in the list that match the specified block.
604 static void EliminateBlockCases(BasicBlock *BB,
605 std::vector<ValueEqualityComparisonCase> &Cases) {
606 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
609 /// Return true if there are any keys in C1 that exist in C2 as well.
611 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
612 std::vector<ValueEqualityComparisonCase > &C2) {
613 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
615 // Make V1 be smaller than V2.
616 if (V1->size() > V2->size())
619 if (V1->size() == 0) return false;
620 if (V1->size() == 1) {
622 ConstantInt *TheVal = (*V1)[0].Value;
623 for (unsigned i = 0, e = V2->size(); i != e; ++i)
624 if (TheVal == (*V2)[i].Value)
628 // Otherwise, just sort both lists and compare element by element.
629 array_pod_sort(V1->begin(), V1->end());
630 array_pod_sort(V2->begin(), V2->end());
631 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
632 while (i1 != e1 && i2 != e2) {
633 if ((*V1)[i1].Value == (*V2)[i2].Value)
635 if ((*V1)[i1].Value < (*V2)[i2].Value)
643 /// If TI is known to be a terminator instruction and its block is known to
644 /// only have a single predecessor block, check to see if that predecessor is
645 /// also a value comparison with the same value, and if that comparison
646 /// determines the outcome of this comparison. If so, simplify TI. This does a
647 /// very limited form of jump threading.
648 bool SimplifyCFGOpt::
649 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
651 IRBuilder<> &Builder) {
652 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
653 if (!PredVal) return false; // Not a value comparison in predecessor.
655 Value *ThisVal = isValueEqualityComparison(TI);
656 assert(ThisVal && "This isn't a value comparison!!");
657 if (ThisVal != PredVal) return false; // Different predicates.
659 // TODO: Preserve branch weight metadata, similarly to how
660 // FoldValueComparisonIntoPredecessors preserves it.
662 // Find out information about when control will move from Pred to TI's block.
663 std::vector<ValueEqualityComparisonCase> PredCases;
664 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
666 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
668 // Find information about how control leaves this block.
669 std::vector<ValueEqualityComparisonCase> ThisCases;
670 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
671 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
673 // If TI's block is the default block from Pred's comparison, potentially
674 // simplify TI based on this knowledge.
675 if (PredDef == TI->getParent()) {
676 // If we are here, we know that the value is none of those cases listed in
677 // PredCases. If there are any cases in ThisCases that are in PredCases, we
679 if (!ValuesOverlap(PredCases, ThisCases))
682 if (isa<BranchInst>(TI)) {
683 // Okay, one of the successors of this condbr is dead. Convert it to a
685 assert(ThisCases.size() == 1 && "Branch can only have one case!");
686 // Insert the new branch.
687 Instruction *NI = Builder.CreateBr(ThisDef);
690 // Remove PHI node entries for the dead edge.
691 ThisCases[0].Dest->removePredecessor(TI->getParent());
693 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
694 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
696 EraseTerminatorInstAndDCECond(TI);
700 SwitchInst *SI = cast<SwitchInst>(TI);
701 // Okay, TI has cases that are statically dead, prune them away.
702 SmallPtrSet<Constant*, 16> DeadCases;
703 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
704 DeadCases.insert(PredCases[i].Value);
706 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
707 << "Through successor TI: " << *TI);
709 // Collect branch weights into a vector.
710 SmallVector<uint32_t, 8> Weights;
711 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
712 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
714 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
716 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
717 Weights.push_back(CI->getValue().getZExtValue());
719 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
721 if (DeadCases.count(i.getCaseValue())) {
723 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
726 i.getCaseSuccessor()->removePredecessor(TI->getParent());
730 if (HasWeight && Weights.size() >= 2)
731 SI->setMetadata(LLVMContext::MD_prof,
732 MDBuilder(SI->getParent()->getContext()).
733 createBranchWeights(Weights));
735 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
739 // Otherwise, TI's block must correspond to some matched value. Find out
740 // which value (or set of values) this is.
741 ConstantInt *TIV = nullptr;
742 BasicBlock *TIBB = TI->getParent();
743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].Dest == TIBB) {
746 return false; // Cannot handle multiple values coming to this block.
747 TIV = PredCases[i].Value;
749 assert(TIV && "No edge from pred to succ?");
751 // Okay, we found the one constant that our value can be if we get into TI's
752 // BB. Find out which successor will unconditionally be branched to.
753 BasicBlock *TheRealDest = nullptr;
754 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
755 if (ThisCases[i].Value == TIV) {
756 TheRealDest = ThisCases[i].Dest;
760 // If not handled by any explicit cases, it is handled by the default case.
761 if (!TheRealDest) TheRealDest = ThisDef;
763 // Remove PHI node entries for dead edges.
764 BasicBlock *CheckEdge = TheRealDest;
765 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
766 if (*SI != CheckEdge)
767 (*SI)->removePredecessor(TIBB);
771 // Insert the new branch.
772 Instruction *NI = Builder.CreateBr(TheRealDest);
775 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
776 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
778 EraseTerminatorInstAndDCECond(TI);
783 /// This class implements a stable ordering of constant
784 /// integers that does not depend on their address. This is important for
785 /// applications that sort ConstantInt's to ensure uniqueness.
786 struct ConstantIntOrdering {
787 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
788 return LHS->getValue().ult(RHS->getValue());
793 static int ConstantIntSortPredicate(ConstantInt *const *P1,
794 ConstantInt *const *P2) {
795 const ConstantInt *LHS = *P1;
796 const ConstantInt *RHS = *P2;
797 if (LHS->getValue().ult(RHS->getValue()))
799 if (LHS->getValue() == RHS->getValue())
804 static inline bool HasBranchWeights(const Instruction* I) {
805 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
806 if (ProfMD && ProfMD->getOperand(0))
807 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
808 return MDS->getString().equals("branch_weights");
813 /// Get Weights of a given TerminatorInst, the default weight is at the front
814 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
816 static void GetBranchWeights(TerminatorInst *TI,
817 SmallVectorImpl<uint64_t> &Weights) {
818 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
820 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
821 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
822 Weights.push_back(CI->getValue().getZExtValue());
825 // If TI is a conditional eq, the default case is the false case,
826 // and the corresponding branch-weight data is at index 2. We swap the
827 // default weight to be the first entry.
828 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
829 assert(Weights.size() == 2);
830 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
831 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
832 std::swap(Weights.front(), Weights.back());
836 /// Keep halving the weights until all can fit in uint32_t.
837 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
838 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
839 if (Max > UINT_MAX) {
840 unsigned Offset = 32 - countLeadingZeros(Max);
841 for (uint64_t &I : Weights)
846 /// The specified terminator is a value equality comparison instruction
847 /// (either a switch or a branch on "X == c").
848 /// See if any of the predecessors of the terminator block are value comparisons
849 /// on the same value. If so, and if safe to do so, fold them together.
850 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
851 IRBuilder<> &Builder) {
852 BasicBlock *BB = TI->getParent();
853 Value *CV = isValueEqualityComparison(TI); // CondVal
854 assert(CV && "Not a comparison?");
855 bool Changed = false;
857 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
858 while (!Preds.empty()) {
859 BasicBlock *Pred = Preds.pop_back_val();
861 // See if the predecessor is a comparison with the same value.
862 TerminatorInst *PTI = Pred->getTerminator();
863 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
865 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
866 // Figure out which 'cases' to copy from SI to PSI.
867 std::vector<ValueEqualityComparisonCase> BBCases;
868 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
870 std::vector<ValueEqualityComparisonCase> PredCases;
871 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
873 // Based on whether the default edge from PTI goes to BB or not, fill in
874 // PredCases and PredDefault with the new switch cases we would like to
876 SmallVector<BasicBlock*, 8> NewSuccessors;
878 // Update the branch weight metadata along the way
879 SmallVector<uint64_t, 8> Weights;
880 bool PredHasWeights = HasBranchWeights(PTI);
881 bool SuccHasWeights = HasBranchWeights(TI);
883 if (PredHasWeights) {
884 GetBranchWeights(PTI, Weights);
885 // branch-weight metadata is inconsistent here.
886 if (Weights.size() != 1 + PredCases.size())
887 PredHasWeights = SuccHasWeights = false;
888 } else if (SuccHasWeights)
889 // If there are no predecessor weights but there are successor weights,
890 // populate Weights with 1, which will later be scaled to the sum of
891 // successor's weights
892 Weights.assign(1 + PredCases.size(), 1);
894 SmallVector<uint64_t, 8> SuccWeights;
895 if (SuccHasWeights) {
896 GetBranchWeights(TI, SuccWeights);
897 // branch-weight metadata is inconsistent here.
898 if (SuccWeights.size() != 1 + BBCases.size())
899 PredHasWeights = SuccHasWeights = false;
900 } else if (PredHasWeights)
901 SuccWeights.assign(1 + BBCases.size(), 1);
903 if (PredDefault == BB) {
904 // If this is the default destination from PTI, only the edges in TI
905 // that don't occur in PTI, or that branch to BB will be activated.
906 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
907 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
908 if (PredCases[i].Dest != BB)
909 PTIHandled.insert(PredCases[i].Value);
911 // The default destination is BB, we don't need explicit targets.
912 std::swap(PredCases[i], PredCases.back());
914 if (PredHasWeights || SuccHasWeights) {
915 // Increase weight for the default case.
916 Weights[0] += Weights[i+1];
917 std::swap(Weights[i+1], Weights.back());
921 PredCases.pop_back();
925 // Reconstruct the new switch statement we will be building.
926 if (PredDefault != BBDefault) {
927 PredDefault->removePredecessor(Pred);
928 PredDefault = BBDefault;
929 NewSuccessors.push_back(BBDefault);
932 unsigned CasesFromPred = Weights.size();
933 uint64_t ValidTotalSuccWeight = 0;
934 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
935 if (!PTIHandled.count(BBCases[i].Value) &&
936 BBCases[i].Dest != BBDefault) {
937 PredCases.push_back(BBCases[i]);
938 NewSuccessors.push_back(BBCases[i].Dest);
939 if (SuccHasWeights || PredHasWeights) {
940 // The default weight is at index 0, so weight for the ith case
941 // should be at index i+1. Scale the cases from successor by
942 // PredDefaultWeight (Weights[0]).
943 Weights.push_back(Weights[0] * SuccWeights[i+1]);
944 ValidTotalSuccWeight += SuccWeights[i+1];
948 if (SuccHasWeights || PredHasWeights) {
949 ValidTotalSuccWeight += SuccWeights[0];
950 // Scale the cases from predecessor by ValidTotalSuccWeight.
951 for (unsigned i = 1; i < CasesFromPred; ++i)
952 Weights[i] *= ValidTotalSuccWeight;
953 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
954 Weights[0] *= SuccWeights[0];
957 // If this is not the default destination from PSI, only the edges
958 // in SI that occur in PSI with a destination of BB will be
960 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
961 std::map<ConstantInt*, uint64_t> WeightsForHandled;
962 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
963 if (PredCases[i].Dest == BB) {
964 PTIHandled.insert(PredCases[i].Value);
966 if (PredHasWeights || SuccHasWeights) {
967 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
968 std::swap(Weights[i+1], Weights.back());
972 std::swap(PredCases[i], PredCases.back());
973 PredCases.pop_back();
977 // Okay, now we know which constants were sent to BB from the
978 // predecessor. Figure out where they will all go now.
979 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
980 if (PTIHandled.count(BBCases[i].Value)) {
981 // If this is one we are capable of getting...
982 if (PredHasWeights || SuccHasWeights)
983 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
984 PredCases.push_back(BBCases[i]);
985 NewSuccessors.push_back(BBCases[i].Dest);
986 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
989 // If there are any constants vectored to BB that TI doesn't handle,
990 // they must go to the default destination of TI.
991 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
993 E = PTIHandled.end(); I != E; ++I) {
994 if (PredHasWeights || SuccHasWeights)
995 Weights.push_back(WeightsForHandled[*I]);
996 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
997 NewSuccessors.push_back(BBDefault);
1001 // Okay, at this point, we know which new successor Pred will get. Make
1002 // sure we update the number of entries in the PHI nodes for these
1004 for (BasicBlock *NewSuccessor : NewSuccessors)
1005 AddPredecessorToBlock(NewSuccessor, Pred, BB);
1007 Builder.SetInsertPoint(PTI);
1008 // Convert pointer to int before we switch.
1009 if (CV->getType()->isPointerTy()) {
1010 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
1014 // Now that the successors are updated, create the new Switch instruction.
1015 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1017 NewSI->setDebugLoc(PTI->getDebugLoc());
1018 for (ValueEqualityComparisonCase &V : PredCases)
1019 NewSI->addCase(V.Value, V.Dest);
1021 if (PredHasWeights || SuccHasWeights) {
1022 // Halve the weights if any of them cannot fit in an uint32_t
1023 FitWeights(Weights);
1025 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1027 NewSI->setMetadata(LLVMContext::MD_prof,
1028 MDBuilder(BB->getContext()).
1029 createBranchWeights(MDWeights));
1032 EraseTerminatorInstAndDCECond(PTI);
1034 // Okay, last check. If BB is still a successor of PSI, then we must
1035 // have an infinite loop case. If so, add an infinitely looping block
1036 // to handle the case to preserve the behavior of the code.
1037 BasicBlock *InfLoopBlock = nullptr;
1038 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1039 if (NewSI->getSuccessor(i) == BB) {
1040 if (!InfLoopBlock) {
1041 // Insert it at the end of the function, because it's either code,
1042 // or it won't matter if it's hot. :)
1043 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1044 "infloop", BB->getParent());
1045 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1047 NewSI->setSuccessor(i, InfLoopBlock);
1056 // If we would need to insert a select that uses the value of this invoke
1057 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1058 // can't hoist the invoke, as there is nowhere to put the select in this case.
1059 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1060 Instruction *I1, Instruction *I2) {
1061 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1063 for (BasicBlock::iterator BBI = SI->begin();
1064 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1065 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1066 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1067 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1075 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1077 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1078 /// in the two blocks up into the branch block. The caller of this function
1079 /// guarantees that BI's block dominates BB1 and BB2.
1080 static bool HoistThenElseCodeToIf(BranchInst *BI,
1081 const TargetTransformInfo &TTI) {
1082 // This does very trivial matching, with limited scanning, to find identical
1083 // instructions in the two blocks. In particular, we don't want to get into
1084 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1085 // such, we currently just scan for obviously identical instructions in an
1087 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1088 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1090 BasicBlock::iterator BB1_Itr = BB1->begin();
1091 BasicBlock::iterator BB2_Itr = BB2->begin();
1093 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1094 // Skip debug info if it is not identical.
1095 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1096 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1097 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1098 while (isa<DbgInfoIntrinsic>(I1))
1100 while (isa<DbgInfoIntrinsic>(I2))
1103 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1104 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1107 BasicBlock *BIParent = BI->getParent();
1109 bool Changed = false;
1111 // If we are hoisting the terminator instruction, don't move one (making a
1112 // broken BB), instead clone it, and remove BI.
1113 if (isa<TerminatorInst>(I1))
1114 goto HoistTerminator;
1116 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1119 // For a normal instruction, we just move one to right before the branch,
1120 // then replace all uses of the other with the first. Finally, we remove
1121 // the now redundant second instruction.
1122 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
1123 if (!I2->use_empty())
1124 I2->replaceAllUsesWith(I1);
1125 I1->intersectOptionalDataWith(I2);
1126 unsigned KnownIDs[] = {
1127 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1128 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1129 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1130 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1131 LLVMContext::MD_dereferenceable_or_null};
1132 combineMetadata(I1, I2, KnownIDs);
1133 I2->eraseFromParent();
1138 // Skip debug info if it is not identical.
1139 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1140 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1141 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1142 while (isa<DbgInfoIntrinsic>(I1))
1144 while (isa<DbgInfoIntrinsic>(I2))
1147 } while (I1->isIdenticalToWhenDefined(I2));
1152 // It may not be possible to hoist an invoke.
1153 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1156 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1158 for (BasicBlock::iterator BBI = SI->begin();
1159 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1160 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1161 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1165 // Check for passingValueIsAlwaysUndefined here because we would rather
1166 // eliminate undefined control flow then converting it to a select.
1167 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1168 passingValueIsAlwaysUndefined(BB2V, PN))
1171 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1173 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1178 // Okay, it is safe to hoist the terminator.
1179 Instruction *NT = I1->clone();
1180 BIParent->getInstList().insert(BI->getIterator(), NT);
1181 if (!NT->getType()->isVoidTy()) {
1182 I1->replaceAllUsesWith(NT);
1183 I2->replaceAllUsesWith(NT);
1187 IRBuilder<true, NoFolder> Builder(NT);
1188 // Hoisting one of the terminators from our successor is a great thing.
1189 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1190 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1191 // nodes, so we insert select instruction to compute the final result.
1192 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1193 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1195 for (BasicBlock::iterator BBI = SI->begin();
1196 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1197 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1198 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1199 if (BB1V == BB2V) continue;
1201 // These values do not agree. Insert a select instruction before NT
1202 // that determines the right value.
1203 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1205 SI = cast<SelectInst>
1206 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1207 BB1V->getName()+"."+BB2V->getName()));
1209 // Make the PHI node use the select for all incoming values for BB1/BB2
1210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1211 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1212 PN->setIncomingValue(i, SI);
1216 // Update any PHI nodes in our new successors.
1217 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1218 AddPredecessorToBlock(*SI, BIParent, BB1);
1220 EraseTerminatorInstAndDCECond(BI);
1224 /// Given an unconditional branch that goes to BBEnd,
1225 /// check whether BBEnd has only two predecessors and the other predecessor
1226 /// ends with an unconditional branch. If it is true, sink any common code
1227 /// in the two predecessors to BBEnd.
1228 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1229 assert(BI1->isUnconditional());
1230 BasicBlock *BB1 = BI1->getParent();
1231 BasicBlock *BBEnd = BI1->getSuccessor(0);
1233 // Check that BBEnd has two predecessors and the other predecessor ends with
1234 // an unconditional branch.
1235 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1236 BasicBlock *Pred0 = *PI++;
1237 if (PI == PE) // Only one predecessor.
1239 BasicBlock *Pred1 = *PI++;
1240 if (PI != PE) // More than two predecessors.
1242 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1243 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1244 if (!BI2 || !BI2->isUnconditional())
1247 // Gather the PHI nodes in BBEnd.
1248 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
1249 Instruction *FirstNonPhiInBBEnd = nullptr;
1250 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
1251 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1252 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1253 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1254 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
1256 FirstNonPhiInBBEnd = &*I;
1260 if (!FirstNonPhiInBBEnd)
1263 // This does very trivial matching, with limited scanning, to find identical
1264 // instructions in the two blocks. We scan backward for obviously identical
1265 // instructions in an identical order.
1266 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1267 RE1 = BB1->getInstList().rend(),
1268 RI2 = BB2->getInstList().rbegin(),
1269 RE2 = BB2->getInstList().rend();
1271 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1274 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1277 // Skip the unconditional branches.
1281 bool Changed = false;
1282 while (RI1 != RE1 && RI2 != RE2) {
1284 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1287 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1291 Instruction *I1 = &*RI1, *I2 = &*RI2;
1292 auto InstPair = std::make_pair(I1, I2);
1293 // I1 and I2 should have a single use in the same PHI node, and they
1294 // perform the same operation.
1295 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1296 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1297 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1298 I1->isEHPad() || I2->isEHPad() ||
1299 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1300 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1301 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1302 !I1->hasOneUse() || !I2->hasOneUse() ||
1303 !JointValueMap.count(InstPair))
1306 // Check whether we should swap the operands of ICmpInst.
1307 // TODO: Add support of communativity.
1308 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1309 bool SwapOpnds = false;
1310 if (ICmp1 && ICmp2 &&
1311 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1312 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1313 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1314 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1315 ICmp2->swapOperands();
1318 if (!I1->isSameOperationAs(I2)) {
1320 ICmp2->swapOperands();
1324 // The operands should be either the same or they need to be generated
1325 // with a PHI node after sinking. We only handle the case where there is
1326 // a single pair of different operands.
1327 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1328 unsigned Op1Idx = ~0U;
1329 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1330 if (I1->getOperand(I) == I2->getOperand(I))
1332 // Early exit if we have more-than one pair of different operands or if
1333 // we need a PHI node to replace a constant.
1334 if (Op1Idx != ~0U ||
1335 isa<Constant>(I1->getOperand(I)) ||
1336 isa<Constant>(I2->getOperand(I))) {
1337 // If we can't sink the instructions, undo the swapping.
1339 ICmp2->swapOperands();
1342 DifferentOp1 = I1->getOperand(I);
1344 DifferentOp2 = I2->getOperand(I);
1347 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1348 DEBUG(dbgs() << " " << *I2 << "\n");
1350 // We insert the pair of different operands to JointValueMap and
1351 // remove (I1, I2) from JointValueMap.
1352 if (Op1Idx != ~0U) {
1353 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1356 PHINode::Create(DifferentOp1->getType(), 2,
1357 DifferentOp1->getName() + ".sink", &BBEnd->front());
1358 NewPN->addIncoming(DifferentOp1, BB1);
1359 NewPN->addIncoming(DifferentOp2, BB2);
1360 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1362 // I1 should use NewPN instead of DifferentOp1.
1363 I1->setOperand(Op1Idx, NewPN);
1365 PHINode *OldPN = JointValueMap[InstPair];
1366 JointValueMap.erase(InstPair);
1368 // We need to update RE1 and RE2 if we are going to sink the first
1369 // instruction in the basic block down.
1370 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1371 // Sink the instruction.
1372 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1373 BB1->getInstList(), I1);
1374 if (!OldPN->use_empty())
1375 OldPN->replaceAllUsesWith(I1);
1376 OldPN->eraseFromParent();
1378 if (!I2->use_empty())
1379 I2->replaceAllUsesWith(I1);
1380 I1->intersectOptionalDataWith(I2);
1381 // TODO: Use combineMetadata here to preserve what metadata we can
1382 // (analogous to the hoisting case above).
1383 I2->eraseFromParent();
1386 RE1 = BB1->getInstList().rend();
1388 RE2 = BB2->getInstList().rend();
1389 FirstNonPhiInBBEnd = &*I1;
1396 /// \brief Determine if we can hoist sink a sole store instruction out of a
1397 /// conditional block.
1399 /// We are looking for code like the following:
1401 /// store i32 %add, i32* %arrayidx2
1402 /// ... // No other stores or function calls (we could be calling a memory
1403 /// ... // function).
1404 /// %cmp = icmp ult %x, %y
1405 /// br i1 %cmp, label %EndBB, label %ThenBB
1407 /// store i32 %add5, i32* %arrayidx2
1411 /// We are going to transform this into:
1413 /// store i32 %add, i32* %arrayidx2
1415 /// %cmp = icmp ult %x, %y
1416 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1417 /// store i32 %add.add5, i32* %arrayidx2
1420 /// \return The pointer to the value of the previous store if the store can be
1421 /// hoisted into the predecessor block. 0 otherwise.
1422 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1423 BasicBlock *StoreBB, BasicBlock *EndBB) {
1424 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1428 // Volatile or atomic.
1429 if (!StoreToHoist->isSimple())
1432 Value *StorePtr = StoreToHoist->getPointerOperand();
1434 // Look for a store to the same pointer in BrBB.
1435 unsigned MaxNumInstToLookAt = 10;
1436 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1437 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1438 Instruction *CurI = &*RI;
1440 // Could be calling an instruction that effects memory like free().
1441 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1444 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1445 // Found the previous store make sure it stores to the same location.
1446 if (SI && SI->getPointerOperand() == StorePtr)
1447 // Found the previous store, return its value operand.
1448 return SI->getValueOperand();
1450 return nullptr; // Unknown store.
1456 /// \brief Speculate a conditional basic block flattening the CFG.
1458 /// Note that this is a very risky transform currently. Speculating
1459 /// instructions like this is most often not desirable. Instead, there is an MI
1460 /// pass which can do it with full awareness of the resource constraints.
1461 /// However, some cases are "obvious" and we should do directly. An example of
1462 /// this is speculating a single, reasonably cheap instruction.
1464 /// There is only one distinct advantage to flattening the CFG at the IR level:
1465 /// it makes very common but simplistic optimizations such as are common in
1466 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1467 /// modeling their effects with easier to reason about SSA value graphs.
1470 /// An illustration of this transform is turning this IR:
1473 /// %cmp = icmp ult %x, %y
1474 /// br i1 %cmp, label %EndBB, label %ThenBB
1476 /// %sub = sub %x, %y
1479 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1486 /// %cmp = icmp ult %x, %y
1487 /// %sub = sub %x, %y
1488 /// %cond = select i1 %cmp, 0, %sub
1492 /// \returns true if the conditional block is removed.
1493 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1494 const TargetTransformInfo &TTI) {
1495 // Be conservative for now. FP select instruction can often be expensive.
1496 Value *BrCond = BI->getCondition();
1497 if (isa<FCmpInst>(BrCond))
1500 BasicBlock *BB = BI->getParent();
1501 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1503 // If ThenBB is actually on the false edge of the conditional branch, remember
1504 // to swap the select operands later.
1505 bool Invert = false;
1506 if (ThenBB != BI->getSuccessor(0)) {
1507 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1510 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1512 // Keep a count of how many times instructions are used within CondBB when
1513 // they are candidates for sinking into CondBB. Specifically:
1514 // - They are defined in BB, and
1515 // - They have no side effects, and
1516 // - All of their uses are in CondBB.
1517 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1519 unsigned SpeculationCost = 0;
1520 Value *SpeculatedStoreValue = nullptr;
1521 StoreInst *SpeculatedStore = nullptr;
1522 for (BasicBlock::iterator BBI = ThenBB->begin(),
1523 BBE = std::prev(ThenBB->end());
1524 BBI != BBE; ++BBI) {
1525 Instruction *I = &*BBI;
1527 if (isa<DbgInfoIntrinsic>(I))
1530 // Only speculatively execute a single instruction (not counting the
1531 // terminator) for now.
1533 if (SpeculationCost > 1)
1536 // Don't hoist the instruction if it's unsafe or expensive.
1537 if (!isSafeToSpeculativelyExecute(I) &&
1538 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1539 I, BB, ThenBB, EndBB))))
1541 if (!SpeculatedStoreValue &&
1542 ComputeSpeculationCost(I, TTI) >
1543 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
1546 // Store the store speculation candidate.
1547 if (SpeculatedStoreValue)
1548 SpeculatedStore = cast<StoreInst>(I);
1550 // Do not hoist the instruction if any of its operands are defined but not
1551 // used in BB. The transformation will prevent the operand from
1552 // being sunk into the use block.
1553 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1555 Instruction *OpI = dyn_cast<Instruction>(*i);
1556 if (!OpI || OpI->getParent() != BB ||
1557 OpI->mayHaveSideEffects())
1558 continue; // Not a candidate for sinking.
1560 ++SinkCandidateUseCounts[OpI];
1564 // Consider any sink candidates which are only used in CondBB as costs for
1565 // speculation. Note, while we iterate over a DenseMap here, we are summing
1566 // and so iteration order isn't significant.
1567 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1568 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1570 if (I->first->getNumUses() == I->second) {
1572 if (SpeculationCost > 1)
1576 // Check that the PHI nodes can be converted to selects.
1577 bool HaveRewritablePHIs = false;
1578 for (BasicBlock::iterator I = EndBB->begin();
1579 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1580 Value *OrigV = PN->getIncomingValueForBlock(BB);
1581 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1583 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1584 // Skip PHIs which are trivial.
1588 // Don't convert to selects if we could remove undefined behavior instead.
1589 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1590 passingValueIsAlwaysUndefined(ThenV, PN))
1593 HaveRewritablePHIs = true;
1594 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1595 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1596 if (!OrigCE && !ThenCE)
1597 continue; // Known safe and cheap.
1599 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1600 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1602 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1603 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
1604 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1605 TargetTransformInfo::TCC_Basic;
1606 if (OrigCost + ThenCost > MaxCost)
1609 // Account for the cost of an unfolded ConstantExpr which could end up
1610 // getting expanded into Instructions.
1611 // FIXME: This doesn't account for how many operations are combined in the
1612 // constant expression.
1614 if (SpeculationCost > 1)
1618 // If there are no PHIs to process, bail early. This helps ensure idempotence
1620 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1623 // If we get here, we can hoist the instruction and if-convert.
1624 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1626 // Insert a select of the value of the speculated store.
1627 if (SpeculatedStoreValue) {
1628 IRBuilder<true, NoFolder> Builder(BI);
1629 Value *TrueV = SpeculatedStore->getValueOperand();
1630 Value *FalseV = SpeculatedStoreValue;
1632 std::swap(TrueV, FalseV);
1633 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1634 "." + FalseV->getName());
1635 SpeculatedStore->setOperand(0, S);
1638 // Metadata can be dependent on the condition we are hoisting above.
1639 // Conservatively strip all metadata on the instruction.
1640 for (auto &I: *ThenBB)
1641 I.dropUnknownNonDebugMetadata();
1643 // Hoist the instructions.
1644 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1645 ThenBB->begin(), std::prev(ThenBB->end()));
1647 // Insert selects and rewrite the PHI operands.
1648 IRBuilder<true, NoFolder> Builder(BI);
1649 for (BasicBlock::iterator I = EndBB->begin();
1650 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1651 unsigned OrigI = PN->getBasicBlockIndex(BB);
1652 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1653 Value *OrigV = PN->getIncomingValue(OrigI);
1654 Value *ThenV = PN->getIncomingValue(ThenI);
1656 // Skip PHIs which are trivial.
1660 // Create a select whose true value is the speculatively executed value and
1661 // false value is the preexisting value. Swap them if the branch
1662 // destinations were inverted.
1663 Value *TrueV = ThenV, *FalseV = OrigV;
1665 std::swap(TrueV, FalseV);
1666 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1667 TrueV->getName() + "." + FalseV->getName());
1668 PN->setIncomingValue(OrigI, V);
1669 PN->setIncomingValue(ThenI, V);
1676 /// \returns True if this block contains a CallInst with the NoDuplicate
1678 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1679 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1680 const CallInst *CI = dyn_cast<CallInst>(I);
1683 if (CI->cannotDuplicate())
1689 /// Return true if we can thread a branch across this block.
1690 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1691 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1694 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1695 if (isa<DbgInfoIntrinsic>(BBI))
1697 if (Size > 10) return false; // Don't clone large BB's.
1700 // We can only support instructions that do not define values that are
1701 // live outside of the current basic block.
1702 for (User *U : BBI->users()) {
1703 Instruction *UI = cast<Instruction>(U);
1704 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1707 // Looks ok, continue checking.
1713 /// If we have a conditional branch on a PHI node value that is defined in the
1714 /// same block as the branch and if any PHI entries are constants, thread edges
1715 /// corresponding to that entry to be branches to their ultimate destination.
1716 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
1717 BasicBlock *BB = BI->getParent();
1718 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1719 // NOTE: we currently cannot transform this case if the PHI node is used
1720 // outside of the block.
1721 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1724 // Degenerate case of a single entry PHI.
1725 if (PN->getNumIncomingValues() == 1) {
1726 FoldSingleEntryPHINodes(PN->getParent());
1730 // Now we know that this block has multiple preds and two succs.
1731 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1733 if (HasNoDuplicateCall(BB)) return false;
1735 // Okay, this is a simple enough basic block. See if any phi values are
1737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1738 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1739 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1741 // Okay, we now know that all edges from PredBB should be revectored to
1742 // branch to RealDest.
1743 BasicBlock *PredBB = PN->getIncomingBlock(i);
1744 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1746 if (RealDest == BB) continue; // Skip self loops.
1747 // Skip if the predecessor's terminator is an indirect branch.
1748 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1750 // The dest block might have PHI nodes, other predecessors and other
1751 // difficult cases. Instead of being smart about this, just insert a new
1752 // block that jumps to the destination block, effectively splitting
1753 // the edge we are about to create.
1754 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1755 RealDest->getName()+".critedge",
1756 RealDest->getParent(), RealDest);
1757 BranchInst::Create(RealDest, EdgeBB);
1759 // Update PHI nodes.
1760 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1762 // BB may have instructions that are being threaded over. Clone these
1763 // instructions into EdgeBB. We know that there will be no uses of the
1764 // cloned instructions outside of EdgeBB.
1765 BasicBlock::iterator InsertPt = EdgeBB->begin();
1766 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1767 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1768 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1769 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1772 // Clone the instruction.
1773 Instruction *N = BBI->clone();
1774 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1776 // Update operands due to translation.
1777 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1779 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1780 if (PI != TranslateMap.end())
1784 // Check for trivial simplification.
1785 if (Value *V = SimplifyInstruction(N, DL)) {
1786 TranslateMap[&*BBI] = V;
1787 delete N; // Instruction folded away, don't need actual inst
1789 // Insert the new instruction into its new home.
1790 EdgeBB->getInstList().insert(InsertPt, N);
1791 if (!BBI->use_empty())
1792 TranslateMap[&*BBI] = N;
1796 // Loop over all of the edges from PredBB to BB, changing them to branch
1797 // to EdgeBB instead.
1798 TerminatorInst *PredBBTI = PredBB->getTerminator();
1799 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1800 if (PredBBTI->getSuccessor(i) == BB) {
1801 BB->removePredecessor(PredBB);
1802 PredBBTI->setSuccessor(i, EdgeBB);
1805 // Recurse, simplifying any other constants.
1806 return FoldCondBranchOnPHI(BI, DL) | true;
1812 /// Given a BB that starts with the specified two-entry PHI node,
1813 /// see if we can eliminate it.
1814 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1815 const DataLayout &DL) {
1816 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1817 // statement", which has a very simple dominance structure. Basically, we
1818 // are trying to find the condition that is being branched on, which
1819 // subsequently causes this merge to happen. We really want control
1820 // dependence information for this check, but simplifycfg can't keep it up
1821 // to date, and this catches most of the cases we care about anyway.
1822 BasicBlock *BB = PN->getParent();
1823 BasicBlock *IfTrue, *IfFalse;
1824 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1826 // Don't bother if the branch will be constant folded trivially.
1827 isa<ConstantInt>(IfCond))
1830 // Okay, we found that we can merge this two-entry phi node into a select.
1831 // Doing so would require us to fold *all* two entry phi nodes in this block.
1832 // At some point this becomes non-profitable (particularly if the target
1833 // doesn't support cmov's). Only do this transformation if there are two or
1834 // fewer PHI nodes in this block.
1835 unsigned NumPhis = 0;
1836 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1840 // Loop over the PHI's seeing if we can promote them all to select
1841 // instructions. While we are at it, keep track of the instructions
1842 // that need to be moved to the dominating block.
1843 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1844 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1845 MaxCostVal1 = PHINodeFoldingThreshold;
1846 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1847 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
1849 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1850 PHINode *PN = cast<PHINode>(II++);
1851 if (Value *V = SimplifyInstruction(PN, DL)) {
1852 PN->replaceAllUsesWith(V);
1853 PN->eraseFromParent();
1857 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1858 MaxCostVal0, TTI) ||
1859 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1864 // If we folded the first phi, PN dangles at this point. Refresh it. If
1865 // we ran out of PHIs then we simplified them all.
1866 PN = dyn_cast<PHINode>(BB->begin());
1867 if (!PN) return true;
1869 // Don't fold i1 branches on PHIs which contain binary operators. These can
1870 // often be turned into switches and other things.
1871 if (PN->getType()->isIntegerTy(1) &&
1872 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1873 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1874 isa<BinaryOperator>(IfCond)))
1877 // If we all PHI nodes are promotable, check to make sure that all
1878 // instructions in the predecessor blocks can be promoted as well. If
1879 // not, we won't be able to get rid of the control flow, so it's not
1880 // worth promoting to select instructions.
1881 BasicBlock *DomBlock = nullptr;
1882 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1883 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1884 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1887 DomBlock = *pred_begin(IfBlock1);
1888 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1889 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
1890 // This is not an aggressive instruction that we can promote.
1891 // Because of this, we won't be able to get rid of the control
1892 // flow, so the xform is not worth it.
1897 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1900 DomBlock = *pred_begin(IfBlock2);
1901 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1902 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
1903 // This is not an aggressive instruction that we can promote.
1904 // Because of this, we won't be able to get rid of the control
1905 // flow, so the xform is not worth it.
1910 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1911 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1913 // If we can still promote the PHI nodes after this gauntlet of tests,
1914 // do all of the PHI's now.
1915 Instruction *InsertPt = DomBlock->getTerminator();
1916 IRBuilder<true, NoFolder> Builder(InsertPt);
1918 // Move all 'aggressive' instructions, which are defined in the
1919 // conditional parts of the if's up to the dominating block.
1921 DomBlock->getInstList().splice(InsertPt->getIterator(),
1922 IfBlock1->getInstList(), IfBlock1->begin(),
1923 IfBlock1->getTerminator()->getIterator());
1925 DomBlock->getInstList().splice(InsertPt->getIterator(),
1926 IfBlock2->getInstList(), IfBlock2->begin(),
1927 IfBlock2->getTerminator()->getIterator());
1929 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1930 // Change the PHI node into a select instruction.
1931 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1932 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1935 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1936 PN->replaceAllUsesWith(NV);
1938 PN->eraseFromParent();
1941 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1942 // has been flattened. Change DomBlock to jump directly to our new block to
1943 // avoid other simplifycfg's kicking in on the diamond.
1944 TerminatorInst *OldTI = DomBlock->getTerminator();
1945 Builder.SetInsertPoint(OldTI);
1946 Builder.CreateBr(BB);
1947 OldTI->eraseFromParent();
1951 /// If we found a conditional branch that goes to two returning blocks,
1952 /// try to merge them together into one return,
1953 /// introducing a select if the return values disagree.
1954 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1955 IRBuilder<> &Builder) {
1956 assert(BI->isConditional() && "Must be a conditional branch");
1957 BasicBlock *TrueSucc = BI->getSuccessor(0);
1958 BasicBlock *FalseSucc = BI->getSuccessor(1);
1959 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1960 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1962 // Check to ensure both blocks are empty (just a return) or optionally empty
1963 // with PHI nodes. If there are other instructions, merging would cause extra
1964 // computation on one path or the other.
1965 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1967 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1970 Builder.SetInsertPoint(BI);
1971 // Okay, we found a branch that is going to two return nodes. If
1972 // there is no return value for this function, just change the
1973 // branch into a return.
1974 if (FalseRet->getNumOperands() == 0) {
1975 TrueSucc->removePredecessor(BI->getParent());
1976 FalseSucc->removePredecessor(BI->getParent());
1977 Builder.CreateRetVoid();
1978 EraseTerminatorInstAndDCECond(BI);
1982 // Otherwise, figure out what the true and false return values are
1983 // so we can insert a new select instruction.
1984 Value *TrueValue = TrueRet->getReturnValue();
1985 Value *FalseValue = FalseRet->getReturnValue();
1987 // Unwrap any PHI nodes in the return blocks.
1988 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1989 if (TVPN->getParent() == TrueSucc)
1990 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1991 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1992 if (FVPN->getParent() == FalseSucc)
1993 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1995 // In order for this transformation to be safe, we must be able to
1996 // unconditionally execute both operands to the return. This is
1997 // normally the case, but we could have a potentially-trapping
1998 // constant expression that prevents this transformation from being
2000 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2003 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2007 // Okay, we collected all the mapped values and checked them for sanity, and
2008 // defined to really do this transformation. First, update the CFG.
2009 TrueSucc->removePredecessor(BI->getParent());
2010 FalseSucc->removePredecessor(BI->getParent());
2012 // Insert select instructions where needed.
2013 Value *BrCond = BI->getCondition();
2015 // Insert a select if the results differ.
2016 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2017 } else if (isa<UndefValue>(TrueValue)) {
2018 TrueValue = FalseValue;
2020 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2021 FalseValue, "retval");
2025 Value *RI = !TrueValue ?
2026 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2030 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2031 << "\n " << *BI << "NewRet = " << *RI
2032 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2034 EraseTerminatorInstAndDCECond(BI);
2039 /// Given a conditional BranchInstruction, retrieve the probabilities of the
2040 /// branch taking each edge. Fills in the two APInt parameters and returns true,
2041 /// or returns false if no or invalid metadata was found.
2042 static bool ExtractBranchMetadata(BranchInst *BI,
2043 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2044 assert(BI->isConditional() &&
2045 "Looking for probabilities on unconditional branch?");
2046 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2047 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2048 ConstantInt *CITrue =
2049 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2050 ConstantInt *CIFalse =
2051 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
2052 if (!CITrue || !CIFalse) return false;
2053 ProbTrue = CITrue->getValue().getZExtValue();
2054 ProbFalse = CIFalse->getValue().getZExtValue();
2058 /// Return true if the given instruction is available
2059 /// in its predecessor block. If yes, the instruction will be removed.
2060 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2061 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2063 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2064 Instruction *PBI = &*I;
2065 // Check whether Inst and PBI generate the same value.
2066 if (Inst->isIdenticalTo(PBI)) {
2067 Inst->replaceAllUsesWith(PBI);
2068 Inst->eraseFromParent();
2075 /// If this basic block is simple enough, and if a predecessor branches to us
2076 /// and one of our successors, fold the block into the predecessor and use
2077 /// logical operations to pick the right destination.
2078 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
2079 BasicBlock *BB = BI->getParent();
2081 Instruction *Cond = nullptr;
2082 if (BI->isConditional())
2083 Cond = dyn_cast<Instruction>(BI->getCondition());
2085 // For unconditional branch, check for a simple CFG pattern, where
2086 // BB has a single predecessor and BB's successor is also its predecessor's
2087 // successor. If such pattern exisits, check for CSE between BB and its
2089 if (BasicBlock *PB = BB->getSinglePredecessor())
2090 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2091 if (PBI->isConditional() &&
2092 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2093 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2094 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2096 Instruction *Curr = &*I++;
2097 if (isa<CmpInst>(Curr)) {
2101 // Quit if we can't remove this instruction.
2102 if (!checkCSEInPredecessor(Curr, PB))
2111 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2112 Cond->getParent() != BB || !Cond->hasOneUse())
2115 // Make sure the instruction after the condition is the cond branch.
2116 BasicBlock::iterator CondIt = ++Cond->getIterator();
2118 // Ignore dbg intrinsics.
2119 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2124 // Only allow this transformation if computing the condition doesn't involve
2125 // too many instructions and these involved instructions can be executed
2126 // unconditionally. We denote all involved instructions except the condition
2127 // as "bonus instructions", and only allow this transformation when the
2128 // number of the bonus instructions does not exceed a certain threshold.
2129 unsigned NumBonusInsts = 0;
2130 for (auto I = BB->begin(); Cond != I; ++I) {
2131 // Ignore dbg intrinsics.
2132 if (isa<DbgInfoIntrinsic>(I))
2134 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
2136 // I has only one use and can be executed unconditionally.
2137 Instruction *User = dyn_cast<Instruction>(I->user_back());
2138 if (User == nullptr || User->getParent() != BB)
2140 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2141 // to use any other instruction, User must be an instruction between next(I)
2144 // Early exits once we reach the limit.
2145 if (NumBonusInsts > BonusInstThreshold)
2149 // Cond is known to be a compare or binary operator. Check to make sure that
2150 // neither operand is a potentially-trapping constant expression.
2151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2158 // Finally, don't infinitely unroll conditional loops.
2159 BasicBlock *TrueDest = BI->getSuccessor(0);
2160 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2161 if (TrueDest == BB || FalseDest == BB)
2164 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2165 BasicBlock *PredBlock = *PI;
2166 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2168 // Check that we have two conditional branches. If there is a PHI node in
2169 // the common successor, verify that the same value flows in from both
2171 SmallVector<PHINode*, 4> PHIs;
2172 if (!PBI || PBI->isUnconditional() ||
2173 (BI->isConditional() &&
2174 !SafeToMergeTerminators(BI, PBI)) ||
2175 (!BI->isConditional() &&
2176 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2179 // Determine if the two branches share a common destination.
2180 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2181 bool InvertPredCond = false;
2183 if (BI->isConditional()) {
2184 if (PBI->getSuccessor(0) == TrueDest)
2185 Opc = Instruction::Or;
2186 else if (PBI->getSuccessor(1) == FalseDest)
2187 Opc = Instruction::And;
2188 else if (PBI->getSuccessor(0) == FalseDest)
2189 Opc = Instruction::And, InvertPredCond = true;
2190 else if (PBI->getSuccessor(1) == TrueDest)
2191 Opc = Instruction::Or, InvertPredCond = true;
2195 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2199 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2200 IRBuilder<> Builder(PBI);
2202 // If we need to invert the condition in the pred block to match, do so now.
2203 if (InvertPredCond) {
2204 Value *NewCond = PBI->getCondition();
2206 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2207 CmpInst *CI = cast<CmpInst>(NewCond);
2208 CI->setPredicate(CI->getInversePredicate());
2210 NewCond = Builder.CreateNot(NewCond,
2211 PBI->getCondition()->getName()+".not");
2214 PBI->setCondition(NewCond);
2215 PBI->swapSuccessors();
2218 // If we have bonus instructions, clone them into the predecessor block.
2219 // Note that there may be multiple predecessor blocks, so we cannot move
2220 // bonus instructions to a predecessor block.
2221 ValueToValueMapTy VMap; // maps original values to cloned values
2222 // We already make sure Cond is the last instruction before BI. Therefore,
2223 // all instructions before Cond other than DbgInfoIntrinsic are bonus
2225 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2226 if (isa<DbgInfoIntrinsic>(BonusInst))
2228 Instruction *NewBonusInst = BonusInst->clone();
2229 RemapInstruction(NewBonusInst, VMap,
2230 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2231 VMap[&*BonusInst] = NewBonusInst;
2233 // If we moved a load, we cannot any longer claim any knowledge about
2234 // its potential value. The previous information might have been valid
2235 // only given the branch precondition.
2236 // For an analogous reason, we must also drop all the metadata whose
2237 // semantics we don't understand.
2238 NewBonusInst->dropUnknownNonDebugMetadata();
2240 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2241 NewBonusInst->takeName(&*BonusInst);
2242 BonusInst->setName(BonusInst->getName() + ".old");
2245 // Clone Cond into the predecessor basic block, and or/and the
2246 // two conditions together.
2247 Instruction *New = Cond->clone();
2248 RemapInstruction(New, VMap,
2249 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2250 PredBlock->getInstList().insert(PBI->getIterator(), New);
2251 New->takeName(Cond);
2252 Cond->setName(New->getName() + ".old");
2254 if (BI->isConditional()) {
2255 Instruction *NewCond =
2256 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2258 PBI->setCondition(NewCond);
2260 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2261 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2263 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2265 SmallVector<uint64_t, 8> NewWeights;
2267 if (PBI->getSuccessor(0) == BB) {
2268 if (PredHasWeights && SuccHasWeights) {
2269 // PBI: br i1 %x, BB, FalseDest
2270 // BI: br i1 %y, TrueDest, FalseDest
2271 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2272 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2273 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2274 // TrueWeight for PBI * FalseWeight for BI.
2275 // We assume that total weights of a BranchInst can fit into 32 bits.
2276 // Therefore, we will not have overflow using 64-bit arithmetic.
2277 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2278 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2280 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2281 PBI->setSuccessor(0, TrueDest);
2283 if (PBI->getSuccessor(1) == BB) {
2284 if (PredHasWeights && SuccHasWeights) {
2285 // PBI: br i1 %x, TrueDest, BB
2286 // BI: br i1 %y, TrueDest, FalseDest
2287 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2288 // FalseWeight for PBI * TrueWeight for BI.
2289 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2290 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2291 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2292 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2294 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2295 PBI->setSuccessor(1, FalseDest);
2297 if (NewWeights.size() == 2) {
2298 // Halve the weights if any of them cannot fit in an uint32_t
2299 FitWeights(NewWeights);
2301 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2302 PBI->setMetadata(LLVMContext::MD_prof,
2303 MDBuilder(BI->getContext()).
2304 createBranchWeights(MDWeights));
2306 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2308 // Update PHI nodes in the common successors.
2309 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2310 ConstantInt *PBI_C = cast<ConstantInt>(
2311 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2312 assert(PBI_C->getType()->isIntegerTy(1));
2313 Instruction *MergedCond = nullptr;
2314 if (PBI->getSuccessor(0) == TrueDest) {
2315 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2316 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2317 // is false: !PBI_Cond and BI_Value
2318 Instruction *NotCond =
2319 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2322 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2327 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2328 PBI->getCondition(), MergedCond,
2331 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2332 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2333 // is false: PBI_Cond and BI_Value
2335 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2336 PBI->getCondition(), New,
2338 if (PBI_C->isOne()) {
2339 Instruction *NotCond =
2340 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2343 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2344 NotCond, MergedCond,
2349 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2352 // Change PBI from Conditional to Unconditional.
2353 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2354 EraseTerminatorInstAndDCECond(PBI);
2358 // TODO: If BB is reachable from all paths through PredBlock, then we
2359 // could replace PBI's branch probabilities with BI's.
2361 // Copy any debug value intrinsics into the end of PredBlock.
2362 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2363 if (isa<DbgInfoIntrinsic>(*I))
2364 I->clone()->insertBefore(PBI);
2371 // If there is only one store in BB1 and BB2, return it, otherwise return
2373 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2374 StoreInst *S = nullptr;
2375 for (auto *BB : {BB1, BB2}) {
2379 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2381 // Multiple stores seen.
2390 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2391 Value *AlternativeV = nullptr) {
2392 // PHI is going to be a PHI node that allows the value V that is defined in
2393 // BB to be referenced in BB's only successor.
2395 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2396 // doesn't matter to us what the other operand is (it'll never get used). We
2397 // could just create a new PHI with an undef incoming value, but that could
2398 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2399 // other PHI. So here we directly look for some PHI in BB's successor with V
2400 // as an incoming operand. If we find one, we use it, else we create a new
2403 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2404 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2405 // where OtherBB is the single other predecessor of BB's only successor.
2406 PHINode *PHI = nullptr;
2407 BasicBlock *Succ = BB->getSingleSuccessor();
2409 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2410 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2411 PHI = cast<PHINode>(I);
2415 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2416 auto PredI = pred_begin(Succ);
2417 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2418 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2425 // If V is not an instruction defined in BB, just return it.
2426 if (!AlternativeV &&
2427 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2430 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
2431 PHI->addIncoming(V, BB);
2432 for (BasicBlock *PredBB : predecessors(Succ))
2434 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2439 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2440 BasicBlock *QTB, BasicBlock *QFB,
2441 BasicBlock *PostBB, Value *Address,
2442 bool InvertPCond, bool InvertQCond) {
2443 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2444 return Operator::getOpcode(&I) == Instruction::BitCast &&
2445 I.getType()->isPointerTy();
2448 // If we're not in aggressive mode, we only optimize if we have some
2449 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2450 auto IsWorthwhile = [&](BasicBlock *BB) {
2453 // Heuristic: if the block can be if-converted/phi-folded and the
2454 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2455 // thread this store.
2457 for (auto &I : *BB) {
2458 // Cheap instructions viable for folding.
2459 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2462 // Free instructions.
2463 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2464 IsaBitcastOfPointerType(I))
2469 return N <= PHINodeFoldingThreshold;
2472 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2473 !IsWorthwhile(PFB) ||
2474 !IsWorthwhile(QTB) ||
2475 !IsWorthwhile(QFB)))
2478 // For every pointer, there must be exactly two stores, one coming from
2479 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2480 // store (to any address) in PTB,PFB or QTB,QFB.
2481 // FIXME: We could relax this restriction with a bit more work and performance
2483 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2484 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2485 if (!PStore || !QStore)
2488 // Now check the stores are compatible.
2489 if (!QStore->isUnordered() || !PStore->isUnordered())
2492 // Check that sinking the store won't cause program behavior changes. Sinking
2493 // the store out of the Q blocks won't change any behavior as we're sinking
2494 // from a block to its unconditional successor. But we're moving a store from
2495 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2496 // So we need to check that there are no aliasing loads or stores in
2497 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2498 // operations between PStore and the end of its parent block.
2500 // The ideal way to do this is to query AliasAnalysis, but we don't
2501 // preserve AA currently so that is dangerous. Be super safe and just
2502 // check there are no other memory operations at all.
2503 for (auto &I : *QFB->getSinglePredecessor())
2504 if (I.mayReadOrWriteMemory())
2506 for (auto &I : *QFB)
2507 if (&I != QStore && I.mayReadOrWriteMemory())
2510 for (auto &I : *QTB)
2511 if (&I != QStore && I.mayReadOrWriteMemory())
2513 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2515 if (&*I != PStore && I->mayReadOrWriteMemory())
2518 // OK, we're going to sink the stores to PostBB. The store has to be
2519 // conditional though, so first create the predicate.
2520 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2522 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2525 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2526 PStore->getParent());
2527 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2528 QStore->getParent(), PPHI);
2530 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2532 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2533 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2536 PPred = QB.CreateNot(PPred);
2538 QPred = QB.CreateNot(QPred);
2539 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2542 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
2543 QB.SetInsertPoint(T);
2544 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2546 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2547 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2548 SI->setAAMetadata(AAMD);
2550 QStore->eraseFromParent();
2551 PStore->eraseFromParent();
2556 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2557 // The intention here is to find diamonds or triangles (see below) where each
2558 // conditional block contains a store to the same address. Both of these
2559 // stores are conditional, so they can't be unconditionally sunk. But it may
2560 // be profitable to speculatively sink the stores into one merged store at the
2561 // end, and predicate the merged store on the union of the two conditions of
2564 // This can reduce the number of stores executed if both of the conditions are
2565 // true, and can allow the blocks to become small enough to be if-converted.
2566 // This optimization will also chain, so that ladders of test-and-set
2567 // sequences can be if-converted away.
2569 // We only deal with simple diamonds or triangles:
2571 // PBI or PBI or a combination of the two
2581 // We model triangles as a type of diamond with a nullptr "true" block.
2582 // Triangles are canonicalized so that the fallthrough edge is represented by
2583 // a true condition, as in the diagram above.
2585 BasicBlock *PTB = PBI->getSuccessor(0);
2586 BasicBlock *PFB = PBI->getSuccessor(1);
2587 BasicBlock *QTB = QBI->getSuccessor(0);
2588 BasicBlock *QFB = QBI->getSuccessor(1);
2589 BasicBlock *PostBB = QFB->getSingleSuccessor();
2591 bool InvertPCond = false, InvertQCond = false;
2592 // Canonicalize fallthroughs to the true branches.
2593 if (PFB == QBI->getParent()) {
2594 std::swap(PFB, PTB);
2597 if (QFB == PostBB) {
2598 std::swap(QFB, QTB);
2602 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2603 // and QFB may not. Model fallthroughs as a nullptr block.
2604 if (PTB == QBI->getParent())
2609 // Legality bailouts. We must have at least the non-fallthrough blocks and
2610 // the post-dominating block, and the non-fallthroughs must only have one
2612 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2613 return BB->getSinglePredecessor() == P &&
2614 BB->getSingleSuccessor() == S;
2617 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2618 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2620 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2621 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2623 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2626 // OK, this is a sequence of two diamonds or triangles.
2627 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2628 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2629 for (auto *BB : {PTB, PFB}) {
2633 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2634 PStoreAddresses.insert(SI->getPointerOperand());
2636 for (auto *BB : {QTB, QFB}) {
2640 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2641 QStoreAddresses.insert(SI->getPointerOperand());
2644 set_intersect(PStoreAddresses, QStoreAddresses);
2645 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2646 // clear what it contains.
2647 auto &CommonAddresses = PStoreAddresses;
2649 bool Changed = false;
2650 for (auto *Address : CommonAddresses)
2651 Changed |= mergeConditionalStoreToAddress(
2652 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2656 /// If we have a conditional branch as a predecessor of another block,
2657 /// this function tries to simplify it. We know
2658 /// that PBI and BI are both conditional branches, and BI is in one of the
2659 /// successor blocks of PBI - PBI branches to BI.
2660 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2661 const DataLayout &DL) {
2662 assert(PBI->isConditional() && BI->isConditional());
2663 BasicBlock *BB = BI->getParent();
2665 // If this block ends with a branch instruction, and if there is a
2666 // predecessor that ends on a branch of the same condition, make
2667 // this conditional branch redundant.
2668 if (PBI->getCondition() == BI->getCondition() &&
2669 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2670 // Okay, the outcome of this conditional branch is statically
2671 // knowable. If this block had a single pred, handle specially.
2672 if (BB->getSinglePredecessor()) {
2673 // Turn this into a branch on constant.
2674 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2675 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2677 return true; // Nuke the branch on constant.
2680 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2681 // in the constant and simplify the block result. Subsequent passes of
2682 // simplifycfg will thread the block.
2683 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2684 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2685 PHINode *NewPN = PHINode::Create(
2686 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2687 BI->getCondition()->getName() + ".pr", &BB->front());
2688 // Okay, we're going to insert the PHI node. Since PBI is not the only
2689 // predecessor, compute the PHI'd conditional value for all of the preds.
2690 // Any predecessor where the condition is not computable we keep symbolic.
2691 for (pred_iterator PI = PB; PI != PE; ++PI) {
2692 BasicBlock *P = *PI;
2693 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2694 PBI != BI && PBI->isConditional() &&
2695 PBI->getCondition() == BI->getCondition() &&
2696 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2697 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2698 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2701 NewPN->addIncoming(BI->getCondition(), P);
2705 BI->setCondition(NewPN);
2710 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2714 // If BI is reached from the true path of PBI and PBI's condition implies
2715 // BI's condition, we know the direction of the BI branch.
2716 if (PBI->getSuccessor(0) == BI->getParent() &&
2717 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
2718 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2719 BB->getSinglePredecessor()) {
2720 // Turn this into a branch on constant.
2721 auto *OldCond = BI->getCondition();
2722 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2723 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2724 return true; // Nuke the branch on constant.
2727 // If both branches are conditional and both contain stores to the same
2728 // address, remove the stores from the conditionals and create a conditional
2729 // merged store at the end.
2730 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2733 // If this is a conditional branch in an empty block, and if any
2734 // predecessors are a conditional branch to one of our destinations,
2735 // fold the conditions into logical ops and one cond br.
2736 BasicBlock::iterator BBI = BB->begin();
2737 // Ignore dbg intrinsics.
2738 while (isa<DbgInfoIntrinsic>(BBI))
2744 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2746 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2747 PBIOp = 0, BIOp = 1;
2748 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2749 PBIOp = 1, BIOp = 0;
2750 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2755 // Check to make sure that the other destination of this branch
2756 // isn't BB itself. If so, this is an infinite loop that will
2757 // keep getting unwound.
2758 if (PBI->getSuccessor(PBIOp) == BB)
2761 // Do not perform this transformation if it would require
2762 // insertion of a large number of select instructions. For targets
2763 // without predication/cmovs, this is a big pessimization.
2765 // Also do not perform this transformation if any phi node in the common
2766 // destination block can trap when reached by BB or PBB (PR17073). In that
2767 // case, it would be unsafe to hoist the operation into a select instruction.
2769 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2770 unsigned NumPhis = 0;
2771 for (BasicBlock::iterator II = CommonDest->begin();
2772 isa<PHINode>(II); ++II, ++NumPhis) {
2773 if (NumPhis > 2) // Disable this xform.
2776 PHINode *PN = cast<PHINode>(II);
2777 Value *BIV = PN->getIncomingValueForBlock(BB);
2778 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2782 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2783 Value *PBIV = PN->getIncomingValue(PBBIdx);
2784 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2789 // Finally, if everything is ok, fold the branches to logical ops.
2790 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2792 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2793 << "AND: " << *BI->getParent());
2796 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2797 // branch in it, where one edge (OtherDest) goes back to itself but the other
2798 // exits. We don't *know* that the program avoids the infinite loop
2799 // (even though that seems likely). If we do this xform naively, we'll end up
2800 // recursively unpeeling the loop. Since we know that (after the xform is
2801 // done) that the block *is* infinite if reached, we just make it an obviously
2802 // infinite loop with no cond branch.
2803 if (OtherDest == BB) {
2804 // Insert it at the end of the function, because it's either code,
2805 // or it won't matter if it's hot. :)
2806 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2807 "infloop", BB->getParent());
2808 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2809 OtherDest = InfLoopBlock;
2812 DEBUG(dbgs() << *PBI->getParent()->getParent());
2814 // BI may have other predecessors. Because of this, we leave
2815 // it alone, but modify PBI.
2817 // Make sure we get to CommonDest on True&True directions.
2818 Value *PBICond = PBI->getCondition();
2819 IRBuilder<true, NoFolder> Builder(PBI);
2821 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2823 Value *BICond = BI->getCondition();
2825 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2827 // Merge the conditions.
2828 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2830 // Modify PBI to branch on the new condition to the new dests.
2831 PBI->setCondition(Cond);
2832 PBI->setSuccessor(0, CommonDest);
2833 PBI->setSuccessor(1, OtherDest);
2835 // Update branch weight for PBI.
2836 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2837 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2839 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2841 if (PredHasWeights && SuccHasWeights) {
2842 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2843 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2844 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2845 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2846 // The weight to CommonDest should be PredCommon * SuccTotal +
2847 // PredOther * SuccCommon.
2848 // The weight to OtherDest should be PredOther * SuccOther.
2849 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2850 PredOther * SuccCommon,
2851 PredOther * SuccOther};
2852 // Halve the weights if any of them cannot fit in an uint32_t
2853 FitWeights(NewWeights);
2855 PBI->setMetadata(LLVMContext::MD_prof,
2856 MDBuilder(BI->getContext())
2857 .createBranchWeights(NewWeights[0], NewWeights[1]));
2860 // OtherDest may have phi nodes. If so, add an entry from PBI's
2861 // block that are identical to the entries for BI's block.
2862 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2864 // We know that the CommonDest already had an edge from PBI to
2865 // it. If it has PHIs though, the PHIs may have different
2866 // entries for BB and PBI's BB. If so, insert a select to make
2869 for (BasicBlock::iterator II = CommonDest->begin();
2870 (PN = dyn_cast<PHINode>(II)); ++II) {
2871 Value *BIV = PN->getIncomingValueForBlock(BB);
2872 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2873 Value *PBIV = PN->getIncomingValue(PBBIdx);
2875 // Insert a select in PBI to pick the right value.
2876 Value *NV = cast<SelectInst>
2877 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2878 PN->setIncomingValue(PBBIdx, NV);
2882 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2883 DEBUG(dbgs() << *PBI->getParent()->getParent());
2885 // This basic block is probably dead. We know it has at least
2886 // one fewer predecessor.
2890 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2891 // true or to FalseBB if Cond is false.
2892 // Takes care of updating the successors and removing the old terminator.
2893 // Also makes sure not to introduce new successors by assuming that edges to
2894 // non-successor TrueBBs and FalseBBs aren't reachable.
2895 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2896 BasicBlock *TrueBB, BasicBlock *FalseBB,
2897 uint32_t TrueWeight,
2898 uint32_t FalseWeight){
2899 // Remove any superfluous successor edges from the CFG.
2900 // First, figure out which successors to preserve.
2901 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2903 BasicBlock *KeepEdge1 = TrueBB;
2904 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2906 // Then remove the rest.
2907 for (BasicBlock *Succ : OldTerm->successors()) {
2908 // Make sure only to keep exactly one copy of each edge.
2909 if (Succ == KeepEdge1)
2910 KeepEdge1 = nullptr;
2911 else if (Succ == KeepEdge2)
2912 KeepEdge2 = nullptr;
2914 Succ->removePredecessor(OldTerm->getParent(),
2915 /*DontDeleteUselessPHIs=*/true);
2918 IRBuilder<> Builder(OldTerm);
2919 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2921 // Insert an appropriate new terminator.
2922 if (!KeepEdge1 && !KeepEdge2) {
2923 if (TrueBB == FalseBB)
2924 // We were only looking for one successor, and it was present.
2925 // Create an unconditional branch to it.
2926 Builder.CreateBr(TrueBB);
2928 // We found both of the successors we were looking for.
2929 // Create a conditional branch sharing the condition of the select.
2930 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2931 if (TrueWeight != FalseWeight)
2932 NewBI->setMetadata(LLVMContext::MD_prof,
2933 MDBuilder(OldTerm->getContext()).
2934 createBranchWeights(TrueWeight, FalseWeight));
2936 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2937 // Neither of the selected blocks were successors, so this
2938 // terminator must be unreachable.
2939 new UnreachableInst(OldTerm->getContext(), OldTerm);
2941 // One of the selected values was a successor, but the other wasn't.
2942 // Insert an unconditional branch to the one that was found;
2943 // the edge to the one that wasn't must be unreachable.
2945 // Only TrueBB was found.
2946 Builder.CreateBr(TrueBB);
2948 // Only FalseBB was found.
2949 Builder.CreateBr(FalseBB);
2952 EraseTerminatorInstAndDCECond(OldTerm);
2957 // (switch (select cond, X, Y)) on constant X, Y
2958 // with a branch - conditional if X and Y lead to distinct BBs,
2959 // unconditional otherwise.
2960 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2961 // Check for constant integer values in the select.
2962 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2963 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2964 if (!TrueVal || !FalseVal)
2967 // Find the relevant condition and destinations.
2968 Value *Condition = Select->getCondition();
2969 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2970 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2972 // Get weight for TrueBB and FalseBB.
2973 uint32_t TrueWeight = 0, FalseWeight = 0;
2974 SmallVector<uint64_t, 8> Weights;
2975 bool HasWeights = HasBranchWeights(SI);
2977 GetBranchWeights(SI, Weights);
2978 if (Weights.size() == 1 + SI->getNumCases()) {
2979 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2980 getSuccessorIndex()];
2981 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2982 getSuccessorIndex()];
2986 // Perform the actual simplification.
2987 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2988 TrueWeight, FalseWeight);
2992 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2993 // blockaddress(@fn, BlockB)))
2995 // (br cond, BlockA, BlockB).
2996 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2997 // Check that both operands of the select are block addresses.
2998 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2999 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3003 // Extract the actual blocks.
3004 BasicBlock *TrueBB = TBA->getBasicBlock();
3005 BasicBlock *FalseBB = FBA->getBasicBlock();
3007 // Perform the actual simplification.
3008 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3012 /// This is called when we find an icmp instruction
3013 /// (a seteq/setne with a constant) as the only instruction in a
3014 /// block that ends with an uncond branch. We are looking for a very specific
3015 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3016 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3017 /// default value goes to an uncond block with a seteq in it, we get something
3020 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3022 /// %tmp = icmp eq i8 %A, 92
3025 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3027 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3028 /// the PHI, merging the third icmp into the switch.
3029 static bool TryToSimplifyUncondBranchWithICmpInIt(
3030 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3031 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3032 AssumptionCache *AC) {
3033 BasicBlock *BB = ICI->getParent();
3035 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3037 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3039 Value *V = ICI->getOperand(0);
3040 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3042 // The pattern we're looking for is where our only predecessor is a switch on
3043 // 'V' and this block is the default case for the switch. In this case we can
3044 // fold the compared value into the switch to simplify things.
3045 BasicBlock *Pred = BB->getSinglePredecessor();
3046 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
3048 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3049 if (SI->getCondition() != V)
3052 // If BB is reachable on a non-default case, then we simply know the value of
3053 // V in this block. Substitute it and constant fold the icmp instruction
3055 if (SI->getDefaultDest() != BB) {
3056 ConstantInt *VVal = SI->findCaseDest(BB);
3057 assert(VVal && "Should have a unique destination value");
3058 ICI->setOperand(0, VVal);
3060 if (Value *V = SimplifyInstruction(ICI, DL)) {
3061 ICI->replaceAllUsesWith(V);
3062 ICI->eraseFromParent();
3064 // BB is now empty, so it is likely to simplify away.
3065 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3068 // Ok, the block is reachable from the default dest. If the constant we're
3069 // comparing exists in one of the other edges, then we can constant fold ICI
3071 if (SI->findCaseValue(Cst) != SI->case_default()) {
3073 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3074 V = ConstantInt::getFalse(BB->getContext());
3076 V = ConstantInt::getTrue(BB->getContext());
3078 ICI->replaceAllUsesWith(V);
3079 ICI->eraseFromParent();
3080 // BB is now empty, so it is likely to simplify away.
3081 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3084 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3086 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3087 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3088 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3089 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3092 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3094 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3095 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3097 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3098 std::swap(DefaultCst, NewCst);
3100 // Replace ICI (which is used by the PHI for the default value) with true or
3101 // false depending on if it is EQ or NE.
3102 ICI->replaceAllUsesWith(DefaultCst);
3103 ICI->eraseFromParent();
3105 // Okay, the switch goes to this block on a default value. Add an edge from
3106 // the switch to the merge point on the compared value.
3107 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3108 BB->getParent(), BB);
3109 SmallVector<uint64_t, 8> Weights;
3110 bool HasWeights = HasBranchWeights(SI);
3112 GetBranchWeights(SI, Weights);
3113 if (Weights.size() == 1 + SI->getNumCases()) {
3114 // Split weight for default case to case for "Cst".
3115 Weights[0] = (Weights[0]+1) >> 1;
3116 Weights.push_back(Weights[0]);
3118 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3119 SI->setMetadata(LLVMContext::MD_prof,
3120 MDBuilder(SI->getContext()).
3121 createBranchWeights(MDWeights));
3124 SI->addCase(Cst, NewBB);
3126 // NewBB branches to the phi block, add the uncond branch and the phi entry.
3127 Builder.SetInsertPoint(NewBB);
3128 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3129 Builder.CreateBr(SuccBlock);
3130 PHIUse->addIncoming(NewCst, NewBB);
3134 /// The specified branch is a conditional branch.
3135 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3136 /// fold it into a switch instruction if so.
3137 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3138 const DataLayout &DL) {
3139 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3140 if (!Cond) return false;
3142 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3143 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3144 // 'setne's and'ed together, collect them.
3146 // Try to gather values from a chain of and/or to be turned into a switch
3147 ConstantComparesGatherer ConstantCompare(Cond, DL);
3148 // Unpack the result
3149 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3150 Value *CompVal = ConstantCompare.CompValue;
3151 unsigned UsedICmps = ConstantCompare.UsedICmps;
3152 Value *ExtraCase = ConstantCompare.Extra;
3154 // If we didn't have a multiply compared value, fail.
3155 if (!CompVal) return false;
3157 // Avoid turning single icmps into a switch.
3161 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3163 // There might be duplicate constants in the list, which the switch
3164 // instruction can't handle, remove them now.
3165 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3166 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3168 // If Extra was used, we require at least two switch values to do the
3169 // transformation. A switch with one value is just a conditional branch.
3170 if (ExtraCase && Values.size() < 2) return false;
3172 // TODO: Preserve branch weight metadata, similarly to how
3173 // FoldValueComparisonIntoPredecessors preserves it.
3175 // Figure out which block is which destination.
3176 BasicBlock *DefaultBB = BI->getSuccessor(1);
3177 BasicBlock *EdgeBB = BI->getSuccessor(0);
3178 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
3180 BasicBlock *BB = BI->getParent();
3182 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3183 << " cases into SWITCH. BB is:\n" << *BB);
3185 // If there are any extra values that couldn't be folded into the switch
3186 // then we evaluate them with an explicit branch first. Split the block
3187 // right before the condbr to handle it.
3190 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
3191 // Remove the uncond branch added to the old block.
3192 TerminatorInst *OldTI = BB->getTerminator();
3193 Builder.SetInsertPoint(OldTI);
3196 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
3198 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
3200 OldTI->eraseFromParent();
3202 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3203 // for the edge we just added.
3204 AddPredecessorToBlock(EdgeBB, BB, NewBB);
3206 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3207 << "\nEXTRABB = " << *BB);
3211 Builder.SetInsertPoint(BI);
3212 // Convert pointer to int before we switch.
3213 if (CompVal->getType()->isPointerTy()) {
3214 CompVal = Builder.CreatePtrToInt(
3215 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
3218 // Create the new switch instruction now.
3219 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
3221 // Add all of the 'cases' to the switch instruction.
3222 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3223 New->addCase(Values[i], EdgeBB);
3225 // We added edges from PI to the EdgeBB. As such, if there were any
3226 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3227 // the number of edges added.
3228 for (BasicBlock::iterator BBI = EdgeBB->begin();
3229 isa<PHINode>(BBI); ++BBI) {
3230 PHINode *PN = cast<PHINode>(BBI);
3231 Value *InVal = PN->getIncomingValueForBlock(BB);
3232 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3233 PN->addIncoming(InVal, BB);
3236 // Erase the old branch instruction.
3237 EraseTerminatorInstAndDCECond(BI);
3239 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
3243 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3244 if (isa<PHINode>(RI->getValue()))
3245 return SimplifyCommonResume(RI);
3246 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3247 RI->getValue() == RI->getParent()->getFirstNonPHI())
3248 // The resume must unwind the exception that caused control to branch here.
3249 return SimplifySingleResume(RI);
3252 // Simplify resume that is shared by several landing pads (phi of landing pad).
3253 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3254 BasicBlock *BB = RI->getParent();
3256 // Check that there are no other instructions except for debug intrinsics
3257 // between the phi of landing pads (RI->getValue()) and resume instruction.
3258 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3259 E = RI->getIterator();
3261 if (!isa<DbgInfoIntrinsic>(I))
3264 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3265 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3267 // Check incoming blocks to see if any of them are trivial.
3268 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3269 Idx != End; Idx++) {
3270 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3271 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3273 // If the block has other successors, we can not delete it because
3274 // it has other dependents.
3275 if (IncomingBB->getUniqueSuccessor() != BB)
3279 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3280 // Not the landing pad that caused the control to branch here.
3281 if (IncomingValue != LandingPad)
3284 bool isTrivial = true;
3286 I = IncomingBB->getFirstNonPHI()->getIterator();
3287 E = IncomingBB->getTerminator()->getIterator();
3289 if (!isa<DbgInfoIntrinsic>(I)) {
3295 TrivialUnwindBlocks.insert(IncomingBB);
3298 // If no trivial unwind blocks, don't do any simplifications.
3299 if (TrivialUnwindBlocks.empty()) return false;
3301 // Turn all invokes that unwind here into calls.
3302 for (auto *TrivialBB : TrivialUnwindBlocks) {
3303 // Blocks that will be simplified should be removed from the phi node.
3304 // Note there could be multiple edges to the resume block, and we need
3305 // to remove them all.
3306 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3307 BB->removePredecessor(TrivialBB, true);
3309 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3311 BasicBlock *Pred = *PI++;
3312 removeUnwindEdge(Pred);
3315 // In each SimplifyCFG run, only the current processed block can be erased.
3316 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3317 // of erasing TrivialBB, we only remove the branch to the common resume
3318 // block so that we can later erase the resume block since it has no
3320 TrivialBB->getTerminator()->eraseFromParent();
3321 new UnreachableInst(RI->getContext(), TrivialBB);
3324 // Delete the resume block if all its predecessors have been removed.
3326 BB->eraseFromParent();
3328 return !TrivialUnwindBlocks.empty();
3331 // Simplify resume that is only used by a single (non-phi) landing pad.
3332 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
3333 BasicBlock *BB = RI->getParent();
3334 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
3335 assert (RI->getValue() == LPInst &&
3336 "Resume must unwind the exception that caused control to here");
3338 // Check that there are no other instructions except for debug intrinsics.
3339 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3341 if (!isa<DbgInfoIntrinsic>(I))
3344 // Turn all invokes that unwind here into calls and delete the basic block.
3345 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3346 BasicBlock *Pred = *PI++;
3347 removeUnwindEdge(Pred);
3350 // The landingpad is now unreachable. Zap it.
3351 BB->eraseFromParent();
3355 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3356 // If this is a trivial cleanup pad that executes no instructions, it can be
3357 // eliminated. If the cleanup pad continues to the caller, any predecessor
3358 // that is an EH pad will be updated to continue to the caller and any
3359 // predecessor that terminates with an invoke instruction will have its invoke
3360 // instruction converted to a call instruction. If the cleanup pad being
3361 // simplified does not continue to the caller, each predecessor will be
3362 // updated to continue to the unwind destination of the cleanup pad being
3364 BasicBlock *BB = RI->getParent();
3365 CleanupPadInst *CPInst = RI->getCleanupPad();
3366 if (CPInst->getParent() != BB)
3367 // This isn't an empty cleanup.
3370 // Check that there are no other instructions except for debug intrinsics.
3371 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
3373 if (!isa<DbgInfoIntrinsic>(I))
3376 // If the cleanup return we are simplifying unwinds to the caller, this will
3377 // set UnwindDest to nullptr.
3378 BasicBlock *UnwindDest = RI->getUnwindDest();
3379 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
3381 // We're about to remove BB from the control flow. Before we do, sink any
3382 // PHINodes into the unwind destination. Doing this before changing the
3383 // control flow avoids some potentially slow checks, since we can currently
3384 // be certain that UnwindDest and BB have no common predecessors (since they
3385 // are both EH pads).
3387 // First, go through the PHI nodes in UnwindDest and update any nodes that
3388 // reference the block we are removing
3389 for (BasicBlock::iterator I = UnwindDest->begin(),
3390 IE = DestEHPad->getIterator();
3392 PHINode *DestPN = cast<PHINode>(I);
3394 int Idx = DestPN->getBasicBlockIndex(BB);
3395 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
3397 // This PHI node has an incoming value that corresponds to a control
3398 // path through the cleanup pad we are removing. If the incoming
3399 // value is in the cleanup pad, it must be a PHINode (because we
3400 // verified above that the block is otherwise empty). Otherwise, the
3401 // value is either a constant or a value that dominates the cleanup
3402 // pad being removed.
3404 // Because BB and UnwindDest are both EH pads, all of their
3405 // predecessors must unwind to these blocks, and since no instruction
3406 // can have multiple unwind destinations, there will be no overlap in
3407 // incoming blocks between SrcPN and DestPN.
3408 Value *SrcVal = DestPN->getIncomingValue(Idx);
3409 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3411 // Remove the entry for the block we are deleting.
3412 DestPN->removeIncomingValue(Idx, false);
3414 if (SrcPN && SrcPN->getParent() == BB) {
3415 // If the incoming value was a PHI node in the cleanup pad we are
3416 // removing, we need to merge that PHI node's incoming values into
3418 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3419 SrcIdx != SrcE; ++SrcIdx) {
3420 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3421 SrcPN->getIncomingBlock(SrcIdx));
3424 // Otherwise, the incoming value came from above BB and
3425 // so we can just reuse it. We must associate all of BB's
3426 // predecessors with this value.
3427 for (auto *pred : predecessors(BB)) {
3428 DestPN->addIncoming(SrcVal, pred);
3433 // Sink any remaining PHI nodes directly into UnwindDest.
3434 Instruction *InsertPt = DestEHPad;
3435 for (BasicBlock::iterator I = BB->begin(),
3436 IE = BB->getFirstNonPHI()->getIterator();
3438 // The iterator must be incremented here because the instructions are
3439 // being moved to another block.
3440 PHINode *PN = cast<PHINode>(I++);
3441 if (PN->use_empty())
3442 // If the PHI node has no uses, just leave it. It will be erased
3443 // when we erase BB below.
3446 // Otherwise, sink this PHI node into UnwindDest.
3447 // Any predecessors to UnwindDest which are not already represented
3448 // must be back edges which inherit the value from the path through
3449 // BB. In this case, the PHI value must reference itself.
3450 for (auto *pred : predecessors(UnwindDest))
3452 PN->addIncoming(PN, pred);
3453 PN->moveBefore(InsertPt);
3457 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3458 // The iterator must be updated here because we are removing this pred.
3459 BasicBlock *PredBB = *PI++;
3460 if (UnwindDest == nullptr) {
3461 removeUnwindEdge(PredBB);
3463 TerminatorInst *TI = PredBB->getTerminator();
3464 TI->replaceUsesOfWith(BB, UnwindDest);
3468 // The cleanup pad is now unreachable. Zap it.
3469 BB->eraseFromParent();
3473 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
3474 BasicBlock *BB = RI->getParent();
3475 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
3477 // Find predecessors that end with branches.
3478 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3479 SmallVector<BranchInst*, 8> CondBranchPreds;
3480 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3481 BasicBlock *P = *PI;
3482 TerminatorInst *PTI = P->getTerminator();
3483 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3484 if (BI->isUnconditional())
3485 UncondBranchPreds.push_back(P);
3487 CondBranchPreds.push_back(BI);
3491 // If we found some, do the transformation!
3492 if (!UncondBranchPreds.empty() && DupRet) {
3493 while (!UncondBranchPreds.empty()) {
3494 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3495 DEBUG(dbgs() << "FOLDING: " << *BB
3496 << "INTO UNCOND BRANCH PRED: " << *Pred);
3497 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3500 // If we eliminated all predecessors of the block, delete the block now.
3502 // We know there are no successors, so just nuke the block.
3503 BB->eraseFromParent();
3508 // Check out all of the conditional branches going to this return
3509 // instruction. If any of them just select between returns, change the
3510 // branch itself into a select/return pair.
3511 while (!CondBranchPreds.empty()) {
3512 BranchInst *BI = CondBranchPreds.pop_back_val();
3514 // Check to see if the non-BB successor is also a return block.
3515 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3516 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3517 SimplifyCondBranchToTwoReturns(BI, Builder))
3523 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3524 BasicBlock *BB = UI->getParent();
3526 bool Changed = false;
3528 // If there are any instructions immediately before the unreachable that can
3529 // be removed, do so.
3530 while (UI->getIterator() != BB->begin()) {
3531 BasicBlock::iterator BBI = UI->getIterator();
3533 // Do not delete instructions that can have side effects which might cause
3534 // the unreachable to not be reachable; specifically, calls and volatile
3535 // operations may have this effect.
3536 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3538 if (BBI->mayHaveSideEffects()) {
3539 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
3540 if (SI->isVolatile())
3542 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
3543 if (LI->isVolatile())
3545 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3546 if (RMWI->isVolatile())
3548 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3549 if (CXI->isVolatile())
3551 } else if (isa<CatchPadInst>(BBI)) {
3552 // A catchpad may invoke exception object constructors and such, which
3553 // in some languages can be arbitrary code, so be conservative by
3555 // For CoreCLR, it just involves a type test, so can be removed.
3556 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3557 EHPersonality::CoreCLR)
3559 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3560 !isa<LandingPadInst>(BBI)) {
3563 // Note that deleting LandingPad's here is in fact okay, although it
3564 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3565 // all the predecessors of this block will be the unwind edges of Invokes,
3566 // and we can therefore guarantee this block will be erased.
3569 // Delete this instruction (any uses are guaranteed to be dead)
3570 if (!BBI->use_empty())
3571 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3572 BBI->eraseFromParent();
3576 // If the unreachable instruction is the first in the block, take a gander
3577 // at all of the predecessors of this instruction, and simplify them.
3578 if (&BB->front() != UI) return Changed;
3580 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3581 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3582 TerminatorInst *TI = Preds[i]->getTerminator();
3583 IRBuilder<> Builder(TI);
3584 if (auto *BI = dyn_cast<BranchInst>(TI)) {
3585 if (BI->isUnconditional()) {
3586 if (BI->getSuccessor(0) == BB) {
3587 new UnreachableInst(TI->getContext(), TI);
3588 TI->eraseFromParent();
3592 if (BI->getSuccessor(0) == BB) {
3593 Builder.CreateBr(BI->getSuccessor(1));
3594 EraseTerminatorInstAndDCECond(BI);
3595 } else if (BI->getSuccessor(1) == BB) {
3596 Builder.CreateBr(BI->getSuccessor(0));
3597 EraseTerminatorInstAndDCECond(BI);
3601 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
3602 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3604 if (i.getCaseSuccessor() == BB) {
3605 BB->removePredecessor(SI->getParent());
3610 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3611 if (II->getUnwindDest() == BB) {
3612 removeUnwindEdge(TI->getParent());
3615 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3616 if (CSI->getUnwindDest() == BB) {
3617 removeUnwindEdge(TI->getParent());
3622 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3623 E = CSI->handler_end();
3626 CSI->removeHandler(I);
3632 if (CSI->getNumHandlers() == 0) {
3633 BasicBlock *CatchSwitchBB = CSI->getParent();
3634 if (CSI->hasUnwindDest()) {
3635 // Redirect preds to the unwind dest
3636 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3638 // Rewrite all preds to unwind to caller (or from invoke to call).
3639 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3640 for (BasicBlock *EHPred : EHPreds)
3641 removeUnwindEdge(EHPred);
3643 // The catchswitch is no longer reachable.
3644 new UnreachableInst(CSI->getContext(), CSI);
3645 CSI->eraseFromParent();
3648 } else if (isa<CleanupReturnInst>(TI)) {
3649 new UnreachableInst(TI->getContext(), TI);
3650 TI->eraseFromParent();
3655 // If this block is now dead, remove it.
3656 if (pred_empty(BB) &&
3657 BB != &BB->getParent()->getEntryBlock()) {
3658 // We know there are no successors, so just nuke the block.
3659 BB->eraseFromParent();
3666 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3667 assert(Cases.size() >= 1);
3669 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3670 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3671 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3677 /// Turn a switch with two reachable destinations into an integer range
3678 /// comparison and branch.
3679 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3680 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3683 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3685 // Partition the cases into two sets with different destinations.
3686 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3687 BasicBlock *DestB = nullptr;
3688 SmallVector <ConstantInt *, 16> CasesA;
3689 SmallVector <ConstantInt *, 16> CasesB;
3691 for (SwitchInst::CaseIt I : SI->cases()) {
3692 BasicBlock *Dest = I.getCaseSuccessor();
3693 if (!DestA) DestA = Dest;
3694 if (Dest == DestA) {
3695 CasesA.push_back(I.getCaseValue());
3698 if (!DestB) DestB = Dest;
3699 if (Dest == DestB) {
3700 CasesB.push_back(I.getCaseValue());
3703 return false; // More than two destinations.
3706 assert(DestA && DestB && "Single-destination switch should have been folded.");
3707 assert(DestA != DestB);
3708 assert(DestB != SI->getDefaultDest());
3709 assert(!CasesB.empty() && "There must be non-default cases.");
3710 assert(!CasesA.empty() || HasDefault);
3712 // Figure out if one of the sets of cases form a contiguous range.
3713 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3714 BasicBlock *ContiguousDest = nullptr;
3715 BasicBlock *OtherDest = nullptr;
3716 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3717 ContiguousCases = &CasesA;
3718 ContiguousDest = DestA;
3720 } else if (CasesAreContiguous(CasesB)) {
3721 ContiguousCases = &CasesB;
3722 ContiguousDest = DestB;
3727 // Start building the compare and branch.
3729 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3730 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
3732 Value *Sub = SI->getCondition();
3733 if (!Offset->isNullValue())
3734 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3737 // If NumCases overflowed, then all possible values jump to the successor.
3738 if (NumCases->isNullValue() && !ContiguousCases->empty())
3739 Cmp = ConstantInt::getTrue(SI->getContext());
3741 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3742 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
3744 // Update weight for the newly-created conditional branch.
3745 if (HasBranchWeights(SI)) {
3746 SmallVector<uint64_t, 8> Weights;
3747 GetBranchWeights(SI, Weights);
3748 if (Weights.size() == 1 + SI->getNumCases()) {
3749 uint64_t TrueWeight = 0;
3750 uint64_t FalseWeight = 0;
3751 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3752 if (SI->getSuccessor(I) == ContiguousDest)
3753 TrueWeight += Weights[I];
3755 FalseWeight += Weights[I];
3757 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3761 NewBI->setMetadata(LLVMContext::MD_prof,
3762 MDBuilder(SI->getContext()).createBranchWeights(
3763 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
3767 // Prune obsolete incoming values off the successors' PHI nodes.
3768 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3769 unsigned PreviousEdges = ContiguousCases->size();
3770 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3771 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3772 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3774 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3775 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3776 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3777 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3778 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3782 SI->eraseFromParent();
3787 /// Compute masked bits for the condition of a switch
3788 /// and use it to remove dead cases.
3789 static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3790 const DataLayout &DL) {
3791 Value *Cond = SI->getCondition();
3792 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3793 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3794 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
3796 // Gather dead cases.
3797 SmallVector<ConstantInt*, 8> DeadCases;
3798 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3799 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3800 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3801 DeadCases.push_back(I.getCaseValue());
3802 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3803 << I.getCaseValue() << "' is dead.\n");
3807 // If we can prove that the cases must cover all possible values, the
3808 // default destination becomes dead and we can remove it. If we know some
3809 // of the bits in the value, we can use that to more precisely compute the
3810 // number of possible unique case values.
3812 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3813 const unsigned NumUnknownBits = Bits -
3814 (KnownZero.Or(KnownOne)).countPopulation();
3815 assert(NumUnknownBits <= Bits);
3816 if (HasDefault && DeadCases.empty() &&
3817 NumUnknownBits < 64 /* avoid overflow */ &&
3818 SI->getNumCases() == (1ULL << NumUnknownBits)) {
3819 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3820 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3821 SI->getParent(), "");
3822 SI->setDefaultDest(&*NewDefault);
3823 SplitBlock(&*NewDefault, &NewDefault->front());
3824 auto *OldTI = NewDefault->getTerminator();
3825 new UnreachableInst(SI->getContext(), OldTI);
3826 EraseTerminatorInstAndDCECond(OldTI);
3830 SmallVector<uint64_t, 8> Weights;
3831 bool HasWeight = HasBranchWeights(SI);
3833 GetBranchWeights(SI, Weights);
3834 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3837 // Remove dead cases from the switch.
3838 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3839 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3840 assert(Case != SI->case_default() &&
3841 "Case was not found. Probably mistake in DeadCases forming.");
3843 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3847 // Prune unused values from PHI nodes.
3848 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3849 SI->removeCase(Case);
3851 if (HasWeight && Weights.size() >= 2) {
3852 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3853 SI->setMetadata(LLVMContext::MD_prof,
3854 MDBuilder(SI->getParent()->getContext()).
3855 createBranchWeights(MDWeights));
3858 return !DeadCases.empty();
3861 /// If BB would be eligible for simplification by
3862 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3863 /// by an unconditional branch), look at the phi node for BB in the successor
3864 /// block and see if the incoming value is equal to CaseValue. If so, return
3865 /// the phi node, and set PhiIndex to BB's index in the phi node.
3866 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3869 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3870 return nullptr; // BB must be empty to be a candidate for simplification.
3871 if (!BB->getSinglePredecessor())
3872 return nullptr; // BB must be dominated by the switch.
3874 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3875 if (!Branch || !Branch->isUnconditional())
3876 return nullptr; // Terminator must be unconditional branch.
3878 BasicBlock *Succ = Branch->getSuccessor(0);
3880 BasicBlock::iterator I = Succ->begin();
3881 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3882 int Idx = PHI->getBasicBlockIndex(BB);
3883 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3885 Value *InValue = PHI->getIncomingValue(Idx);
3886 if (InValue != CaseValue) continue;
3895 /// Try to forward the condition of a switch instruction to a phi node
3896 /// dominated by the switch, if that would mean that some of the destination
3897 /// blocks of the switch can be folded away.
3898 /// Returns true if a change is made.
3899 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3900 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3901 ForwardingNodesMap ForwardingNodes;
3903 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3904 ConstantInt *CaseValue = I.getCaseValue();
3905 BasicBlock *CaseDest = I.getCaseSuccessor();
3908 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3912 ForwardingNodes[PHI].push_back(PhiIndex);
3915 bool Changed = false;
3917 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3918 E = ForwardingNodes.end(); I != E; ++I) {
3919 PHINode *Phi = I->first;
3920 SmallVectorImpl<int> &Indexes = I->second;
3922 if (Indexes.size() < 2) continue;
3924 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3925 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3932 /// Return true if the backend will be able to handle
3933 /// initializing an array of constants like C.
3934 static bool ValidLookupTableConstant(Constant *C) {
3935 if (C->isThreadDependent())
3937 if (C->isDLLImportDependent())
3940 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3941 return CE->isGEPWithNoNotionalOverIndexing();
3943 return isa<ConstantFP>(C) ||
3944 isa<ConstantInt>(C) ||
3945 isa<ConstantPointerNull>(C) ||
3946 isa<GlobalValue>(C) ||
3950 /// If V is a Constant, return it. Otherwise, try to look up
3951 /// its constant value in ConstantPool, returning 0 if it's not there.
3952 static Constant *LookupConstant(Value *V,
3953 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3954 if (Constant *C = dyn_cast<Constant>(V))
3956 return ConstantPool.lookup(V);
3959 /// Try to fold instruction I into a constant. This works for
3960 /// simple instructions such as binary operations where both operands are
3961 /// constant or can be replaced by constants from the ConstantPool. Returns the
3962 /// resulting constant on success, 0 otherwise.
3964 ConstantFold(Instruction *I, const DataLayout &DL,
3965 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
3966 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3967 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3970 if (A->isAllOnesValue())
3971 return LookupConstant(Select->getTrueValue(), ConstantPool);
3972 if (A->isNullValue())
3973 return LookupConstant(Select->getFalseValue(), ConstantPool);
3977 SmallVector<Constant *, 4> COps;
3978 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3979 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3985 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3986 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3990 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3993 /// Try to determine the resulting constant values in phi nodes
3994 /// at the common destination basic block, *CommonDest, for one of the case
3995 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3996 /// case), of a switch instruction SI.
3998 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
3999 BasicBlock **CommonDest,
4000 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4001 const DataLayout &DL) {
4002 // The block from which we enter the common destination.
4003 BasicBlock *Pred = SI->getParent();
4005 // If CaseDest is empty except for some side-effect free instructions through
4006 // which we can constant-propagate the CaseVal, continue to its successor.
4007 SmallDenseMap<Value*, Constant*> ConstantPool;
4008 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4009 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4011 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4012 // If the terminator is a simple branch, continue to the next block.
4013 if (T->getNumSuccessors() != 1)
4016 CaseDest = T->getSuccessor(0);
4017 } else if (isa<DbgInfoIntrinsic>(I)) {
4018 // Skip debug intrinsic.
4020 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
4021 // Instruction is side-effect free and constant.
4023 // If the instruction has uses outside this block or a phi node slot for
4024 // the block, it is not safe to bypass the instruction since it would then
4025 // no longer dominate all its uses.
4026 for (auto &Use : I->uses()) {
4027 User *User = Use.getUser();
4028 if (Instruction *I = dyn_cast<Instruction>(User))
4029 if (I->getParent() == CaseDest)
4031 if (PHINode *Phi = dyn_cast<PHINode>(User))
4032 if (Phi->getIncomingBlock(Use) == CaseDest)
4037 ConstantPool.insert(std::make_pair(&*I, C));
4043 // If we did not have a CommonDest before, use the current one.
4045 *CommonDest = CaseDest;
4046 // If the destination isn't the common one, abort.
4047 if (CaseDest != *CommonDest)
4050 // Get the values for this case from phi nodes in the destination block.
4051 BasicBlock::iterator I = (*CommonDest)->begin();
4052 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4053 int Idx = PHI->getBasicBlockIndex(Pred);
4057 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4062 // Be conservative about which kinds of constants we support.
4063 if (!ValidLookupTableConstant(ConstVal))
4066 Res.push_back(std::make_pair(PHI, ConstVal));
4069 return Res.size() > 0;
4072 // Helper function used to add CaseVal to the list of cases that generate
4074 static void MapCaseToResult(ConstantInt *CaseVal,
4075 SwitchCaseResultVectorTy &UniqueResults,
4077 for (auto &I : UniqueResults) {
4078 if (I.first == Result) {
4079 I.second.push_back(CaseVal);
4083 UniqueResults.push_back(std::make_pair(Result,
4084 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4087 // Helper function that initializes a map containing
4088 // results for the PHI node of the common destination block for a switch
4089 // instruction. Returns false if multiple PHI nodes have been found or if
4090 // there is not a common destination block for the switch.
4091 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4092 BasicBlock *&CommonDest,
4093 SwitchCaseResultVectorTy &UniqueResults,
4094 Constant *&DefaultResult,
4095 const DataLayout &DL) {
4096 for (auto &I : SI->cases()) {
4097 ConstantInt *CaseVal = I.getCaseValue();
4099 // Resulting value at phi nodes for this case value.
4100 SwitchCaseResultsTy Results;
4101 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4105 // Only one value per case is permitted
4106 if (Results.size() > 1)
4108 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4110 // Check the PHI consistency.
4112 PHI = Results[0].first;
4113 else if (PHI != Results[0].first)
4116 // Find the default result value.
4117 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4118 BasicBlock *DefaultDest = SI->getDefaultDest();
4119 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4121 // If the default value is not found abort unless the default destination
4124 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4125 if ((!DefaultResult &&
4126 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4132 // Helper function that checks if it is possible to transform a switch with only
4133 // two cases (or two cases + default) that produces a result into a select.
4136 // case 10: %0 = icmp eq i32 %a, 10
4137 // return 10; %1 = select i1 %0, i32 10, i32 4
4138 // case 20: ----> %2 = icmp eq i32 %a, 20
4139 // return 2; %3 = select i1 %2, i32 2, i32 %1
4144 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4145 Constant *DefaultResult, Value *Condition,
4146 IRBuilder<> &Builder) {
4147 assert(ResultVector.size() == 2 &&
4148 "We should have exactly two unique results at this point");
4149 // If we are selecting between only two cases transform into a simple
4150 // select or a two-way select if default is possible.
4151 if (ResultVector[0].second.size() == 1 &&
4152 ResultVector[1].second.size() == 1) {
4153 ConstantInt *const FirstCase = ResultVector[0].second[0];
4154 ConstantInt *const SecondCase = ResultVector[1].second[0];
4156 bool DefaultCanTrigger = DefaultResult;
4157 Value *SelectValue = ResultVector[1].first;
4158 if (DefaultCanTrigger) {
4159 Value *const ValueCompare =
4160 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4161 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4162 DefaultResult, "switch.select");
4164 Value *const ValueCompare =
4165 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4166 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4173 // Helper function to cleanup a switch instruction that has been converted into
4174 // a select, fixing up PHI nodes and basic blocks.
4175 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4177 IRBuilder<> &Builder) {
4178 BasicBlock *SelectBB = SI->getParent();
4179 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4180 PHI->removeIncomingValue(SelectBB);
4181 PHI->addIncoming(SelectValue, SelectBB);
4183 Builder.CreateBr(PHI->getParent());
4185 // Remove the switch.
4186 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4187 BasicBlock *Succ = SI->getSuccessor(i);
4189 if (Succ == PHI->getParent())
4191 Succ->removePredecessor(SelectBB);
4193 SI->eraseFromParent();
4196 /// If the switch is only used to initialize one or more
4197 /// phi nodes in a common successor block with only two different
4198 /// constant values, replace the switch with select.
4199 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4200 AssumptionCache *AC, const DataLayout &DL) {
4201 Value *const Cond = SI->getCondition();
4202 PHINode *PHI = nullptr;
4203 BasicBlock *CommonDest = nullptr;
4204 Constant *DefaultResult;
4205 SwitchCaseResultVectorTy UniqueResults;
4206 // Collect all the cases that will deliver the same value from the switch.
4207 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4210 // Selects choose between maximum two values.
4211 if (UniqueResults.size() != 2)
4213 assert(PHI != nullptr && "PHI for value select not found");
4215 Builder.SetInsertPoint(SI);
4216 Value *SelectValue = ConvertTwoCaseSwitch(
4218 DefaultResult, Cond, Builder);
4220 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4223 // The switch couldn't be converted into a select.
4228 /// This class represents a lookup table that can be used to replace a switch.
4229 class SwitchLookupTable {
4231 /// Create a lookup table to use as a switch replacement with the contents
4232 /// of Values, using DefaultValue to fill any holes in the table.
4234 Module &M, uint64_t TableSize, ConstantInt *Offset,
4235 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4236 Constant *DefaultValue, const DataLayout &DL);
4238 /// Build instructions with Builder to retrieve the value at
4239 /// the position given by Index in the lookup table.
4240 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4242 /// Return true if a table with TableSize elements of
4243 /// type ElementType would fit in a target-legal register.
4244 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4248 // Depending on the contents of the table, it can be represented in
4251 // For tables where each element contains the same value, we just have to
4252 // store that single value and return it for each lookup.
4255 // For tables where there is a linear relationship between table index
4256 // and values. We calculate the result with a simple multiplication
4257 // and addition instead of a table lookup.
4260 // For small tables with integer elements, we can pack them into a bitmap
4261 // that fits into a target-legal register. Values are retrieved by
4262 // shift and mask operations.
4265 // The table is stored as an array of values. Values are retrieved by load
4266 // instructions from the table.
4270 // For SingleValueKind, this is the single value.
4271 Constant *SingleValue;
4273 // For BitMapKind, this is the bitmap.
4274 ConstantInt *BitMap;
4275 IntegerType *BitMapElementTy;
4277 // For LinearMapKind, these are the constants used to derive the value.
4278 ConstantInt *LinearOffset;
4279 ConstantInt *LinearMultiplier;
4281 // For ArrayKind, this is the array.
4282 GlobalVariable *Array;
4286 SwitchLookupTable::SwitchLookupTable(
4287 Module &M, uint64_t TableSize, ConstantInt *Offset,
4288 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4289 Constant *DefaultValue, const DataLayout &DL)
4290 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
4291 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
4292 assert(Values.size() && "Can't build lookup table without values!");
4293 assert(TableSize >= Values.size() && "Can't fit values in table!");
4295 // If all values in the table are equal, this is that value.
4296 SingleValue = Values.begin()->second;
4298 Type *ValueType = Values.begin()->second->getType();
4300 // Build up the table contents.
4301 SmallVector<Constant*, 64> TableContents(TableSize);
4302 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4303 ConstantInt *CaseVal = Values[I].first;
4304 Constant *CaseRes = Values[I].second;
4305 assert(CaseRes->getType() == ValueType);
4307 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4309 TableContents[Idx] = CaseRes;
4311 if (CaseRes != SingleValue)
4312 SingleValue = nullptr;
4315 // Fill in any holes in the table with the default result.
4316 if (Values.size() < TableSize) {
4317 assert(DefaultValue &&
4318 "Need a default value to fill the lookup table holes.");
4319 assert(DefaultValue->getType() == ValueType);
4320 for (uint64_t I = 0; I < TableSize; ++I) {
4321 if (!TableContents[I])
4322 TableContents[I] = DefaultValue;
4325 if (DefaultValue != SingleValue)
4326 SingleValue = nullptr;
4329 // If each element in the table contains the same value, we only need to store
4330 // that single value.
4332 Kind = SingleValueKind;
4336 // Check if we can derive the value with a linear transformation from the
4338 if (isa<IntegerType>(ValueType)) {
4339 bool LinearMappingPossible = true;
4342 assert(TableSize >= 2 && "Should be a SingleValue table.");
4343 // Check if there is the same distance between two consecutive values.
4344 for (uint64_t I = 0; I < TableSize; ++I) {
4345 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4347 // This is an undef. We could deal with it, but undefs in lookup tables
4348 // are very seldom. It's probably not worth the additional complexity.
4349 LinearMappingPossible = false;
4352 APInt Val = ConstVal->getValue();
4354 APInt Dist = Val - PrevVal;
4357 } else if (Dist != DistToPrev) {
4358 LinearMappingPossible = false;
4364 if (LinearMappingPossible) {
4365 LinearOffset = cast<ConstantInt>(TableContents[0]);
4366 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4367 Kind = LinearMapKind;
4373 // If the type is integer and the table fits in a register, build a bitmap.
4374 if (WouldFitInRegister(DL, TableSize, ValueType)) {
4375 IntegerType *IT = cast<IntegerType>(ValueType);
4376 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4377 for (uint64_t I = TableSize; I > 0; --I) {
4378 TableInt <<= IT->getBitWidth();
4379 // Insert values into the bitmap. Undef values are set to zero.
4380 if (!isa<UndefValue>(TableContents[I - 1])) {
4381 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4382 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4385 BitMap = ConstantInt::get(M.getContext(), TableInt);
4386 BitMapElementTy = IT;
4392 // Store the table in an array.
4393 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4394 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4396 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4397 GlobalVariable::PrivateLinkage,
4400 Array->setUnnamedAddr(true);
4404 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
4406 case SingleValueKind:
4408 case LinearMapKind: {
4409 // Derive the result value from the input value.
4410 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4411 false, "switch.idx.cast");
4412 if (!LinearMultiplier->isOne())
4413 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4414 if (!LinearOffset->isZero())
4415 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4419 // Type of the bitmap (e.g. i59).
4420 IntegerType *MapTy = BitMap->getType();
4422 // Cast Index to the same type as the bitmap.
4423 // Note: The Index is <= the number of elements in the table, so
4424 // truncating it to the width of the bitmask is safe.
4425 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
4427 // Multiply the shift amount by the element width.
4428 ShiftAmt = Builder.CreateMul(ShiftAmt,
4429 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4433 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4434 "switch.downshift");
4436 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4440 // Make sure the table index will not overflow when treated as signed.
4441 IntegerType *IT = cast<IntegerType>(Index->getType());
4442 uint64_t TableSize = Array->getInitializer()->getType()
4443 ->getArrayNumElements();
4444 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4445 Index = Builder.CreateZExt(Index,
4446 IntegerType::get(IT->getContext(),
4447 IT->getBitWidth() + 1),
4448 "switch.tableidx.zext");
4450 Value *GEPIndices[] = { Builder.getInt32(0), Index };
4451 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4452 GEPIndices, "switch.gep");
4453 return Builder.CreateLoad(GEP, "switch.load");
4456 llvm_unreachable("Unknown lookup table kind!");
4459 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
4461 Type *ElementType) {
4462 auto *IT = dyn_cast<IntegerType>(ElementType);
4465 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4466 // are <= 15, we could try to narrow the type.
4468 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4469 if (TableSize >= UINT_MAX/IT->getBitWidth())
4471 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
4474 /// Determine whether a lookup table should be built for this switch, based on
4475 /// the number of cases, size of the table, and the types of the results.
4477 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4478 const TargetTransformInfo &TTI, const DataLayout &DL,
4479 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
4480 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4481 return false; // TableSize overflowed, or mul below might overflow.
4483 bool AllTablesFitInRegister = true;
4484 bool HasIllegalType = false;
4485 for (const auto &I : ResultTypes) {
4486 Type *Ty = I.second;
4488 // Saturate this flag to true.
4489 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
4491 // Saturate this flag to false.
4492 AllTablesFitInRegister = AllTablesFitInRegister &&
4493 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
4495 // If both flags saturate, we're done. NOTE: This *only* works with
4496 // saturating flags, and all flags have to saturate first due to the
4497 // non-deterministic behavior of iterating over a dense map.
4498 if (HasIllegalType && !AllTablesFitInRegister)
4502 // If each table would fit in a register, we should build it anyway.
4503 if (AllTablesFitInRegister)
4506 // Don't build a table that doesn't fit in-register if it has illegal types.
4510 // The table density should be at least 40%. This is the same criterion as for
4511 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4512 // FIXME: Find the best cut-off.
4513 return SI->getNumCases() * 10 >= TableSize * 4;
4516 /// Try to reuse the switch table index compare. Following pattern:
4518 /// if (idx < tablesize)
4519 /// r = table[idx]; // table does not contain default_value
4521 /// r = default_value;
4522 /// if (r != default_value)
4525 /// Is optimized to:
4527 /// cond = idx < tablesize;
4531 /// r = default_value;
4535 /// Jump threading will then eliminate the second if(cond).
4536 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4537 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4538 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4540 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4544 // We require that the compare is in the same block as the phi so that jump
4545 // threading can do its work afterwards.
4546 if (CmpInst->getParent() != PhiBlock)
4549 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4553 Value *RangeCmp = RangeCheckBranch->getCondition();
4554 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4555 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4557 // Check if the compare with the default value is constant true or false.
4558 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4559 DefaultValue, CmpOp1, true);
4560 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4563 // Check if the compare with the case values is distinct from the default
4565 for (auto ValuePair : Values) {
4566 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4567 ValuePair.second, CmpOp1, true);
4568 if (!CaseConst || CaseConst == DefaultConst)
4570 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4571 "Expect true or false as compare result.");
4574 // Check if the branch instruction dominates the phi node. It's a simple
4575 // dominance check, but sufficient for our needs.
4576 // Although this check is invariant in the calling loops, it's better to do it
4577 // at this late stage. Practically we do it at most once for a switch.
4578 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4579 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4580 BasicBlock *Pred = *PI;
4581 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4585 if (DefaultConst == FalseConst) {
4586 // The compare yields the same result. We can replace it.
4587 CmpInst->replaceAllUsesWith(RangeCmp);
4588 ++NumTableCmpReuses;
4590 // The compare yields the same result, just inverted. We can replace it.
4591 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4592 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4594 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4595 ++NumTableCmpReuses;
4599 /// If the switch is only used to initialize one or more phi nodes in a common
4600 /// successor block with different constant values, replace the switch with
4602 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4603 const DataLayout &DL,
4604 const TargetTransformInfo &TTI) {
4605 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4607 // Only build lookup table when we have a target that supports it.
4608 if (!TTI.shouldBuildLookupTables())
4611 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4612 // split off a dense part and build a lookup table for that.
4614 // FIXME: This creates arrays of GEPs to constant strings, which means each
4615 // GEP needs a runtime relocation in PIC code. We should just build one big
4616 // string and lookup indices into that.
4618 // Ignore switches with less than three cases. Lookup tables will not make them
4619 // faster, so we don't analyze them.
4620 if (SI->getNumCases() < 3)
4623 // Figure out the corresponding result for each case value and phi node in the
4624 // common destination, as well as the min and max case values.
4625 assert(SI->case_begin() != SI->case_end());
4626 SwitchInst::CaseIt CI = SI->case_begin();
4627 ConstantInt *MinCaseVal = CI.getCaseValue();
4628 ConstantInt *MaxCaseVal = CI.getCaseValue();
4630 BasicBlock *CommonDest = nullptr;
4631 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4632 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4633 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4634 SmallDenseMap<PHINode*, Type*> ResultTypes;
4635 SmallVector<PHINode*, 4> PHIs;
4637 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4638 ConstantInt *CaseVal = CI.getCaseValue();
4639 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4640 MinCaseVal = CaseVal;
4641 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4642 MaxCaseVal = CaseVal;
4644 // Resulting value at phi nodes for this case value.
4645 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4647 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4651 // Append the result from this case to the list for each phi.
4652 for (const auto &I : Results) {
4653 PHINode *PHI = I.first;
4654 Constant *Value = I.second;
4655 if (!ResultLists.count(PHI))
4656 PHIs.push_back(PHI);
4657 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4661 // Keep track of the result types.
4662 for (PHINode *PHI : PHIs) {
4663 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4666 uint64_t NumResults = ResultLists[PHIs[0]].size();
4667 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4668 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4669 bool TableHasHoles = (NumResults < TableSize);
4671 // If the table has holes, we need a constant result for the default case
4672 // or a bitmask that fits in a register.
4673 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4674 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4675 &CommonDest, DefaultResultsList, DL);
4677 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4679 // As an extra penalty for the validity test we require more cases.
4680 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4682 if (!DL.fitsInLegalInteger(TableSize))
4686 for (const auto &I : DefaultResultsList) {
4687 PHINode *PHI = I.first;
4688 Constant *Result = I.second;
4689 DefaultResults[PHI] = Result;
4692 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4695 // Create the BB that does the lookups.
4696 Module &Mod = *CommonDest->getParent()->getParent();
4697 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4699 CommonDest->getParent(),
4702 // Compute the table index value.
4703 Builder.SetInsertPoint(SI);
4704 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4707 // Compute the maximum table size representable by the integer type we are
4709 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4710 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4711 assert(MaxTableSize >= TableSize &&
4712 "It is impossible for a switch to have more entries than the max "
4713 "representable value of its input integer type's size.");
4715 // If the default destination is unreachable, or if the lookup table covers
4716 // all values of the conditional variable, branch directly to the lookup table
4717 // BB. Otherwise, check that the condition is within the case range.
4718 const bool DefaultIsReachable =
4719 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4720 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
4721 BranchInst *RangeCheckBranch = nullptr;
4723 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4724 Builder.CreateBr(LookupBB);
4725 // Note: We call removeProdecessor later since we need to be able to get the
4726 // PHI value for the default case in case we're using a bit mask.
4728 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4729 MinCaseVal->getType(), TableSize));
4730 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4733 // Populate the BB that does the lookups.
4734 Builder.SetInsertPoint(LookupBB);
4737 // Before doing the lookup we do the hole check.
4738 // The LookupBB is therefore re-purposed to do the hole check
4739 // and we create a new LookupBB.
4740 BasicBlock *MaskBB = LookupBB;
4741 MaskBB->setName("switch.hole_check");
4742 LookupBB = BasicBlock::Create(Mod.getContext(),
4744 CommonDest->getParent(),
4747 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4748 // unnecessary illegal types.
4749 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4750 APInt MaskInt(TableSizePowOf2, 0);
4751 APInt One(TableSizePowOf2, 1);
4752 // Build bitmask; fill in a 1 bit for every case.
4753 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4754 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4755 uint64_t Idx = (ResultList[I].first->getValue() -
4756 MinCaseVal->getValue()).getLimitedValue();
4757 MaskInt |= One << Idx;
4759 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4761 // Get the TableIndex'th bit of the bitmask.
4762 // If this bit is 0 (meaning hole) jump to the default destination,
4763 // else continue with table lookup.
4764 IntegerType *MapTy = TableMask->getType();
4765 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4766 "switch.maskindex");
4767 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4769 Value *LoBit = Builder.CreateTrunc(Shifted,
4770 Type::getInt1Ty(Mod.getContext()),
4772 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4774 Builder.SetInsertPoint(LookupBB);
4775 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4778 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4779 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4780 // do not delete PHINodes here.
4781 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4782 /*DontDeleteUselessPHIs=*/true);
4785 bool ReturnedEarly = false;
4786 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4787 PHINode *PHI = PHIs[I];
4788 const ResultListTy &ResultList = ResultLists[PHI];
4790 // If using a bitmask, use any value to fill the lookup table holes.
4791 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4792 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4794 Value *Result = Table.BuildLookup(TableIndex, Builder);
4796 // If the result is used to return immediately from the function, we want to
4797 // do that right here.
4798 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4799 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4800 Builder.CreateRet(Result);
4801 ReturnedEarly = true;
4805 // Do a small peephole optimization: re-use the switch table compare if
4807 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4808 BasicBlock *PhiBlock = PHI->getParent();
4809 // Search for compare instructions which use the phi.
4810 for (auto *User : PHI->users()) {
4811 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4815 PHI->addIncoming(Result, LookupBB);
4819 Builder.CreateBr(CommonDest);
4821 // Remove the switch.
4822 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4823 BasicBlock *Succ = SI->getSuccessor(i);
4825 if (Succ == SI->getDefaultDest())
4827 Succ->removePredecessor(SI->getParent());
4829 SI->eraseFromParent();
4833 ++NumLookupTablesHoles;
4837 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4838 BasicBlock *BB = SI->getParent();
4840 if (isValueEqualityComparison(SI)) {
4841 // If we only have one predecessor, and if it is a branch on this value,
4842 // see if that predecessor totally determines the outcome of this switch.
4843 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4844 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4845 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4847 Value *Cond = SI->getCondition();
4848 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4849 if (SimplifySwitchOnSelect(SI, Select))
4850 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4852 // If the block only contains the switch, see if we can fold the block
4853 // away into any preds.
4854 BasicBlock::iterator BBI = BB->begin();
4855 // Ignore dbg intrinsics.
4856 while (isa<DbgInfoIntrinsic>(BBI))
4859 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4860 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4863 // Try to transform the switch into an icmp and a branch.
4864 if (TurnSwitchRangeIntoICmp(SI, Builder))
4865 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4867 // Remove unreachable cases.
4868 if (EliminateDeadSwitchCases(SI, AC, DL))
4869 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4871 if (SwitchToSelect(SI, Builder, AC, DL))
4872 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4874 if (ForwardSwitchConditionToPHI(SI))
4875 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4877 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4878 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4883 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4884 BasicBlock *BB = IBI->getParent();
4885 bool Changed = false;
4887 // Eliminate redundant destinations.
4888 SmallPtrSet<Value *, 8> Succs;
4889 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4890 BasicBlock *Dest = IBI->getDestination(i);
4891 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4892 Dest->removePredecessor(BB);
4893 IBI->removeDestination(i);
4899 if (IBI->getNumDestinations() == 0) {
4900 // If the indirectbr has no successors, change it to unreachable.
4901 new UnreachableInst(IBI->getContext(), IBI);
4902 EraseTerminatorInstAndDCECond(IBI);
4906 if (IBI->getNumDestinations() == 1) {
4907 // If the indirectbr has one successor, change it to a direct branch.
4908 BranchInst::Create(IBI->getDestination(0), IBI);
4909 EraseTerminatorInstAndDCECond(IBI);
4913 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4914 if (SimplifyIndirectBrOnSelect(IBI, SI))
4915 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4920 /// Given an block with only a single landing pad and a unconditional branch
4921 /// try to find another basic block which this one can be merged with. This
4922 /// handles cases where we have multiple invokes with unique landing pads, but
4923 /// a shared handler.
4925 /// We specifically choose to not worry about merging non-empty blocks
4926 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4927 /// practice, the optimizer produces empty landing pad blocks quite frequently
4928 /// when dealing with exception dense code. (see: instcombine, gvn, if-else
4929 /// sinking in this file)
4931 /// This is primarily a code size optimization. We need to avoid performing
4932 /// any transform which might inhibit optimization (such as our ability to
4933 /// specialize a particular handler via tail commoning). We do this by not
4934 /// merging any blocks which require us to introduce a phi. Since the same
4935 /// values are flowing through both blocks, we don't loose any ability to
4936 /// specialize. If anything, we make such specialization more likely.
4938 /// TODO - This transformation could remove entries from a phi in the target
4939 /// block when the inputs in the phi are the same for the two blocks being
4940 /// merged. In some cases, this could result in removal of the PHI entirely.
4941 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4943 auto Succ = BB->getUniqueSuccessor();
4945 // If there's a phi in the successor block, we'd likely have to introduce
4946 // a phi into the merged landing pad block.
4947 if (isa<PHINode>(*Succ->begin()))
4950 for (BasicBlock *OtherPred : predecessors(Succ)) {
4951 if (BB == OtherPred)
4953 BasicBlock::iterator I = OtherPred->begin();
4954 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4955 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4957 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4958 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4959 if (!BI2 || !BI2->isIdenticalTo(BI))
4962 // We've found an identical block. Update our predeccessors to take that
4963 // path instead and make ourselves dead.
4964 SmallSet<BasicBlock *, 16> Preds;
4965 Preds.insert(pred_begin(BB), pred_end(BB));
4966 for (BasicBlock *Pred : Preds) {
4967 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4968 assert(II->getNormalDest() != BB &&
4969 II->getUnwindDest() == BB && "unexpected successor");
4970 II->setUnwindDest(OtherPred);
4973 // The debug info in OtherPred doesn't cover the merged control flow that
4974 // used to go through BB. We need to delete it or update it.
4975 for (auto I = OtherPred->begin(), E = OtherPred->end();
4977 Instruction &Inst = *I; I++;
4978 if (isa<DbgInfoIntrinsic>(Inst))
4979 Inst.eraseFromParent();
4982 SmallSet<BasicBlock *, 16> Succs;
4983 Succs.insert(succ_begin(BB), succ_end(BB));
4984 for (BasicBlock *Succ : Succs) {
4985 Succ->removePredecessor(BB);
4988 IRBuilder<> Builder(BI);
4989 Builder.CreateUnreachable();
4990 BI->eraseFromParent();
4996 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4997 BasicBlock *BB = BI->getParent();
4999 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5002 // If the Terminator is the only non-phi instruction, simplify the block.
5003 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5004 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5005 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5008 // If the only instruction in the block is a seteq/setne comparison
5009 // against a constant, try to simplify the block.
5010 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5011 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5012 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5014 if (I->isTerminator() &&
5015 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5016 BonusInstThreshold, AC))
5020 // See if we can merge an empty landing pad block with another which is
5022 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5023 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5024 if (I->isTerminator() &&
5025 TryToMergeLandingPad(LPad, BI, BB))
5029 // If this basic block is ONLY a compare and a branch, and if a predecessor
5030 // branches to us and our successor, fold the comparison into the
5031 // predecessor and use logical operations to update the incoming value
5032 // for PHI nodes in common successor.
5033 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5034 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5038 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5039 BasicBlock *PredPred = nullptr;
5040 for (auto *P : predecessors(BB)) {
5041 BasicBlock *PPred = P->getSinglePredecessor();
5042 if (!PPred || (PredPred && PredPred != PPred))
5049 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5050 BasicBlock *BB = BI->getParent();
5052 // Conditional branch
5053 if (isValueEqualityComparison(BI)) {
5054 // If we only have one predecessor, and if it is a branch on this value,
5055 // see if that predecessor totally determines the outcome of this
5057 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5058 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5059 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5061 // This block must be empty, except for the setcond inst, if it exists.
5062 // Ignore dbg intrinsics.
5063 BasicBlock::iterator I = BB->begin();
5064 // Ignore dbg intrinsics.
5065 while (isa<DbgInfoIntrinsic>(I))
5068 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5069 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5070 } else if (&*I == cast<Instruction>(BI->getCondition())){
5072 // Ignore dbg intrinsics.
5073 while (isa<DbgInfoIntrinsic>(I))
5075 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5076 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5080 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5081 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5084 // If this basic block is ONLY a compare and a branch, and if a predecessor
5085 // branches to us and one of our successors, fold the comparison into the
5086 // predecessor and use logical operations to pick the right destination.
5087 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5088 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5090 // We have a conditional branch to two blocks that are only reachable
5091 // from BI. We know that the condbr dominates the two blocks, so see if
5092 // there is any identical code in the "then" and "else" blocks. If so, we
5093 // can hoist it up to the branching block.
5094 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5095 if (BI->getSuccessor(1)->getSinglePredecessor()) {
5096 if (HoistThenElseCodeToIf(BI, TTI))
5097 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5099 // If Successor #1 has multiple preds, we may be able to conditionally
5100 // execute Successor #0 if it branches to Successor #1.
5101 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5102 if (Succ0TI->getNumSuccessors() == 1 &&
5103 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5104 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5105 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5107 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
5108 // If Successor #0 has multiple preds, we may be able to conditionally
5109 // execute Successor #1 if it branches to Successor #0.
5110 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5111 if (Succ1TI->getNumSuccessors() == 1 &&
5112 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
5113 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5114 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5117 // If this is a branch on a phi node in the current block, thread control
5118 // through this block if any PHI node entries are constants.
5119 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5120 if (PN->getParent() == BI->getParent())
5121 if (FoldCondBranchOnPHI(BI, DL))
5122 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5124 // Scan predecessor blocks for conditional branches.
5125 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5126 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5127 if (PBI != BI && PBI->isConditional())
5128 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
5129 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5131 // Look for diamond patterns.
5132 if (MergeCondStores)
5133 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5134 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5135 if (PBI != BI && PBI->isConditional())
5136 if (mergeConditionalStores(PBI, BI))
5137 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5142 /// Check if passing a value to an instruction will cause undefined behavior.
5143 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5144 Constant *C = dyn_cast<Constant>(V);
5151 if (C->isNullValue()) {
5152 // Only look at the first use, avoid hurting compile time with long uselists
5153 User *Use = *I->user_begin();
5155 // Now make sure that there are no instructions in between that can alter
5156 // control flow (eg. calls)
5157 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
5158 if (i == I->getParent()->end() || i->mayHaveSideEffects())
5161 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5162 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5163 if (GEP->getPointerOperand() == I)
5164 return passingValueIsAlwaysUndefined(V, GEP);
5166 // Look through bitcasts.
5167 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5168 return passingValueIsAlwaysUndefined(V, BC);
5170 // Load from null is undefined.
5171 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
5172 if (!LI->isVolatile())
5173 return LI->getPointerAddressSpace() == 0;
5175 // Store to null is undefined.
5176 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
5177 if (!SI->isVolatile())
5178 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
5183 /// If BB has an incoming value that will always trigger undefined behavior
5184 /// (eg. null pointer dereference), remove the branch leading here.
5185 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5186 for (BasicBlock::iterator i = BB->begin();
5187 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5188 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5189 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5190 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5191 IRBuilder<> Builder(T);
5192 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5193 BB->removePredecessor(PHI->getIncomingBlock(i));
5194 // Turn uncoditional branches into unreachables and remove the dead
5195 // destination from conditional branches.
5196 if (BI->isUnconditional())
5197 Builder.CreateUnreachable();
5199 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5200 BI->getSuccessor(0));
5201 BI->eraseFromParent();
5204 // TODO: SwitchInst.
5210 bool SimplifyCFGOpt::run(BasicBlock *BB) {
5211 bool Changed = false;
5213 assert(BB && BB->getParent() && "Block not embedded in function!");
5214 assert(BB->getTerminator() && "Degenerate basic block encountered!");
5216 // Remove basic blocks that have no predecessors (except the entry block)...
5217 // or that just have themself as a predecessor. These are unreachable.
5218 if ((pred_empty(BB) &&
5219 BB != &BB->getParent()->getEntryBlock()) ||
5220 BB->getSinglePredecessor() == BB) {
5221 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5222 DeleteDeadBlock(BB);
5226 // Check to see if we can constant propagate this terminator instruction
5228 Changed |= ConstantFoldTerminator(BB, true);
5230 // Check for and eliminate duplicate PHI nodes in this block.
5231 Changed |= EliminateDuplicatePHINodes(BB);
5233 // Check for and remove branches that will always cause undefined behavior.
5234 Changed |= removeUndefIntroducingPredecessor(BB);
5236 // Merge basic blocks into their predecessor if there is only one distinct
5237 // pred, and if there is only one distinct successor of the predecessor, and
5238 // if there are no PHI nodes.
5240 if (MergeBlockIntoPredecessor(BB))
5243 IRBuilder<> Builder(BB);
5245 // If there is a trivial two-entry PHI node in this basic block, and we can
5246 // eliminate it, do so now.
5247 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5248 if (PN->getNumIncomingValues() == 2)
5249 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
5251 Builder.SetInsertPoint(BB->getTerminator());
5252 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
5253 if (BI->isUnconditional()) {
5254 if (SimplifyUncondBranch(BI, Builder)) return true;
5256 if (SimplifyCondBranch(BI, Builder)) return true;
5258 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
5259 if (SimplifyReturn(RI, Builder)) return true;
5260 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5261 if (SimplifyResume(RI, Builder)) return true;
5262 } else if (CleanupReturnInst *RI =
5263 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5264 if (SimplifyCleanupReturn(RI)) return true;
5265 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
5266 if (SimplifySwitch(SI, Builder)) return true;
5267 } else if (UnreachableInst *UI =
5268 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5269 if (SimplifyUnreachable(UI)) return true;
5270 } else if (IndirectBrInst *IBI =
5271 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5272 if (SimplifyIndirectBr(IBI)) return true;
5278 /// This function is used to do simplification of a CFG.
5279 /// For example, it adjusts branches to branches to eliminate the extra hop,
5280 /// eliminates unreachable basic blocks, and does other "peephole" optimization
5281 /// of the CFG. It returns true if a modification was made.
5283 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
5284 unsigned BonusInstThreshold, AssumptionCache *AC) {
5285 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5286 BonusInstThreshold, AC).run(BB);