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/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
52 using namespace PatternMatch;
54 #define DEBUG_TYPE "simplifycfg"
56 // Chosen as 2 so as to be cheap, but still to have enough power to fold
57 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58 // To catch this, we need to fold a compare and a select, hence '2' being the
59 // minimum reasonable default.
60 static cl::opt<unsigned>
61 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
65 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
69 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
72 static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
76 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
77 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
78 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
79 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
80 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
81 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
82 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
85 // The first field contains the value that the switch produces when a certain
86 // case group is selected, and the second field is a vector containing the cases
87 // composing the case group.
88 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
89 SwitchCaseResultVectorTy;
90 // The first field contains the phi node that generates a result of the switch
91 // and the second field contains the value generated for a certain case in the switch
93 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
95 /// ValueEqualityComparisonCase - Represents a case of a switch.
96 struct ValueEqualityComparisonCase {
100 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
101 : Value(Value), Dest(Dest) {}
103 bool operator<(ValueEqualityComparisonCase RHS) const {
104 // Comparing pointers is ok as we only rely on the order for uniquing.
105 return Value < RHS.Value;
108 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
111 class SimplifyCFGOpt {
112 const TargetTransformInfo &TTI;
113 const DataLayout &DL;
114 unsigned BonusInstThreshold;
116 Value *isValueEqualityComparison(TerminatorInst *TI);
117 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
118 std::vector<ValueEqualityComparisonCase> &Cases);
119 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
121 IRBuilder<> &Builder);
122 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
123 IRBuilder<> &Builder);
125 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
126 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
127 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
128 bool SimplifyUnreachable(UnreachableInst *UI);
129 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
130 bool SimplifyIndirectBr(IndirectBrInst *IBI);
131 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
132 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
135 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
136 unsigned BonusInstThreshold, AssumptionCache *AC)
137 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
138 bool run(BasicBlock *BB);
142 /// Return true if it is safe to merge these two
143 /// terminator instructions together.
144 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
145 if (SI1 == SI2) return false; // Can't merge with self!
147 // It is not safe to merge these two switch instructions if they have a common
148 // successor, and if that successor has a PHI node, and if *that* PHI node has
149 // conflicting incoming values from the two switch blocks.
150 BasicBlock *SI1BB = SI1->getParent();
151 BasicBlock *SI2BB = SI2->getParent();
152 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
154 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
155 if (SI1Succs.count(*I))
156 for (BasicBlock::iterator BBI = (*I)->begin();
157 isa<PHINode>(BBI); ++BBI) {
158 PHINode *PN = cast<PHINode>(BBI);
159 if (PN->getIncomingValueForBlock(SI1BB) !=
160 PN->getIncomingValueForBlock(SI2BB))
167 /// Return true if it is safe and profitable to merge these two terminator
168 /// instructions together, where SI1 is an unconditional branch. PhiNodes will
169 /// store all PHI nodes in common successors.
170 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
173 SmallVectorImpl<PHINode*> &PhiNodes) {
174 if (SI1 == SI2) return false; // Can't merge with self!
175 assert(SI1->isUnconditional() && SI2->isConditional());
177 // We fold the unconditional branch if we can easily update all PHI nodes in
178 // common successors:
179 // 1> We have a constant incoming value for the conditional branch;
180 // 2> We have "Cond" as the incoming value for the unconditional branch;
181 // 3> SI2->getCondition() and Cond have same operands.
182 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
183 if (!Ci2) return false;
184 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
185 Cond->getOperand(1) == Ci2->getOperand(1)) &&
186 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
187 Cond->getOperand(1) == Ci2->getOperand(0)))
190 BasicBlock *SI1BB = SI1->getParent();
191 BasicBlock *SI2BB = SI2->getParent();
192 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
193 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
194 if (SI1Succs.count(*I))
195 for (BasicBlock::iterator BBI = (*I)->begin();
196 isa<PHINode>(BBI); ++BBI) {
197 PHINode *PN = cast<PHINode>(BBI);
198 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
199 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
201 PhiNodes.push_back(PN);
206 /// Update PHI nodes in Succ to indicate that there will now be entries in it
207 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
208 /// will be the same as those coming in from ExistPred, an existing predecessor
210 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
211 BasicBlock *ExistPred) {
212 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
215 for (BasicBlock::iterator I = Succ->begin();
216 (PN = dyn_cast<PHINode>(I)); ++I)
217 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
220 /// Compute an abstract "cost" of speculating the given instruction,
221 /// which is assumed to be safe to speculate. TCC_Free means cheap,
222 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
224 static unsigned ComputeSpeculationCost(const User *I,
225 const TargetTransformInfo &TTI) {
226 assert(isSafeToSpeculativelyExecute(I) &&
227 "Instruction is not safe to speculatively execute!");
228 return TTI.getUserCost(I);
230 /// If we have a merge point of an "if condition" as accepted above,
231 /// return true if the specified value dominates the block. We
232 /// don't handle the true generality of domination here, just a special case
233 /// which works well enough for us.
235 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
236 /// see if V (which must be an instruction) and its recursive operands
237 /// that do not dominate BB have a combined cost lower than CostRemaining and
238 /// are non-trapping. If both are true, the instruction is inserted into the
239 /// set and true is returned.
241 /// The cost for most non-trapping instructions is defined as 1 except for
242 /// Select whose cost is 2.
244 /// After this function returns, CostRemaining is decreased by the cost of
245 /// V plus its non-dominating operands. If that cost is greater than
246 /// CostRemaining, false is returned and CostRemaining is undefined.
247 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
248 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
249 unsigned &CostRemaining,
250 const TargetTransformInfo &TTI) {
251 Instruction *I = dyn_cast<Instruction>(V);
253 // Non-instructions all dominate instructions, but not all constantexprs
254 // can be executed unconditionally.
255 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
260 BasicBlock *PBB = I->getParent();
262 // We don't want to allow weird loops that might have the "if condition" in
263 // the bottom of this block.
264 if (PBB == BB) return false;
266 // If this instruction is defined in a block that contains an unconditional
267 // branch to BB, then it must be in the 'conditional' part of the "if
268 // statement". If not, it definitely dominates the region.
269 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
270 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
273 // If we aren't allowing aggressive promotion anymore, then don't consider
274 // instructions in the 'if region'.
275 if (!AggressiveInsts) return false;
277 // If we have seen this instruction before, don't count it again.
278 if (AggressiveInsts->count(I)) return true;
280 // Okay, it looks like the instruction IS in the "condition". Check to
281 // see if it's a cheap instruction to unconditionally compute, and if it
282 // only uses stuff defined outside of the condition. If so, hoist it out.
283 if (!isSafeToSpeculativelyExecute(I))
286 unsigned Cost = ComputeSpeculationCost(I, TTI);
288 if (Cost > CostRemaining)
291 CostRemaining -= Cost;
293 // Okay, we can only really hoist these out if their operands do
294 // not take us over the cost threshold.
295 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
296 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
298 // Okay, it's safe to do this! Remember this instruction.
299 AggressiveInsts->insert(I);
303 /// Extract ConstantInt from value, looking through IntToPtr
304 /// and PointerNullValue. Return NULL if value is not a constant int.
305 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
306 // Normal constant int.
307 ConstantInt *CI = dyn_cast<ConstantInt>(V);
308 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
311 // This is some kind of pointer constant. Turn it into a pointer-sized
312 // ConstantInt if possible.
313 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
315 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
316 if (isa<ConstantPointerNull>(V))
317 return ConstantInt::get(PtrTy, 0);
319 // IntToPtr const int.
320 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
321 if (CE->getOpcode() == Instruction::IntToPtr)
322 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
323 // The constant is very likely to have the right type already.
324 if (CI->getType() == PtrTy)
327 return cast<ConstantInt>
328 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
335 /// Given a chain of or (||) or and (&&) comparison of a value against a
336 /// constant, this will try to recover the information required for a switch
338 /// It will depth-first traverse the chain of comparison, seeking for patterns
339 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
340 /// representing the different cases for the switch.
341 /// Note that if the chain is composed of '||' it will build the set of elements
342 /// that matches the comparisons (i.e. any of this value validate the chain)
343 /// while for a chain of '&&' it will build the set elements that make the test
345 struct ConstantComparesGatherer {
346 const DataLayout &DL;
347 Value *CompValue; /// Value found for the switch comparison
348 Value *Extra; /// Extra clause to be checked before the switch
349 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
350 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
352 /// Construct and compute the result for the comparison instruction Cond
353 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
354 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
359 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
360 ConstantComparesGatherer &
361 operator=(const ConstantComparesGatherer &) = delete;
365 /// Try to set the current value used for the comparison, it succeeds only if
366 /// it wasn't set before or if the new value is the same as the old one
367 bool setValueOnce(Value *NewVal) {
368 if(CompValue && CompValue != NewVal) return false;
370 return (CompValue != nullptr);
373 /// Try to match Instruction "I" as a comparison against a constant and
374 /// populates the array Vals with the set of values that match (or do not
375 /// match depending on isEQ).
376 /// Return false on failure. On success, the Value the comparison matched
377 /// against is placed in CompValue.
378 /// If CompValue is already set, the function is expected to fail if a match
379 /// is found but the value compared to is different.
380 bool matchInstruction(Instruction *I, bool isEQ) {
381 // If this is an icmp against a constant, handle this as one of the cases.
384 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
385 (C = GetConstantInt(I->getOperand(1), DL)))) {
392 // Pattern match a special case
393 // (x & ~2^x) == y --> x == y || x == y|2^x
394 // This undoes a transformation done by instcombine to fuse 2 compares.
395 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
396 if (match(ICI->getOperand(0),
397 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
398 APInt Not = ~RHSC->getValue();
399 if (Not.isPowerOf2()) {
400 // If we already have a value for the switch, it has to match!
401 if(!setValueOnce(RHSVal))
405 Vals.push_back(ConstantInt::get(C->getContext(),
406 C->getValue() | Not));
412 // If we already have a value for the switch, it has to match!
413 if(!setValueOnce(ICI->getOperand(0)))
418 return ICI->getOperand(0);
421 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
422 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
423 ICI->getPredicate(), C->getValue());
425 // Shift the range if the compare is fed by an add. This is the range
426 // compare idiom as emitted by instcombine.
427 Value *CandidateVal = I->getOperand(0);
428 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
429 Span = Span.subtract(RHSC->getValue());
430 CandidateVal = RHSVal;
433 // If this is an and/!= check, then we are looking to build the set of
434 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
437 Span = Span.inverse();
439 // If there are a ton of values, we don't want to make a ginormous switch.
440 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
444 // If we already have a value for the switch, it has to match!
445 if(!setValueOnce(CandidateVal))
448 // Add all values from the range to the set
449 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
450 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
457 /// Given a potentially 'or'd or 'and'd together collection of icmp
458 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
459 /// the value being compared, and stick the list constants into the Vals
461 /// One "Extra" case is allowed to differ from the other.
462 void gather(Value *V) {
463 Instruction *I = dyn_cast<Instruction>(V);
464 bool isEQ = (I->getOpcode() == Instruction::Or);
466 // Keep a stack (SmallVector for efficiency) for depth-first traversal
467 SmallVector<Value *, 8> DFT;
472 while(!DFT.empty()) {
473 V = DFT.pop_back_val();
475 if (Instruction *I = dyn_cast<Instruction>(V)) {
476 // If it is a || (or && depending on isEQ), process the operands.
477 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
478 DFT.push_back(I->getOperand(1));
479 DFT.push_back(I->getOperand(0));
483 // Try to match the current instruction
484 if (matchInstruction(I, isEQ))
485 // Match succeed, continue the loop
489 // One element of the sequence of || (or &&) could not be match as a
490 // comparison against the same value as the others.
491 // We allow only one "Extra" case to be checked before the switch
496 // Failed to parse a proper sequence, abort now
505 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
506 Instruction *Cond = nullptr;
507 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
508 Cond = dyn_cast<Instruction>(SI->getCondition());
509 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
510 if (BI->isConditional())
511 Cond = dyn_cast<Instruction>(BI->getCondition());
512 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
513 Cond = dyn_cast<Instruction>(IBI->getAddress());
516 TI->eraseFromParent();
517 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
520 /// Return true if the specified terminator checks
521 /// to see if a value is equal to constant integer value.
522 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
524 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
525 // Do not permit merging of large switch instructions into their
526 // predecessors unless there is only one predecessor.
527 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
528 pred_end(SI->getParent())) <= 128)
529 CV = SI->getCondition();
530 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
531 if (BI->isConditional() && BI->getCondition()->hasOneUse())
532 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
533 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
534 CV = ICI->getOperand(0);
537 // Unwrap any lossless ptrtoint cast.
539 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
540 Value *Ptr = PTII->getPointerOperand();
541 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
548 /// Given a value comparison instruction,
549 /// decode all of the 'cases' that it represents and return the 'default' block.
550 BasicBlock *SimplifyCFGOpt::
551 GetValueEqualityComparisonCases(TerminatorInst *TI,
552 std::vector<ValueEqualityComparisonCase>
554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 Cases.reserve(SI->getNumCases());
556 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
557 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
558 i.getCaseSuccessor()));
559 return SI->getDefaultDest();
562 BranchInst *BI = cast<BranchInst>(TI);
563 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
564 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
565 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
568 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
572 /// Given a vector of bb/value pairs, remove any entries
573 /// in the list that match the specified block.
574 static void EliminateBlockCases(BasicBlock *BB,
575 std::vector<ValueEqualityComparisonCase> &Cases) {
576 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
579 /// Return true if there are any keys in C1 that exist in C2 as well.
581 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
582 std::vector<ValueEqualityComparisonCase > &C2) {
583 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
585 // Make V1 be smaller than V2.
586 if (V1->size() > V2->size())
589 if (V1->size() == 0) return false;
590 if (V1->size() == 1) {
592 ConstantInt *TheVal = (*V1)[0].Value;
593 for (unsigned i = 0, e = V2->size(); i != e; ++i)
594 if (TheVal == (*V2)[i].Value)
598 // Otherwise, just sort both lists and compare element by element.
599 array_pod_sort(V1->begin(), V1->end());
600 array_pod_sort(V2->begin(), V2->end());
601 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
602 while (i1 != e1 && i2 != e2) {
603 if ((*V1)[i1].Value == (*V2)[i2].Value)
605 if ((*V1)[i1].Value < (*V2)[i2].Value)
613 /// If TI is known to be a terminator instruction and its block is known to
614 /// only have a single predecessor block, check to see if that predecessor is
615 /// also a value comparison with the same value, and if that comparison
616 /// determines the outcome of this comparison. If so, simplify TI. This does a
617 /// very limited form of jump threading.
618 bool SimplifyCFGOpt::
619 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
621 IRBuilder<> &Builder) {
622 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
623 if (!PredVal) return false; // Not a value comparison in predecessor.
625 Value *ThisVal = isValueEqualityComparison(TI);
626 assert(ThisVal && "This isn't a value comparison!!");
627 if (ThisVal != PredVal) return false; // Different predicates.
629 // TODO: Preserve branch weight metadata, similarly to how
630 // FoldValueComparisonIntoPredecessors preserves it.
632 // Find out information about when control will move from Pred to TI's block.
633 std::vector<ValueEqualityComparisonCase> PredCases;
634 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
636 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
638 // Find information about how control leaves this block.
639 std::vector<ValueEqualityComparisonCase> ThisCases;
640 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
641 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
643 // If TI's block is the default block from Pred's comparison, potentially
644 // simplify TI based on this knowledge.
645 if (PredDef == TI->getParent()) {
646 // If we are here, we know that the value is none of those cases listed in
647 // PredCases. If there are any cases in ThisCases that are in PredCases, we
649 if (!ValuesOverlap(PredCases, ThisCases))
652 if (isa<BranchInst>(TI)) {
653 // Okay, one of the successors of this condbr is dead. Convert it to a
655 assert(ThisCases.size() == 1 && "Branch can only have one case!");
656 // Insert the new branch.
657 Instruction *NI = Builder.CreateBr(ThisDef);
660 // Remove PHI node entries for the dead edge.
661 ThisCases[0].Dest->removePredecessor(TI->getParent());
663 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
664 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
666 EraseTerminatorInstAndDCECond(TI);
670 SwitchInst *SI = cast<SwitchInst>(TI);
671 // Okay, TI has cases that are statically dead, prune them away.
672 SmallPtrSet<Constant*, 16> DeadCases;
673 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
674 DeadCases.insert(PredCases[i].Value);
676 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
677 << "Through successor TI: " << *TI);
679 // Collect branch weights into a vector.
680 SmallVector<uint32_t, 8> Weights;
681 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
682 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
684 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
686 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
687 Weights.push_back(CI->getValue().getZExtValue());
689 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
691 if (DeadCases.count(i.getCaseValue())) {
693 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
696 i.getCaseSuccessor()->removePredecessor(TI->getParent());
700 if (HasWeight && Weights.size() >= 2)
701 SI->setMetadata(LLVMContext::MD_prof,
702 MDBuilder(SI->getParent()->getContext()).
703 createBranchWeights(Weights));
705 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
709 // Otherwise, TI's block must correspond to some matched value. Find out
710 // which value (or set of values) this is.
711 ConstantInt *TIV = nullptr;
712 BasicBlock *TIBB = TI->getParent();
713 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
714 if (PredCases[i].Dest == TIBB) {
716 return false; // Cannot handle multiple values coming to this block.
717 TIV = PredCases[i].Value;
719 assert(TIV && "No edge from pred to succ?");
721 // Okay, we found the one constant that our value can be if we get into TI's
722 // BB. Find out which successor will unconditionally be branched to.
723 BasicBlock *TheRealDest = nullptr;
724 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
725 if (ThisCases[i].Value == TIV) {
726 TheRealDest = ThisCases[i].Dest;
730 // If not handled by any explicit cases, it is handled by the default case.
731 if (!TheRealDest) TheRealDest = ThisDef;
733 // Remove PHI node entries for dead edges.
734 BasicBlock *CheckEdge = TheRealDest;
735 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
736 if (*SI != CheckEdge)
737 (*SI)->removePredecessor(TIBB);
741 // Insert the new branch.
742 Instruction *NI = Builder.CreateBr(TheRealDest);
745 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
746 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
748 EraseTerminatorInstAndDCECond(TI);
753 /// This class implements a stable ordering of constant
754 /// integers that does not depend on their address. This is important for
755 /// applications that sort ConstantInt's to ensure uniqueness.
756 struct ConstantIntOrdering {
757 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
758 return LHS->getValue().ult(RHS->getValue());
763 static int ConstantIntSortPredicate(ConstantInt *const *P1,
764 ConstantInt *const *P2) {
765 const ConstantInt *LHS = *P1;
766 const ConstantInt *RHS = *P2;
767 if (LHS->getValue().ult(RHS->getValue()))
769 if (LHS->getValue() == RHS->getValue())
774 static inline bool HasBranchWeights(const Instruction* I) {
775 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
776 if (ProfMD && ProfMD->getOperand(0))
777 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
778 return MDS->getString().equals("branch_weights");
783 /// Get Weights of a given TerminatorInst, the default weight is at the front
784 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
786 static void GetBranchWeights(TerminatorInst *TI,
787 SmallVectorImpl<uint64_t> &Weights) {
788 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
790 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
791 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
792 Weights.push_back(CI->getValue().getZExtValue());
795 // If TI is a conditional eq, the default case is the false case,
796 // and the corresponding branch-weight data is at index 2. We swap the
797 // default weight to be the first entry.
798 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
799 assert(Weights.size() == 2);
800 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
801 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
802 std::swap(Weights.front(), Weights.back());
806 /// Keep halving the weights until all can fit in uint32_t.
807 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
808 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
809 if (Max > UINT_MAX) {
810 unsigned Offset = 32 - countLeadingZeros(Max);
811 for (uint64_t &I : Weights)
816 /// The specified terminator is a value equality comparison instruction
817 /// (either a switch or a branch on "X == c").
818 /// See if any of the predecessors of the terminator block are value comparisons
819 /// on the same value. If so, and if safe to do so, fold them together.
820 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
821 IRBuilder<> &Builder) {
822 BasicBlock *BB = TI->getParent();
823 Value *CV = isValueEqualityComparison(TI); // CondVal
824 assert(CV && "Not a comparison?");
825 bool Changed = false;
827 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
828 while (!Preds.empty()) {
829 BasicBlock *Pred = Preds.pop_back_val();
831 // See if the predecessor is a comparison with the same value.
832 TerminatorInst *PTI = Pred->getTerminator();
833 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
835 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
836 // Figure out which 'cases' to copy from SI to PSI.
837 std::vector<ValueEqualityComparisonCase> BBCases;
838 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
840 std::vector<ValueEqualityComparisonCase> PredCases;
841 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
843 // Based on whether the default edge from PTI goes to BB or not, fill in
844 // PredCases and PredDefault with the new switch cases we would like to
846 SmallVector<BasicBlock*, 8> NewSuccessors;
848 // Update the branch weight metadata along the way
849 SmallVector<uint64_t, 8> Weights;
850 bool PredHasWeights = HasBranchWeights(PTI);
851 bool SuccHasWeights = HasBranchWeights(TI);
853 if (PredHasWeights) {
854 GetBranchWeights(PTI, Weights);
855 // branch-weight metadata is inconsistent here.
856 if (Weights.size() != 1 + PredCases.size())
857 PredHasWeights = SuccHasWeights = false;
858 } else if (SuccHasWeights)
859 // If there are no predecessor weights but there are successor weights,
860 // populate Weights with 1, which will later be scaled to the sum of
861 // successor's weights
862 Weights.assign(1 + PredCases.size(), 1);
864 SmallVector<uint64_t, 8> SuccWeights;
865 if (SuccHasWeights) {
866 GetBranchWeights(TI, SuccWeights);
867 // branch-weight metadata is inconsistent here.
868 if (SuccWeights.size() != 1 + BBCases.size())
869 PredHasWeights = SuccHasWeights = false;
870 } else if (PredHasWeights)
871 SuccWeights.assign(1 + BBCases.size(), 1);
873 if (PredDefault == BB) {
874 // If this is the default destination from PTI, only the edges in TI
875 // that don't occur in PTI, or that branch to BB will be activated.
876 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
877 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
878 if (PredCases[i].Dest != BB)
879 PTIHandled.insert(PredCases[i].Value);
881 // The default destination is BB, we don't need explicit targets.
882 std::swap(PredCases[i], PredCases.back());
884 if (PredHasWeights || SuccHasWeights) {
885 // Increase weight for the default case.
886 Weights[0] += Weights[i+1];
887 std::swap(Weights[i+1], Weights.back());
891 PredCases.pop_back();
895 // Reconstruct the new switch statement we will be building.
896 if (PredDefault != BBDefault) {
897 PredDefault->removePredecessor(Pred);
898 PredDefault = BBDefault;
899 NewSuccessors.push_back(BBDefault);
902 unsigned CasesFromPred = Weights.size();
903 uint64_t ValidTotalSuccWeight = 0;
904 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
905 if (!PTIHandled.count(BBCases[i].Value) &&
906 BBCases[i].Dest != BBDefault) {
907 PredCases.push_back(BBCases[i]);
908 NewSuccessors.push_back(BBCases[i].Dest);
909 if (SuccHasWeights || PredHasWeights) {
910 // The default weight is at index 0, so weight for the ith case
911 // should be at index i+1. Scale the cases from successor by
912 // PredDefaultWeight (Weights[0]).
913 Weights.push_back(Weights[0] * SuccWeights[i+1]);
914 ValidTotalSuccWeight += SuccWeights[i+1];
918 if (SuccHasWeights || PredHasWeights) {
919 ValidTotalSuccWeight += SuccWeights[0];
920 // Scale the cases from predecessor by ValidTotalSuccWeight.
921 for (unsigned i = 1; i < CasesFromPred; ++i)
922 Weights[i] *= ValidTotalSuccWeight;
923 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
924 Weights[0] *= SuccWeights[0];
927 // If this is not the default destination from PSI, only the edges
928 // in SI that occur in PSI with a destination of BB will be
930 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
931 std::map<ConstantInt*, uint64_t> WeightsForHandled;
932 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
933 if (PredCases[i].Dest == BB) {
934 PTIHandled.insert(PredCases[i].Value);
936 if (PredHasWeights || SuccHasWeights) {
937 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
938 std::swap(Weights[i+1], Weights.back());
942 std::swap(PredCases[i], PredCases.back());
943 PredCases.pop_back();
947 // Okay, now we know which constants were sent to BB from the
948 // predecessor. Figure out where they will all go now.
949 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
950 if (PTIHandled.count(BBCases[i].Value)) {
951 // If this is one we are capable of getting...
952 if (PredHasWeights || SuccHasWeights)
953 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
954 PredCases.push_back(BBCases[i]);
955 NewSuccessors.push_back(BBCases[i].Dest);
956 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
959 // If there are any constants vectored to BB that TI doesn't handle,
960 // they must go to the default destination of TI.
961 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
963 E = PTIHandled.end(); I != E; ++I) {
964 if (PredHasWeights || SuccHasWeights)
965 Weights.push_back(WeightsForHandled[*I]);
966 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
967 NewSuccessors.push_back(BBDefault);
971 // Okay, at this point, we know which new successor Pred will get. Make
972 // sure we update the number of entries in the PHI nodes for these
974 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
975 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
977 Builder.SetInsertPoint(PTI);
978 // Convert pointer to int before we switch.
979 if (CV->getType()->isPointerTy()) {
980 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
984 // Now that the successors are updated, create the new Switch instruction.
985 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
987 NewSI->setDebugLoc(PTI->getDebugLoc());
988 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
989 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
991 if (PredHasWeights || SuccHasWeights) {
992 // Halve the weights if any of them cannot fit in an uint32_t
995 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
997 NewSI->setMetadata(LLVMContext::MD_prof,
998 MDBuilder(BB->getContext()).
999 createBranchWeights(MDWeights));
1002 EraseTerminatorInstAndDCECond(PTI);
1004 // Okay, last check. If BB is still a successor of PSI, then we must
1005 // have an infinite loop case. If so, add an infinitely looping block
1006 // to handle the case to preserve the behavior of the code.
1007 BasicBlock *InfLoopBlock = nullptr;
1008 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1009 if (NewSI->getSuccessor(i) == BB) {
1010 if (!InfLoopBlock) {
1011 // Insert it at the end of the function, because it's either code,
1012 // or it won't matter if it's hot. :)
1013 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1014 "infloop", BB->getParent());
1015 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1017 NewSI->setSuccessor(i, InfLoopBlock);
1026 // If we would need to insert a select that uses the value of this invoke
1027 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1028 // can't hoist the invoke, as there is nowhere to put the select in this case.
1029 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1030 Instruction *I1, Instruction *I2) {
1031 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1033 for (BasicBlock::iterator BBI = SI->begin();
1034 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1035 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1036 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1037 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1045 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1047 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1048 /// in the two blocks up into the branch block. The caller of this function
1049 /// guarantees that BI's block dominates BB1 and BB2.
1050 static bool HoistThenElseCodeToIf(BranchInst *BI,
1051 const TargetTransformInfo &TTI) {
1052 // This does very trivial matching, with limited scanning, to find identical
1053 // instructions in the two blocks. In particular, we don't want to get into
1054 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1055 // such, we currently just scan for obviously identical instructions in an
1057 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1058 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1060 BasicBlock::iterator BB1_Itr = BB1->begin();
1061 BasicBlock::iterator BB2_Itr = BB2->begin();
1063 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1064 // Skip debug info if it is not identical.
1065 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1066 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1067 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1068 while (isa<DbgInfoIntrinsic>(I1))
1070 while (isa<DbgInfoIntrinsic>(I2))
1073 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1074 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1077 BasicBlock *BIParent = BI->getParent();
1079 bool Changed = false;
1081 // If we are hoisting the terminator instruction, don't move one (making a
1082 // broken BB), instead clone it, and remove BI.
1083 if (isa<TerminatorInst>(I1))
1084 goto HoistTerminator;
1086 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1089 // For a normal instruction, we just move one to right before the branch,
1090 // then replace all uses of the other with the first. Finally, we remove
1091 // the now redundant second instruction.
1092 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1093 if (!I2->use_empty())
1094 I2->replaceAllUsesWith(I1);
1095 I1->intersectOptionalDataWith(I2);
1096 unsigned KnownIDs[] = {
1097 LLVMContext::MD_tbaa,
1098 LLVMContext::MD_range,
1099 LLVMContext::MD_fpmath,
1100 LLVMContext::MD_invariant_load,
1101 LLVMContext::MD_nonnull
1103 combineMetadata(I1, I2, KnownIDs);
1104 I2->eraseFromParent();
1109 // Skip debug info if it is not identical.
1110 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1111 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1112 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1113 while (isa<DbgInfoIntrinsic>(I1))
1115 while (isa<DbgInfoIntrinsic>(I2))
1118 } while (I1->isIdenticalToWhenDefined(I2));
1123 // It may not be possible to hoist an invoke.
1124 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1127 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1129 for (BasicBlock::iterator BBI = SI->begin();
1130 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1131 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1132 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1136 // Check for passingValueIsAlwaysUndefined here because we would rather
1137 // eliminate undefined control flow then converting it to a select.
1138 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1139 passingValueIsAlwaysUndefined(BB2V, PN))
1142 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1144 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1149 // Okay, it is safe to hoist the terminator.
1150 Instruction *NT = I1->clone();
1151 BIParent->getInstList().insert(BI, NT);
1152 if (!NT->getType()->isVoidTy()) {
1153 I1->replaceAllUsesWith(NT);
1154 I2->replaceAllUsesWith(NT);
1158 IRBuilder<true, NoFolder> Builder(NT);
1159 // Hoisting one of the terminators from our successor is a great thing.
1160 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1161 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1162 // nodes, so we insert select instruction to compute the final result.
1163 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1164 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1166 for (BasicBlock::iterator BBI = SI->begin();
1167 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1168 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1169 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1170 if (BB1V == BB2V) continue;
1172 // These values do not agree. Insert a select instruction before NT
1173 // that determines the right value.
1174 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1176 SI = cast<SelectInst>
1177 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1178 BB1V->getName()+"."+BB2V->getName()));
1180 // Make the PHI node use the select for all incoming values for BB1/BB2
1181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1182 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1183 PN->setIncomingValue(i, SI);
1187 // Update any PHI nodes in our new successors.
1188 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1189 AddPredecessorToBlock(*SI, BIParent, BB1);
1191 EraseTerminatorInstAndDCECond(BI);
1195 /// Given an unconditional branch that goes to BBEnd,
1196 /// check whether BBEnd has only two predecessors and the other predecessor
1197 /// ends with an unconditional branch. If it is true, sink any common code
1198 /// in the two predecessors to BBEnd.
1199 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1200 assert(BI1->isUnconditional());
1201 BasicBlock *BB1 = BI1->getParent();
1202 BasicBlock *BBEnd = BI1->getSuccessor(0);
1204 // Check that BBEnd has two predecessors and the other predecessor ends with
1205 // an unconditional branch.
1206 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1207 BasicBlock *Pred0 = *PI++;
1208 if (PI == PE) // Only one predecessor.
1210 BasicBlock *Pred1 = *PI++;
1211 if (PI != PE) // More than two predecessors.
1213 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1214 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1215 if (!BI2 || !BI2->isUnconditional())
1218 // Gather the PHI nodes in BBEnd.
1219 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
1220 Instruction *FirstNonPhiInBBEnd = nullptr;
1221 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
1222 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1223 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1224 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1225 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
1227 FirstNonPhiInBBEnd = &*I;
1231 if (!FirstNonPhiInBBEnd)
1234 // This does very trivial matching, with limited scanning, to find identical
1235 // instructions in the two blocks. We scan backward for obviously identical
1236 // instructions in an identical order.
1237 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1238 RE1 = BB1->getInstList().rend(),
1239 RI2 = BB2->getInstList().rbegin(),
1240 RE2 = BB2->getInstList().rend();
1242 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1245 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1248 // Skip the unconditional branches.
1252 bool Changed = false;
1253 while (RI1 != RE1 && RI2 != RE2) {
1255 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1258 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1262 Instruction *I1 = &*RI1, *I2 = &*RI2;
1263 auto InstPair = std::make_pair(I1, I2);
1264 // I1 and I2 should have a single use in the same PHI node, and they
1265 // perform the same operation.
1266 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1267 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1268 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1269 I1->isEHPad() || I2->isEHPad() ||
1270 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1271 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1272 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1273 !I1->hasOneUse() || !I2->hasOneUse() ||
1274 !JointValueMap.count(InstPair))
1277 // Check whether we should swap the operands of ICmpInst.
1278 // TODO: Add support of communativity.
1279 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1280 bool SwapOpnds = false;
1281 if (ICmp1 && ICmp2 &&
1282 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1283 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1284 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1285 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1286 ICmp2->swapOperands();
1289 if (!I1->isSameOperationAs(I2)) {
1291 ICmp2->swapOperands();
1295 // The operands should be either the same or they need to be generated
1296 // with a PHI node after sinking. We only handle the case where there is
1297 // a single pair of different operands.
1298 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1299 unsigned Op1Idx = ~0U;
1300 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1301 if (I1->getOperand(I) == I2->getOperand(I))
1303 // Early exit if we have more-than one pair of different operands or if
1304 // we need a PHI node to replace a constant.
1305 if (Op1Idx != ~0U ||
1306 isa<Constant>(I1->getOperand(I)) ||
1307 isa<Constant>(I2->getOperand(I))) {
1308 // If we can't sink the instructions, undo the swapping.
1310 ICmp2->swapOperands();
1313 DifferentOp1 = I1->getOperand(I);
1315 DifferentOp2 = I2->getOperand(I);
1318 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1319 DEBUG(dbgs() << " " << *I2 << "\n");
1321 // We insert the pair of different operands to JointValueMap and
1322 // remove (I1, I2) from JointValueMap.
1323 if (Op1Idx != ~0U) {
1324 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1327 PHINode::Create(DifferentOp1->getType(), 2,
1328 DifferentOp1->getName() + ".sink", BBEnd->begin());
1329 NewPN->addIncoming(DifferentOp1, BB1);
1330 NewPN->addIncoming(DifferentOp2, BB2);
1331 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1333 // I1 should use NewPN instead of DifferentOp1.
1334 I1->setOperand(Op1Idx, NewPN);
1336 PHINode *OldPN = JointValueMap[InstPair];
1337 JointValueMap.erase(InstPair);
1339 // We need to update RE1 and RE2 if we are going to sink the first
1340 // instruction in the basic block down.
1341 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1342 // Sink the instruction.
1343 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1344 if (!OldPN->use_empty())
1345 OldPN->replaceAllUsesWith(I1);
1346 OldPN->eraseFromParent();
1348 if (!I2->use_empty())
1349 I2->replaceAllUsesWith(I1);
1350 I1->intersectOptionalDataWith(I2);
1351 // TODO: Use combineMetadata here to preserve what metadata we can
1352 // (analogous to the hoisting case above).
1353 I2->eraseFromParent();
1356 RE1 = BB1->getInstList().rend();
1358 RE2 = BB2->getInstList().rend();
1359 FirstNonPhiInBBEnd = I1;
1366 /// \brief Determine if we can hoist sink a sole store instruction out of a
1367 /// conditional block.
1369 /// We are looking for code like the following:
1371 /// store i32 %add, i32* %arrayidx2
1372 /// ... // No other stores or function calls (we could be calling a memory
1373 /// ... // function).
1374 /// %cmp = icmp ult %x, %y
1375 /// br i1 %cmp, label %EndBB, label %ThenBB
1377 /// store i32 %add5, i32* %arrayidx2
1381 /// We are going to transform this into:
1383 /// store i32 %add, i32* %arrayidx2
1385 /// %cmp = icmp ult %x, %y
1386 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1387 /// store i32 %add.add5, i32* %arrayidx2
1390 /// \return The pointer to the value of the previous store if the store can be
1391 /// hoisted into the predecessor block. 0 otherwise.
1392 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1393 BasicBlock *StoreBB, BasicBlock *EndBB) {
1394 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1398 // Volatile or atomic.
1399 if (!StoreToHoist->isSimple())
1402 Value *StorePtr = StoreToHoist->getPointerOperand();
1404 // Look for a store to the same pointer in BrBB.
1405 unsigned MaxNumInstToLookAt = 10;
1406 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1407 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1408 Instruction *CurI = &*RI;
1410 // Could be calling an instruction that effects memory like free().
1411 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1414 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1415 // Found the previous store make sure it stores to the same location.
1416 if (SI && SI->getPointerOperand() == StorePtr)
1417 // Found the previous store, return its value operand.
1418 return SI->getValueOperand();
1420 return nullptr; // Unknown store.
1426 /// \brief Speculate a conditional basic block flattening the CFG.
1428 /// Note that this is a very risky transform currently. Speculating
1429 /// instructions like this is most often not desirable. Instead, there is an MI
1430 /// pass which can do it with full awareness of the resource constraints.
1431 /// However, some cases are "obvious" and we should do directly. An example of
1432 /// this is speculating a single, reasonably cheap instruction.
1434 /// There is only one distinct advantage to flattening the CFG at the IR level:
1435 /// it makes very common but simplistic optimizations such as are common in
1436 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1437 /// modeling their effects with easier to reason about SSA value graphs.
1440 /// An illustration of this transform is turning this IR:
1443 /// %cmp = icmp ult %x, %y
1444 /// br i1 %cmp, label %EndBB, label %ThenBB
1446 /// %sub = sub %x, %y
1449 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1456 /// %cmp = icmp ult %x, %y
1457 /// %sub = sub %x, %y
1458 /// %cond = select i1 %cmp, 0, %sub
1462 /// \returns true if the conditional block is removed.
1463 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1464 const TargetTransformInfo &TTI) {
1465 // Be conservative for now. FP select instruction can often be expensive.
1466 Value *BrCond = BI->getCondition();
1467 if (isa<FCmpInst>(BrCond))
1470 BasicBlock *BB = BI->getParent();
1471 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1473 // If ThenBB is actually on the false edge of the conditional branch, remember
1474 // to swap the select operands later.
1475 bool Invert = false;
1476 if (ThenBB != BI->getSuccessor(0)) {
1477 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1480 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1482 // Keep a count of how many times instructions are used within CondBB when
1483 // they are candidates for sinking into CondBB. Specifically:
1484 // - They are defined in BB, and
1485 // - They have no side effects, and
1486 // - All of their uses are in CondBB.
1487 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1489 unsigned SpeculationCost = 0;
1490 Value *SpeculatedStoreValue = nullptr;
1491 StoreInst *SpeculatedStore = nullptr;
1492 for (BasicBlock::iterator BBI = ThenBB->begin(),
1493 BBE = std::prev(ThenBB->end());
1494 BBI != BBE; ++BBI) {
1495 Instruction *I = BBI;
1497 if (isa<DbgInfoIntrinsic>(I))
1500 // Only speculatively execute a single instruction (not counting the
1501 // terminator) for now.
1503 if (SpeculationCost > 1)
1506 // Don't hoist the instruction if it's unsafe or expensive.
1507 if (!isSafeToSpeculativelyExecute(I) &&
1508 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1509 I, BB, ThenBB, EndBB))))
1511 if (!SpeculatedStoreValue &&
1512 ComputeSpeculationCost(I, TTI) >
1513 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
1516 // Store the store speculation candidate.
1517 if (SpeculatedStoreValue)
1518 SpeculatedStore = cast<StoreInst>(I);
1520 // Do not hoist the instruction if any of its operands are defined but not
1521 // used in BB. The transformation will prevent the operand from
1522 // being sunk into the use block.
1523 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1525 Instruction *OpI = dyn_cast<Instruction>(*i);
1526 if (!OpI || OpI->getParent() != BB ||
1527 OpI->mayHaveSideEffects())
1528 continue; // Not a candidate for sinking.
1530 ++SinkCandidateUseCounts[OpI];
1534 // Consider any sink candidates which are only used in CondBB as costs for
1535 // speculation. Note, while we iterate over a DenseMap here, we are summing
1536 // and so iteration order isn't significant.
1537 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1538 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1540 if (I->first->getNumUses() == I->second) {
1542 if (SpeculationCost > 1)
1546 // Check that the PHI nodes can be converted to selects.
1547 bool HaveRewritablePHIs = false;
1548 for (BasicBlock::iterator I = EndBB->begin();
1549 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1550 Value *OrigV = PN->getIncomingValueForBlock(BB);
1551 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1553 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1554 // Skip PHIs which are trivial.
1558 // Don't convert to selects if we could remove undefined behavior instead.
1559 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1560 passingValueIsAlwaysUndefined(ThenV, PN))
1563 HaveRewritablePHIs = true;
1564 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1565 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1566 if (!OrigCE && !ThenCE)
1567 continue; // Known safe and cheap.
1569 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1570 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1572 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1573 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
1574 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1575 TargetTransformInfo::TCC_Basic;
1576 if (OrigCost + ThenCost > MaxCost)
1579 // Account for the cost of an unfolded ConstantExpr which could end up
1580 // getting expanded into Instructions.
1581 // FIXME: This doesn't account for how many operations are combined in the
1582 // constant expression.
1584 if (SpeculationCost > 1)
1588 // If there are no PHIs to process, bail early. This helps ensure idempotence
1590 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1593 // If we get here, we can hoist the instruction and if-convert.
1594 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1596 // Insert a select of the value of the speculated store.
1597 if (SpeculatedStoreValue) {
1598 IRBuilder<true, NoFolder> Builder(BI);
1599 Value *TrueV = SpeculatedStore->getValueOperand();
1600 Value *FalseV = SpeculatedStoreValue;
1602 std::swap(TrueV, FalseV);
1603 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1604 "." + FalseV->getName());
1605 SpeculatedStore->setOperand(0, S);
1608 // Hoist the instructions.
1609 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1610 std::prev(ThenBB->end()));
1612 // Insert selects and rewrite the PHI operands.
1613 IRBuilder<true, NoFolder> Builder(BI);
1614 for (BasicBlock::iterator I = EndBB->begin();
1615 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1616 unsigned OrigI = PN->getBasicBlockIndex(BB);
1617 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1618 Value *OrigV = PN->getIncomingValue(OrigI);
1619 Value *ThenV = PN->getIncomingValue(ThenI);
1621 // Skip PHIs which are trivial.
1625 // Create a select whose true value is the speculatively executed value and
1626 // false value is the preexisting value. Swap them if the branch
1627 // destinations were inverted.
1628 Value *TrueV = ThenV, *FalseV = OrigV;
1630 std::swap(TrueV, FalseV);
1631 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1632 TrueV->getName() + "." + FalseV->getName());
1633 PN->setIncomingValue(OrigI, V);
1634 PN->setIncomingValue(ThenI, V);
1641 /// \returns True if this block contains a CallInst with the NoDuplicate
1643 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1645 const CallInst *CI = dyn_cast<CallInst>(I);
1648 if (CI->cannotDuplicate())
1654 /// Return true if we can thread a branch across this block.
1655 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1656 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1659 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1660 if (isa<DbgInfoIntrinsic>(BBI))
1662 if (Size > 10) return false; // Don't clone large BB's.
1665 // We can only support instructions that do not define values that are
1666 // live outside of the current basic block.
1667 for (User *U : BBI->users()) {
1668 Instruction *UI = cast<Instruction>(U);
1669 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1672 // Looks ok, continue checking.
1678 /// If we have a conditional branch on a PHI node value that is defined in the
1679 /// same block as the branch and if any PHI entries are constants, thread edges
1680 /// corresponding to that entry to be branches to their ultimate destination.
1681 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
1682 BasicBlock *BB = BI->getParent();
1683 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1684 // NOTE: we currently cannot transform this case if the PHI node is used
1685 // outside of the block.
1686 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1689 // Degenerate case of a single entry PHI.
1690 if (PN->getNumIncomingValues() == 1) {
1691 FoldSingleEntryPHINodes(PN->getParent());
1695 // Now we know that this block has multiple preds and two succs.
1696 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1698 if (HasNoDuplicateCall(BB)) return false;
1700 // Okay, this is a simple enough basic block. See if any phi values are
1702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1703 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1704 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1706 // Okay, we now know that all edges from PredBB should be revectored to
1707 // branch to RealDest.
1708 BasicBlock *PredBB = PN->getIncomingBlock(i);
1709 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1711 if (RealDest == BB) continue; // Skip self loops.
1712 // Skip if the predecessor's terminator is an indirect branch.
1713 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1715 // The dest block might have PHI nodes, other predecessors and other
1716 // difficult cases. Instead of being smart about this, just insert a new
1717 // block that jumps to the destination block, effectively splitting
1718 // the edge we are about to create.
1719 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1720 RealDest->getName()+".critedge",
1721 RealDest->getParent(), RealDest);
1722 BranchInst::Create(RealDest, EdgeBB);
1724 // Update PHI nodes.
1725 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1727 // BB may have instructions that are being threaded over. Clone these
1728 // instructions into EdgeBB. We know that there will be no uses of the
1729 // cloned instructions outside of EdgeBB.
1730 BasicBlock::iterator InsertPt = EdgeBB->begin();
1731 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1732 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1733 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1734 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1737 // Clone the instruction.
1738 Instruction *N = BBI->clone();
1739 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1741 // Update operands due to translation.
1742 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1744 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1745 if (PI != TranslateMap.end())
1749 // Check for trivial simplification.
1750 if (Value *V = SimplifyInstruction(N, DL)) {
1751 TranslateMap[BBI] = V;
1752 delete N; // Instruction folded away, don't need actual inst
1754 // Insert the new instruction into its new home.
1755 EdgeBB->getInstList().insert(InsertPt, N);
1756 if (!BBI->use_empty())
1757 TranslateMap[BBI] = N;
1761 // Loop over all of the edges from PredBB to BB, changing them to branch
1762 // to EdgeBB instead.
1763 TerminatorInst *PredBBTI = PredBB->getTerminator();
1764 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1765 if (PredBBTI->getSuccessor(i) == BB) {
1766 BB->removePredecessor(PredBB);
1767 PredBBTI->setSuccessor(i, EdgeBB);
1770 // Recurse, simplifying any other constants.
1771 return FoldCondBranchOnPHI(BI, DL) | true;
1777 /// Given a BB that starts with the specified two-entry PHI node,
1778 /// see if we can eliminate it.
1779 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1780 const DataLayout &DL) {
1781 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1782 // statement", which has a very simple dominance structure. Basically, we
1783 // are trying to find the condition that is being branched on, which
1784 // subsequently causes this merge to happen. We really want control
1785 // dependence information for this check, but simplifycfg can't keep it up
1786 // to date, and this catches most of the cases we care about anyway.
1787 BasicBlock *BB = PN->getParent();
1788 BasicBlock *IfTrue, *IfFalse;
1789 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1791 // Don't bother if the branch will be constant folded trivially.
1792 isa<ConstantInt>(IfCond))
1795 // Okay, we found that we can merge this two-entry phi node into a select.
1796 // Doing so would require us to fold *all* two entry phi nodes in this block.
1797 // At some point this becomes non-profitable (particularly if the target
1798 // doesn't support cmov's). Only do this transformation if there are two or
1799 // fewer PHI nodes in this block.
1800 unsigned NumPhis = 0;
1801 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1805 // Loop over the PHI's seeing if we can promote them all to select
1806 // instructions. While we are at it, keep track of the instructions
1807 // that need to be moved to the dominating block.
1808 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1809 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1810 MaxCostVal1 = PHINodeFoldingThreshold;
1811 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1812 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
1814 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1815 PHINode *PN = cast<PHINode>(II++);
1816 if (Value *V = SimplifyInstruction(PN, DL)) {
1817 PN->replaceAllUsesWith(V);
1818 PN->eraseFromParent();
1822 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1823 MaxCostVal0, TTI) ||
1824 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1829 // If we folded the first phi, PN dangles at this point. Refresh it. If
1830 // we ran out of PHIs then we simplified them all.
1831 PN = dyn_cast<PHINode>(BB->begin());
1832 if (!PN) return true;
1834 // Don't fold i1 branches on PHIs which contain binary operators. These can
1835 // often be turned into switches and other things.
1836 if (PN->getType()->isIntegerTy(1) &&
1837 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1838 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1839 isa<BinaryOperator>(IfCond)))
1842 // If we all PHI nodes are promotable, check to make sure that all
1843 // instructions in the predecessor blocks can be promoted as well. If
1844 // not, we won't be able to get rid of the control flow, so it's not
1845 // worth promoting to select instructions.
1846 BasicBlock *DomBlock = nullptr;
1847 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1848 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1849 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1852 DomBlock = *pred_begin(IfBlock1);
1853 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1854 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1855 // This is not an aggressive instruction that we can promote.
1856 // Because of this, we won't be able to get rid of the control
1857 // flow, so the xform is not worth it.
1862 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1865 DomBlock = *pred_begin(IfBlock2);
1866 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1867 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1868 // This is not an aggressive instruction that we can promote.
1869 // Because of this, we won't be able to get rid of the control
1870 // flow, so the xform is not worth it.
1875 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1876 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1878 // If we can still promote the PHI nodes after this gauntlet of tests,
1879 // do all of the PHI's now.
1880 Instruction *InsertPt = DomBlock->getTerminator();
1881 IRBuilder<true, NoFolder> Builder(InsertPt);
1883 // Move all 'aggressive' instructions, which are defined in the
1884 // conditional parts of the if's up to the dominating block.
1886 DomBlock->getInstList().splice(InsertPt,
1887 IfBlock1->getInstList(), IfBlock1->begin(),
1888 IfBlock1->getTerminator());
1890 DomBlock->getInstList().splice(InsertPt,
1891 IfBlock2->getInstList(), IfBlock2->begin(),
1892 IfBlock2->getTerminator());
1894 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1895 // Change the PHI node into a select instruction.
1896 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1897 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1900 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1901 PN->replaceAllUsesWith(NV);
1903 PN->eraseFromParent();
1906 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1907 // has been flattened. Change DomBlock to jump directly to our new block to
1908 // avoid other simplifycfg's kicking in on the diamond.
1909 TerminatorInst *OldTI = DomBlock->getTerminator();
1910 Builder.SetInsertPoint(OldTI);
1911 Builder.CreateBr(BB);
1912 OldTI->eraseFromParent();
1916 /// If we found a conditional branch that goes to two returning blocks,
1917 /// try to merge them together into one return,
1918 /// introducing a select if the return values disagree.
1919 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1920 IRBuilder<> &Builder) {
1921 assert(BI->isConditional() && "Must be a conditional branch");
1922 BasicBlock *TrueSucc = BI->getSuccessor(0);
1923 BasicBlock *FalseSucc = BI->getSuccessor(1);
1924 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1925 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1927 // Check to ensure both blocks are empty (just a return) or optionally empty
1928 // with PHI nodes. If there are other instructions, merging would cause extra
1929 // computation on one path or the other.
1930 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1932 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1935 Builder.SetInsertPoint(BI);
1936 // Okay, we found a branch that is going to two return nodes. If
1937 // there is no return value for this function, just change the
1938 // branch into a return.
1939 if (FalseRet->getNumOperands() == 0) {
1940 TrueSucc->removePredecessor(BI->getParent());
1941 FalseSucc->removePredecessor(BI->getParent());
1942 Builder.CreateRetVoid();
1943 EraseTerminatorInstAndDCECond(BI);
1947 // Otherwise, figure out what the true and false return values are
1948 // so we can insert a new select instruction.
1949 Value *TrueValue = TrueRet->getReturnValue();
1950 Value *FalseValue = FalseRet->getReturnValue();
1952 // Unwrap any PHI nodes in the return blocks.
1953 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1954 if (TVPN->getParent() == TrueSucc)
1955 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1956 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1957 if (FVPN->getParent() == FalseSucc)
1958 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1960 // In order for this transformation to be safe, we must be able to
1961 // unconditionally execute both operands to the return. This is
1962 // normally the case, but we could have a potentially-trapping
1963 // constant expression that prevents this transformation from being
1965 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1968 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1972 // Okay, we collected all the mapped values and checked them for sanity, and
1973 // defined to really do this transformation. First, update the CFG.
1974 TrueSucc->removePredecessor(BI->getParent());
1975 FalseSucc->removePredecessor(BI->getParent());
1977 // Insert select instructions where needed.
1978 Value *BrCond = BI->getCondition();
1980 // Insert a select if the results differ.
1981 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1982 } else if (isa<UndefValue>(TrueValue)) {
1983 TrueValue = FalseValue;
1985 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1986 FalseValue, "retval");
1990 Value *RI = !TrueValue ?
1991 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1995 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1996 << "\n " << *BI << "NewRet = " << *RI
1997 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1999 EraseTerminatorInstAndDCECond(BI);
2004 /// Given a conditional BranchInstruction, retrieve the probabilities of the
2005 /// branch taking each edge. Fills in the two APInt parameters and returns true,
2006 /// or returns false if no or invalid metadata was found.
2007 static bool ExtractBranchMetadata(BranchInst *BI,
2008 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2009 assert(BI->isConditional() &&
2010 "Looking for probabilities on unconditional branch?");
2011 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2012 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2013 ConstantInt *CITrue =
2014 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2015 ConstantInt *CIFalse =
2016 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
2017 if (!CITrue || !CIFalse) return false;
2018 ProbTrue = CITrue->getValue().getZExtValue();
2019 ProbFalse = CIFalse->getValue().getZExtValue();
2023 /// Return true if the given instruction is available
2024 /// in its predecessor block. If yes, the instruction will be removed.
2025 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2026 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2028 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2029 Instruction *PBI = &*I;
2030 // Check whether Inst and PBI generate the same value.
2031 if (Inst->isIdenticalTo(PBI)) {
2032 Inst->replaceAllUsesWith(PBI);
2033 Inst->eraseFromParent();
2040 /// If this basic block is simple enough, and if a predecessor branches to us
2041 /// and one of our successors, fold the block into the predecessor and use
2042 /// logical operations to pick the right destination.
2043 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
2044 BasicBlock *BB = BI->getParent();
2046 Instruction *Cond = nullptr;
2047 if (BI->isConditional())
2048 Cond = dyn_cast<Instruction>(BI->getCondition());
2050 // For unconditional branch, check for a simple CFG pattern, where
2051 // BB has a single predecessor and BB's successor is also its predecessor's
2052 // successor. If such pattern exisits, check for CSE between BB and its
2054 if (BasicBlock *PB = BB->getSinglePredecessor())
2055 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2056 if (PBI->isConditional() &&
2057 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2058 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2059 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2061 Instruction *Curr = I++;
2062 if (isa<CmpInst>(Curr)) {
2066 // Quit if we can't remove this instruction.
2067 if (!checkCSEInPredecessor(Curr, PB))
2076 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2077 Cond->getParent() != BB || !Cond->hasOneUse())
2080 // Make sure the instruction after the condition is the cond branch.
2081 BasicBlock::iterator CondIt = Cond; ++CondIt;
2083 // Ignore dbg intrinsics.
2084 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2089 // Only allow this transformation if computing the condition doesn't involve
2090 // too many instructions and these involved instructions can be executed
2091 // unconditionally. We denote all involved instructions except the condition
2092 // as "bonus instructions", and only allow this transformation when the
2093 // number of the bonus instructions does not exceed a certain threshold.
2094 unsigned NumBonusInsts = 0;
2095 for (auto I = BB->begin(); Cond != I; ++I) {
2096 // Ignore dbg intrinsics.
2097 if (isa<DbgInfoIntrinsic>(I))
2099 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
2101 // I has only one use and can be executed unconditionally.
2102 Instruction *User = dyn_cast<Instruction>(I->user_back());
2103 if (User == nullptr || User->getParent() != BB)
2105 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2106 // to use any other instruction, User must be an instruction between next(I)
2109 // Early exits once we reach the limit.
2110 if (NumBonusInsts > BonusInstThreshold)
2114 // Cond is known to be a compare or binary operator. Check to make sure that
2115 // neither operand is a potentially-trapping constant expression.
2116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2123 // Finally, don't infinitely unroll conditional loops.
2124 BasicBlock *TrueDest = BI->getSuccessor(0);
2125 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2126 if (TrueDest == BB || FalseDest == BB)
2129 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2130 BasicBlock *PredBlock = *PI;
2131 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2133 // Check that we have two conditional branches. If there is a PHI node in
2134 // the common successor, verify that the same value flows in from both
2136 SmallVector<PHINode*, 4> PHIs;
2137 if (!PBI || PBI->isUnconditional() ||
2138 (BI->isConditional() &&
2139 !SafeToMergeTerminators(BI, PBI)) ||
2140 (!BI->isConditional() &&
2141 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2144 // Determine if the two branches share a common destination.
2145 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2146 bool InvertPredCond = false;
2148 if (BI->isConditional()) {
2149 if (PBI->getSuccessor(0) == TrueDest)
2150 Opc = Instruction::Or;
2151 else if (PBI->getSuccessor(1) == FalseDest)
2152 Opc = Instruction::And;
2153 else if (PBI->getSuccessor(0) == FalseDest)
2154 Opc = Instruction::And, InvertPredCond = true;
2155 else if (PBI->getSuccessor(1) == TrueDest)
2156 Opc = Instruction::Or, InvertPredCond = true;
2160 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2164 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2165 IRBuilder<> Builder(PBI);
2167 // If we need to invert the condition in the pred block to match, do so now.
2168 if (InvertPredCond) {
2169 Value *NewCond = PBI->getCondition();
2171 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2172 CmpInst *CI = cast<CmpInst>(NewCond);
2173 CI->setPredicate(CI->getInversePredicate());
2175 NewCond = Builder.CreateNot(NewCond,
2176 PBI->getCondition()->getName()+".not");
2179 PBI->setCondition(NewCond);
2180 PBI->swapSuccessors();
2183 // If we have bonus instructions, clone them into the predecessor block.
2184 // Note that there may be multiple predecessor blocks, so we cannot move
2185 // bonus instructions to a predecessor block.
2186 ValueToValueMapTy VMap; // maps original values to cloned values
2187 // We already make sure Cond is the last instruction before BI. Therefore,
2188 // all instructions before Cond other than DbgInfoIntrinsic are bonus
2190 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2191 if (isa<DbgInfoIntrinsic>(BonusInst))
2193 Instruction *NewBonusInst = BonusInst->clone();
2194 RemapInstruction(NewBonusInst, VMap,
2195 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2196 VMap[BonusInst] = NewBonusInst;
2198 // If we moved a load, we cannot any longer claim any knowledge about
2199 // its potential value. The previous information might have been valid
2200 // only given the branch precondition.
2201 // For an analogous reason, we must also drop all the metadata whose
2202 // semantics we don't understand.
2203 NewBonusInst->dropUnknownNonDebugMetadata();
2205 PredBlock->getInstList().insert(PBI, NewBonusInst);
2206 NewBonusInst->takeName(BonusInst);
2207 BonusInst->setName(BonusInst->getName() + ".old");
2210 // Clone Cond into the predecessor basic block, and or/and the
2211 // two conditions together.
2212 Instruction *New = Cond->clone();
2213 RemapInstruction(New, VMap,
2214 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2215 PredBlock->getInstList().insert(PBI, New);
2216 New->takeName(Cond);
2217 Cond->setName(New->getName() + ".old");
2219 if (BI->isConditional()) {
2220 Instruction *NewCond =
2221 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2223 PBI->setCondition(NewCond);
2225 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2226 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2228 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2230 SmallVector<uint64_t, 8> NewWeights;
2232 if (PBI->getSuccessor(0) == BB) {
2233 if (PredHasWeights && SuccHasWeights) {
2234 // PBI: br i1 %x, BB, FalseDest
2235 // BI: br i1 %y, TrueDest, FalseDest
2236 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2237 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2238 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2239 // TrueWeight for PBI * FalseWeight for BI.
2240 // We assume that total weights of a BranchInst can fit into 32 bits.
2241 // Therefore, we will not have overflow using 64-bit arithmetic.
2242 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2243 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2245 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2246 PBI->setSuccessor(0, TrueDest);
2248 if (PBI->getSuccessor(1) == BB) {
2249 if (PredHasWeights && SuccHasWeights) {
2250 // PBI: br i1 %x, TrueDest, BB
2251 // BI: br i1 %y, TrueDest, FalseDest
2252 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2253 // FalseWeight for PBI * TrueWeight for BI.
2254 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2255 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2256 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2257 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2259 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2260 PBI->setSuccessor(1, FalseDest);
2262 if (NewWeights.size() == 2) {
2263 // Halve the weights if any of them cannot fit in an uint32_t
2264 FitWeights(NewWeights);
2266 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2267 PBI->setMetadata(LLVMContext::MD_prof,
2268 MDBuilder(BI->getContext()).
2269 createBranchWeights(MDWeights));
2271 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2273 // Update PHI nodes in the common successors.
2274 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2275 ConstantInt *PBI_C = cast<ConstantInt>(
2276 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2277 assert(PBI_C->getType()->isIntegerTy(1));
2278 Instruction *MergedCond = nullptr;
2279 if (PBI->getSuccessor(0) == TrueDest) {
2280 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2281 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2282 // is false: !PBI_Cond and BI_Value
2283 Instruction *NotCond =
2284 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2287 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2292 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2293 PBI->getCondition(), MergedCond,
2296 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2297 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2298 // is false: PBI_Cond and BI_Value
2300 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 PBI->getCondition(), New,
2303 if (PBI_C->isOne()) {
2304 Instruction *NotCond =
2305 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2308 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2309 NotCond, MergedCond,
2314 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2317 // Change PBI from Conditional to Unconditional.
2318 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2319 EraseTerminatorInstAndDCECond(PBI);
2323 // TODO: If BB is reachable from all paths through PredBlock, then we
2324 // could replace PBI's branch probabilities with BI's.
2326 // Copy any debug value intrinsics into the end of PredBlock.
2327 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2328 if (isa<DbgInfoIntrinsic>(*I))
2329 I->clone()->insertBefore(PBI);
2336 /// If we have a conditional branch as a predecessor of another block,
2337 /// this function tries to simplify it. We know
2338 /// that PBI and BI are both conditional branches, and BI is in one of the
2339 /// successor blocks of PBI - PBI branches to BI.
2340 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2341 assert(PBI->isConditional() && BI->isConditional());
2342 BasicBlock *BB = BI->getParent();
2344 // If this block ends with a branch instruction, and if there is a
2345 // predecessor that ends on a branch of the same condition, make
2346 // this conditional branch redundant.
2347 if (PBI->getCondition() == BI->getCondition() &&
2348 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2349 // Okay, the outcome of this conditional branch is statically
2350 // knowable. If this block had a single pred, handle specially.
2351 if (BB->getSinglePredecessor()) {
2352 // Turn this into a branch on constant.
2353 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2354 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2356 return true; // Nuke the branch on constant.
2359 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2360 // in the constant and simplify the block result. Subsequent passes of
2361 // simplifycfg will thread the block.
2362 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2363 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2364 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2365 std::distance(PB, PE),
2366 BI->getCondition()->getName() + ".pr",
2368 // Okay, we're going to insert the PHI node. Since PBI is not the only
2369 // predecessor, compute the PHI'd conditional value for all of the preds.
2370 // Any predecessor where the condition is not computable we keep symbolic.
2371 for (pred_iterator PI = PB; PI != PE; ++PI) {
2372 BasicBlock *P = *PI;
2373 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2374 PBI != BI && PBI->isConditional() &&
2375 PBI->getCondition() == BI->getCondition() &&
2376 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2377 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2378 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2381 NewPN->addIncoming(BI->getCondition(), P);
2385 BI->setCondition(NewPN);
2390 // If this is a conditional branch in an empty block, and if any
2391 // predecessors are a conditional branch to one of our destinations,
2392 // fold the conditions into logical ops and one cond br.
2393 BasicBlock::iterator BBI = BB->begin();
2394 // Ignore dbg intrinsics.
2395 while (isa<DbgInfoIntrinsic>(BBI))
2401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2406 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2408 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2409 PBIOp = 0, BIOp = 1;
2410 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2411 PBIOp = 1, BIOp = 0;
2412 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2417 // Check to make sure that the other destination of this branch
2418 // isn't BB itself. If so, this is an infinite loop that will
2419 // keep getting unwound.
2420 if (PBI->getSuccessor(PBIOp) == BB)
2423 // Do not perform this transformation if it would require
2424 // insertion of a large number of select instructions. For targets
2425 // without predication/cmovs, this is a big pessimization.
2427 // Also do not perform this transformation if any phi node in the common
2428 // destination block can trap when reached by BB or PBB (PR17073). In that
2429 // case, it would be unsafe to hoist the operation into a select instruction.
2431 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2432 unsigned NumPhis = 0;
2433 for (BasicBlock::iterator II = CommonDest->begin();
2434 isa<PHINode>(II); ++II, ++NumPhis) {
2435 if (NumPhis > 2) // Disable this xform.
2438 PHINode *PN = cast<PHINode>(II);
2439 Value *BIV = PN->getIncomingValueForBlock(BB);
2440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2444 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2445 Value *PBIV = PN->getIncomingValue(PBBIdx);
2446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2451 // Finally, if everything is ok, fold the branches to logical ops.
2452 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2454 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2455 << "AND: " << *BI->getParent());
2458 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2459 // branch in it, where one edge (OtherDest) goes back to itself but the other
2460 // exits. We don't *know* that the program avoids the infinite loop
2461 // (even though that seems likely). If we do this xform naively, we'll end up
2462 // recursively unpeeling the loop. Since we know that (after the xform is
2463 // done) that the block *is* infinite if reached, we just make it an obviously
2464 // infinite loop with no cond branch.
2465 if (OtherDest == BB) {
2466 // Insert it at the end of the function, because it's either code,
2467 // or it won't matter if it's hot. :)
2468 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2469 "infloop", BB->getParent());
2470 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2471 OtherDest = InfLoopBlock;
2474 DEBUG(dbgs() << *PBI->getParent()->getParent());
2476 // BI may have other predecessors. Because of this, we leave
2477 // it alone, but modify PBI.
2479 // Make sure we get to CommonDest on True&True directions.
2480 Value *PBICond = PBI->getCondition();
2481 IRBuilder<true, NoFolder> Builder(PBI);
2483 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2485 Value *BICond = BI->getCondition();
2487 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2489 // Merge the conditions.
2490 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2492 // Modify PBI to branch on the new condition to the new dests.
2493 PBI->setCondition(Cond);
2494 PBI->setSuccessor(0, CommonDest);
2495 PBI->setSuccessor(1, OtherDest);
2497 // Update branch weight for PBI.
2498 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2499 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2501 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2503 if (PredHasWeights && SuccHasWeights) {
2504 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2505 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2506 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2507 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2508 // The weight to CommonDest should be PredCommon * SuccTotal +
2509 // PredOther * SuccCommon.
2510 // The weight to OtherDest should be PredOther * SuccOther.
2511 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2512 PredOther * SuccCommon,
2513 PredOther * SuccOther};
2514 // Halve the weights if any of them cannot fit in an uint32_t
2515 FitWeights(NewWeights);
2517 PBI->setMetadata(LLVMContext::MD_prof,
2518 MDBuilder(BI->getContext())
2519 .createBranchWeights(NewWeights[0], NewWeights[1]));
2522 // OtherDest may have phi nodes. If so, add an entry from PBI's
2523 // block that are identical to the entries for BI's block.
2524 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2526 // We know that the CommonDest already had an edge from PBI to
2527 // it. If it has PHIs though, the PHIs may have different
2528 // entries for BB and PBI's BB. If so, insert a select to make
2531 for (BasicBlock::iterator II = CommonDest->begin();
2532 (PN = dyn_cast<PHINode>(II)); ++II) {
2533 Value *BIV = PN->getIncomingValueForBlock(BB);
2534 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2535 Value *PBIV = PN->getIncomingValue(PBBIdx);
2537 // Insert a select in PBI to pick the right value.
2538 Value *NV = cast<SelectInst>
2539 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2540 PN->setIncomingValue(PBBIdx, NV);
2544 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2545 DEBUG(dbgs() << *PBI->getParent()->getParent());
2547 // This basic block is probably dead. We know it has at least
2548 // one fewer predecessor.
2552 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2553 // true or to FalseBB if Cond is false.
2554 // Takes care of updating the successors and removing the old terminator.
2555 // Also makes sure not to introduce new successors by assuming that edges to
2556 // non-successor TrueBBs and FalseBBs aren't reachable.
2557 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2558 BasicBlock *TrueBB, BasicBlock *FalseBB,
2559 uint32_t TrueWeight,
2560 uint32_t FalseWeight){
2561 // Remove any superfluous successor edges from the CFG.
2562 // First, figure out which successors to preserve.
2563 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2565 BasicBlock *KeepEdge1 = TrueBB;
2566 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2568 // Then remove the rest.
2569 for (BasicBlock *Succ : OldTerm->successors()) {
2570 // Make sure only to keep exactly one copy of each edge.
2571 if (Succ == KeepEdge1)
2572 KeepEdge1 = nullptr;
2573 else if (Succ == KeepEdge2)
2574 KeepEdge2 = nullptr;
2576 Succ->removePredecessor(OldTerm->getParent());
2579 IRBuilder<> Builder(OldTerm);
2580 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2582 // Insert an appropriate new terminator.
2583 if (!KeepEdge1 && !KeepEdge2) {
2584 if (TrueBB == FalseBB)
2585 // We were only looking for one successor, and it was present.
2586 // Create an unconditional branch to it.
2587 Builder.CreateBr(TrueBB);
2589 // We found both of the successors we were looking for.
2590 // Create a conditional branch sharing the condition of the select.
2591 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2592 if (TrueWeight != FalseWeight)
2593 NewBI->setMetadata(LLVMContext::MD_prof,
2594 MDBuilder(OldTerm->getContext()).
2595 createBranchWeights(TrueWeight, FalseWeight));
2597 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2598 // Neither of the selected blocks were successors, so this
2599 // terminator must be unreachable.
2600 new UnreachableInst(OldTerm->getContext(), OldTerm);
2602 // One of the selected values was a successor, but the other wasn't.
2603 // Insert an unconditional branch to the one that was found;
2604 // the edge to the one that wasn't must be unreachable.
2606 // Only TrueBB was found.
2607 Builder.CreateBr(TrueBB);
2609 // Only FalseBB was found.
2610 Builder.CreateBr(FalseBB);
2613 EraseTerminatorInstAndDCECond(OldTerm);
2618 // (switch (select cond, X, Y)) on constant X, Y
2619 // with a branch - conditional if X and Y lead to distinct BBs,
2620 // unconditional otherwise.
2621 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2622 // Check for constant integer values in the select.
2623 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2624 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2625 if (!TrueVal || !FalseVal)
2628 // Find the relevant condition and destinations.
2629 Value *Condition = Select->getCondition();
2630 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2631 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2633 // Get weight for TrueBB and FalseBB.
2634 uint32_t TrueWeight = 0, FalseWeight = 0;
2635 SmallVector<uint64_t, 8> Weights;
2636 bool HasWeights = HasBranchWeights(SI);
2638 GetBranchWeights(SI, Weights);
2639 if (Weights.size() == 1 + SI->getNumCases()) {
2640 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2641 getSuccessorIndex()];
2642 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2643 getSuccessorIndex()];
2647 // Perform the actual simplification.
2648 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2649 TrueWeight, FalseWeight);
2653 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2654 // blockaddress(@fn, BlockB)))
2656 // (br cond, BlockA, BlockB).
2657 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2658 // Check that both operands of the select are block addresses.
2659 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2660 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2664 // Extract the actual blocks.
2665 BasicBlock *TrueBB = TBA->getBasicBlock();
2666 BasicBlock *FalseBB = FBA->getBasicBlock();
2668 // Perform the actual simplification.
2669 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2673 /// This is called when we find an icmp instruction
2674 /// (a seteq/setne with a constant) as the only instruction in a
2675 /// block that ends with an uncond branch. We are looking for a very specific
2676 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2677 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2678 /// default value goes to an uncond block with a seteq in it, we get something
2681 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2683 /// %tmp = icmp eq i8 %A, 92
2686 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2688 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2689 /// the PHI, merging the third icmp into the switch.
2690 static bool TryToSimplifyUncondBranchWithICmpInIt(
2691 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
2692 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
2693 AssumptionCache *AC) {
2694 BasicBlock *BB = ICI->getParent();
2696 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2698 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2700 Value *V = ICI->getOperand(0);
2701 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2703 // The pattern we're looking for is where our only predecessor is a switch on
2704 // 'V' and this block is the default case for the switch. In this case we can
2705 // fold the compared value into the switch to simplify things.
2706 BasicBlock *Pred = BB->getSinglePredecessor();
2707 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2709 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2710 if (SI->getCondition() != V)
2713 // If BB is reachable on a non-default case, then we simply know the value of
2714 // V in this block. Substitute it and constant fold the icmp instruction
2716 if (SI->getDefaultDest() != BB) {
2717 ConstantInt *VVal = SI->findCaseDest(BB);
2718 assert(VVal && "Should have a unique destination value");
2719 ICI->setOperand(0, VVal);
2721 if (Value *V = SimplifyInstruction(ICI, DL)) {
2722 ICI->replaceAllUsesWith(V);
2723 ICI->eraseFromParent();
2725 // BB is now empty, so it is likely to simplify away.
2726 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
2729 // Ok, the block is reachable from the default dest. If the constant we're
2730 // comparing exists in one of the other edges, then we can constant fold ICI
2732 if (SI->findCaseValue(Cst) != SI->case_default()) {
2734 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2735 V = ConstantInt::getFalse(BB->getContext());
2737 V = ConstantInt::getTrue(BB->getContext());
2739 ICI->replaceAllUsesWith(V);
2740 ICI->eraseFromParent();
2741 // BB is now empty, so it is likely to simplify away.
2742 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
2745 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2747 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2748 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2749 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2750 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2753 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2755 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2756 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2758 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2759 std::swap(DefaultCst, NewCst);
2761 // Replace ICI (which is used by the PHI for the default value) with true or
2762 // false depending on if it is EQ or NE.
2763 ICI->replaceAllUsesWith(DefaultCst);
2764 ICI->eraseFromParent();
2766 // Okay, the switch goes to this block on a default value. Add an edge from
2767 // the switch to the merge point on the compared value.
2768 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2769 BB->getParent(), BB);
2770 SmallVector<uint64_t, 8> Weights;
2771 bool HasWeights = HasBranchWeights(SI);
2773 GetBranchWeights(SI, Weights);
2774 if (Weights.size() == 1 + SI->getNumCases()) {
2775 // Split weight for default case to case for "Cst".
2776 Weights[0] = (Weights[0]+1) >> 1;
2777 Weights.push_back(Weights[0]);
2779 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2780 SI->setMetadata(LLVMContext::MD_prof,
2781 MDBuilder(SI->getContext()).
2782 createBranchWeights(MDWeights));
2785 SI->addCase(Cst, NewBB);
2787 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2788 Builder.SetInsertPoint(NewBB);
2789 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2790 Builder.CreateBr(SuccBlock);
2791 PHIUse->addIncoming(NewCst, NewBB);
2795 /// The specified branch is a conditional branch.
2796 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2797 /// fold it into a switch instruction if so.
2798 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
2799 const DataLayout &DL) {
2800 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2801 if (!Cond) return false;
2803 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2804 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2805 // 'setne's and'ed together, collect them.
2807 // Try to gather values from a chain of and/or to be turned into a switch
2808 ConstantComparesGatherer ConstantCompare(Cond, DL);
2809 // Unpack the result
2810 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2811 Value *CompVal = ConstantCompare.CompValue;
2812 unsigned UsedICmps = ConstantCompare.UsedICmps;
2813 Value *ExtraCase = ConstantCompare.Extra;
2815 // If we didn't have a multiply compared value, fail.
2816 if (!CompVal) return false;
2818 // Avoid turning single icmps into a switch.
2822 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2824 // There might be duplicate constants in the list, which the switch
2825 // instruction can't handle, remove them now.
2826 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2827 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2829 // If Extra was used, we require at least two switch values to do the
2830 // transformation. A switch with one value is just an cond branch.
2831 if (ExtraCase && Values.size() < 2) return false;
2833 // TODO: Preserve branch weight metadata, similarly to how
2834 // FoldValueComparisonIntoPredecessors preserves it.
2836 // Figure out which block is which destination.
2837 BasicBlock *DefaultBB = BI->getSuccessor(1);
2838 BasicBlock *EdgeBB = BI->getSuccessor(0);
2839 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2841 BasicBlock *BB = BI->getParent();
2843 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2844 << " cases into SWITCH. BB is:\n" << *BB);
2846 // If there are any extra values that couldn't be folded into the switch
2847 // then we evaluate them with an explicit branch first. Split the block
2848 // right before the condbr to handle it.
2850 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2851 // Remove the uncond branch added to the old block.
2852 TerminatorInst *OldTI = BB->getTerminator();
2853 Builder.SetInsertPoint(OldTI);
2856 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2858 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2860 OldTI->eraseFromParent();
2862 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2863 // for the edge we just added.
2864 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2866 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2867 << "\nEXTRABB = " << *BB);
2871 Builder.SetInsertPoint(BI);
2872 // Convert pointer to int before we switch.
2873 if (CompVal->getType()->isPointerTy()) {
2874 CompVal = Builder.CreatePtrToInt(
2875 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
2878 // Create the new switch instruction now.
2879 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2881 // Add all of the 'cases' to the switch instruction.
2882 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2883 New->addCase(Values[i], EdgeBB);
2885 // We added edges from PI to the EdgeBB. As such, if there were any
2886 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2887 // the number of edges added.
2888 for (BasicBlock::iterator BBI = EdgeBB->begin();
2889 isa<PHINode>(BBI); ++BBI) {
2890 PHINode *PN = cast<PHINode>(BBI);
2891 Value *InVal = PN->getIncomingValueForBlock(BB);
2892 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2893 PN->addIncoming(InVal, BB);
2896 // Erase the old branch instruction.
2897 EraseTerminatorInstAndDCECond(BI);
2899 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2903 // FIXME: This seems like a pretty common thing to want to do. Consider
2904 // whether there is a more accessible place to put this.
2905 static void convertInvokeToCall(InvokeInst *II) {
2906 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2907 // Insert a call instruction before the invoke.
2908 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2910 Call->setCallingConv(II->getCallingConv());
2911 Call->setAttributes(II->getAttributes());
2912 Call->setDebugLoc(II->getDebugLoc());
2914 // Anything that used the value produced by the invoke instruction now uses
2915 // the value produced by the call instruction. Note that we do this even
2916 // for void functions and calls with no uses so that the callgraph edge is
2918 II->replaceAllUsesWith(Call);
2919 II->getUnwindDest()->removePredecessor(II->getParent());
2921 // Insert a branch to the normal destination right before the invoke.
2922 BranchInst::Create(II->getNormalDest(), II);
2924 // Finally, delete the invoke instruction!
2925 II->eraseFromParent();
2928 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2929 // If this is a trivial landing pad that just continues unwinding the caught
2930 // exception then zap the landing pad, turning its invokes into calls.
2931 BasicBlock *BB = RI->getParent();
2932 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2933 if (RI->getValue() != LPInst)
2934 // Not a landing pad, or the resume is not unwinding the exception that
2935 // caused control to branch here.
2938 // Check that there are no other instructions except for debug intrinsics.
2939 BasicBlock::iterator I = LPInst, E = RI;
2941 if (!isa<DbgInfoIntrinsic>(I))
2944 // Turn all invokes that unwind here into calls and delete the basic block.
2945 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2946 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2947 convertInvokeToCall(II);
2950 // The landingpad is now unreachable. Zap it.
2951 BB->eraseFromParent();
2955 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
2956 // If this is a trivial cleanup pad that executes no instructions, it can be
2957 // eliminated. If the cleanup pad continues to the caller, any predecessor
2958 // that is an EH pad will be updated to continue to the caller and any
2959 // predecessor that terminates with an invoke instruction will have its invoke
2960 // instruction converted to a call instruction. If the cleanup pad being
2961 // simplified does not continue to the caller, each predecessor will be
2962 // updated to continue to the unwind destination of the cleanup pad being
2964 BasicBlock *BB = RI->getParent();
2965 Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI());
2967 // This isn't an empty cleanup.
2970 // Check that there are no other instructions except for debug intrinsics.
2971 BasicBlock::iterator I = CPInst, E = RI;
2973 if (!isa<DbgInfoIntrinsic>(I))
2976 // If the cleanup return we are simplifying unwinds to the caller, this
2977 // will set UnwindDest to nullptr.
2978 BasicBlock *UnwindDest = RI->getUnwindDest();
2980 // We're about to remove BB from the control flow. Before we do, sink any
2981 // PHINodes into the unwind destination. Doing this before changing the
2982 // control flow avoids some potentially slow checks, since we can currently
2983 // be certain that UnwindDest and BB have no common predecessors (since they
2984 // are both EH pads).
2986 // First, go through the PHI nodes in UnwindDest and update any nodes that
2987 // reference the block we are removing
2988 for (BasicBlock::iterator I = UnwindDest->begin(),
2989 IE = UnwindDest->getFirstNonPHI();
2991 PHINode *DestPN = cast<PHINode>(I);
2993 int Idx = DestPN->getBasicBlockIndex(BB);
2994 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
2996 // This PHI node has an incoming value that corresponds to a control
2997 // path through the cleanup pad we are removing. If the incoming
2998 // value is in the cleanup pad, it must be a PHINode (because we
2999 // verified above that the block is otherwise empty). Otherwise, the
3000 // value is either a constant or a value that dominates the cleanup
3001 // pad being removed.
3003 // Because BB and UnwindDest are both EH pads, all of their
3004 // predecessors must unwind to these blocks, and since no instruction
3005 // can have multiple unwind destinations, there will be no overlap in
3006 // incoming blocks between SrcPN and DestPN.
3007 Value *SrcVal = DestPN->getIncomingValue(Idx);
3008 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3010 // Remove the entry for the block we are deleting.
3011 DestPN->removeIncomingValue(Idx, false);
3013 if (SrcPN && SrcPN->getParent() == BB) {
3014 // If the incoming value was a PHI node in the cleanup pad we are
3015 // removing, we need to merge that PHI node's incoming values into
3017 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3018 SrcIdx != SrcE; ++SrcIdx) {
3019 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3020 SrcPN->getIncomingBlock(SrcIdx));
3023 // Otherwise, the incoming value came from above BB and
3024 // so we can just reuse it. We must associate all of BB's
3025 // predecessors with this value.
3026 for (auto *pred : predecessors(BB)) {
3027 DestPN->addIncoming(SrcVal, pred);
3032 // Sink any remaining PHI nodes directly into UnwindDest.
3033 Instruction *InsertPt = UnwindDest->getFirstNonPHI();
3034 for (BasicBlock::iterator I = BB->begin(), IE = BB->getFirstNonPHI();
3036 // The iterator must be incremented here because the instructions are
3037 // being moved to another block.
3038 PHINode *PN = cast<PHINode>(I++);
3039 if (PN->use_empty())
3040 // If the PHI node has no uses, just leave it. It will be erased
3041 // when we erase BB below.
3044 // Otherwise, sink this PHI node into UnwindDest.
3045 // Any predecessors to UnwindDest which are not already represented
3046 // must be back edges which inherit the value from the path through
3047 // BB. In this case, the PHI value must reference itself.
3048 for (auto *pred : predecessors(UnwindDest))
3050 PN->addIncoming(PN, pred);
3051 PN->moveBefore(InsertPt);
3055 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3056 // The iterator must be updated here because we are removing this pred.
3057 BasicBlock *PredBB = *PI++;
3058 TerminatorInst *TI = PredBB->getTerminator();
3059 if (UnwindDest == nullptr) {
3060 if (auto *II = dyn_cast<InvokeInst>(TI)) {
3061 // The cleanup return being simplified continues to the caller and this
3062 // predecessor terminated with an invoke instruction. Convert the
3063 // invoke to a call.
3064 // This call updates the predecessor/successor chain.
3065 convertInvokeToCall(II);
3067 // In the remaining cases the predecessor's terminator unwinds to the
3068 // block we are removing. We need to create a new instruction that
3069 // unwinds to the caller. Simply setting the unwind destination to
3070 // nullptr would leave the objects internal data in an inconsistent
3072 // FIXME: Consider whether it is better to update setUnwindDest to
3073 // keep things consistent.
3074 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3075 auto *NewCRI = CleanupReturnInst::Create(CRI->getCleanupPad(),
3077 NewCRI->takeName(CRI);
3078 NewCRI->setDebugLoc(CRI->getDebugLoc());
3079 CRI->eraseFromParent();
3080 } else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI)) {
3081 auto *NewCEP = CatchEndPadInst::Create(CEP->getContext(), nullptr,
3083 NewCEP->takeName(CEP);
3084 NewCEP->setDebugLoc(CEP->getDebugLoc());
3085 CEP->eraseFromParent();
3086 } else if (auto *TPI = dyn_cast<TerminatePadInst>(TI)) {
3087 SmallVector<Value *, 3> TerminatePadArgs;
3088 for (Value *Operand : TPI->arg_operands())
3089 TerminatePadArgs.push_back(Operand);
3090 auto *NewTPI = TerminatePadInst::Create(TPI->getContext(), nullptr,
3091 TerminatePadArgs, TPI);
3092 NewTPI->takeName(TPI);
3093 NewTPI->setDebugLoc(TPI->getDebugLoc());
3094 TPI->eraseFromParent();
3096 llvm_unreachable("Unexpected predecessor to cleanup pad.");
3100 // If the predecessor did not terminate with an invoke instruction, it
3101 // must be some variety of EH pad.
3102 TerminatorInst *TI = PredBB->getTerminator();
3103 // FIXME: Introducing an EH terminator base class would simplify this.
3104 if (auto *II = dyn_cast<InvokeInst>(TI))
3105 II->setUnwindDest(UnwindDest);
3106 else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
3107 CRI->setUnwindDest(UnwindDest);
3108 else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI))
3109 CEP->setUnwindDest(UnwindDest);
3110 else if (auto *TPI = dyn_cast<TerminatePadInst>(TI))
3111 TPI->setUnwindDest(UnwindDest);
3113 llvm_unreachable("Unexpected predecessor to cleanup pad.");
3117 // The cleanup pad is now unreachable. Zap it.
3118 BB->eraseFromParent();
3122 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
3123 BasicBlock *BB = RI->getParent();
3124 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
3126 // Find predecessors that end with branches.
3127 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3128 SmallVector<BranchInst*, 8> CondBranchPreds;
3129 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3130 BasicBlock *P = *PI;
3131 TerminatorInst *PTI = P->getTerminator();
3132 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3133 if (BI->isUnconditional())
3134 UncondBranchPreds.push_back(P);
3136 CondBranchPreds.push_back(BI);
3140 // If we found some, do the transformation!
3141 if (!UncondBranchPreds.empty() && DupRet) {
3142 while (!UncondBranchPreds.empty()) {
3143 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3144 DEBUG(dbgs() << "FOLDING: " << *BB
3145 << "INTO UNCOND BRANCH PRED: " << *Pred);
3146 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3149 // If we eliminated all predecessors of the block, delete the block now.
3151 // We know there are no successors, so just nuke the block.
3152 BB->eraseFromParent();
3157 // Check out all of the conditional branches going to this return
3158 // instruction. If any of them just select between returns, change the
3159 // branch itself into a select/return pair.
3160 while (!CondBranchPreds.empty()) {
3161 BranchInst *BI = CondBranchPreds.pop_back_val();
3163 // Check to see if the non-BB successor is also a return block.
3164 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3165 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3166 SimplifyCondBranchToTwoReturns(BI, Builder))
3172 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3173 BasicBlock *BB = UI->getParent();
3175 bool Changed = false;
3177 // If there are any instructions immediately before the unreachable that can
3178 // be removed, do so.
3179 while (UI != BB->begin()) {
3180 BasicBlock::iterator BBI = UI;
3182 // Do not delete instructions that can have side effects which might cause
3183 // the unreachable to not be reachable; specifically, calls and volatile
3184 // operations may have this effect.
3185 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3187 if (BBI->mayHaveSideEffects()) {
3188 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3189 if (SI->isVolatile())
3191 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3192 if (LI->isVolatile())
3194 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3195 if (RMWI->isVolatile())
3197 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3198 if (CXI->isVolatile())
3200 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3201 !isa<LandingPadInst>(BBI)) {
3204 // Note that deleting LandingPad's here is in fact okay, although it
3205 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3206 // all the predecessors of this block will be the unwind edges of Invokes,
3207 // and we can therefore guarantee this block will be erased.
3210 // Delete this instruction (any uses are guaranteed to be dead)
3211 if (!BBI->use_empty())
3212 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3213 BBI->eraseFromParent();
3217 // If the unreachable instruction is the first in the block, take a gander
3218 // at all of the predecessors of this instruction, and simplify them.
3219 if (&BB->front() != UI) return Changed;
3221 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3222 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3223 TerminatorInst *TI = Preds[i]->getTerminator();
3224 IRBuilder<> Builder(TI);
3225 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3226 if (BI->isUnconditional()) {
3227 if (BI->getSuccessor(0) == BB) {
3228 new UnreachableInst(TI->getContext(), TI);
3229 TI->eraseFromParent();
3233 if (BI->getSuccessor(0) == BB) {
3234 Builder.CreateBr(BI->getSuccessor(1));
3235 EraseTerminatorInstAndDCECond(BI);
3236 } else if (BI->getSuccessor(1) == BB) {
3237 Builder.CreateBr(BI->getSuccessor(0));
3238 EraseTerminatorInstAndDCECond(BI);
3242 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3243 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3245 if (i.getCaseSuccessor() == BB) {
3246 BB->removePredecessor(SI->getParent());
3251 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3252 if (II->getUnwindDest() == BB) {
3253 // Convert the invoke to a call instruction. This would be a good
3254 // place to note that the call does not throw though.
3255 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3256 II->removeFromParent(); // Take out of symbol table
3258 // Insert the call now...
3259 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3260 Builder.SetInsertPoint(BI);
3261 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3262 Args, II->getName());
3263 CI->setCallingConv(II->getCallingConv());
3264 CI->setAttributes(II->getAttributes());
3265 // If the invoke produced a value, the call does now instead.
3266 II->replaceAllUsesWith(CI);
3273 // If this block is now dead, remove it.
3274 if (pred_empty(BB) &&
3275 BB != &BB->getParent()->getEntryBlock()) {
3276 // We know there are no successors, so just nuke the block.
3277 BB->eraseFromParent();
3284 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3285 assert(Cases.size() >= 1);
3287 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3288 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3289 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3295 /// Turn a switch with two reachable destinations into an integer range
3296 /// comparison and branch.
3297 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3298 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3301 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3303 // Partition the cases into two sets with different destinations.
3304 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3305 BasicBlock *DestB = nullptr;
3306 SmallVector <ConstantInt *, 16> CasesA;
3307 SmallVector <ConstantInt *, 16> CasesB;
3309 for (SwitchInst::CaseIt I : SI->cases()) {
3310 BasicBlock *Dest = I.getCaseSuccessor();
3311 if (!DestA) DestA = Dest;
3312 if (Dest == DestA) {
3313 CasesA.push_back(I.getCaseValue());
3316 if (!DestB) DestB = Dest;
3317 if (Dest == DestB) {
3318 CasesB.push_back(I.getCaseValue());
3321 return false; // More than two destinations.
3324 assert(DestA && DestB && "Single-destination switch should have been folded.");
3325 assert(DestA != DestB);
3326 assert(DestB != SI->getDefaultDest());
3327 assert(!CasesB.empty() && "There must be non-default cases.");
3328 assert(!CasesA.empty() || HasDefault);
3330 // Figure out if one of the sets of cases form a contiguous range.
3331 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3332 BasicBlock *ContiguousDest = nullptr;
3333 BasicBlock *OtherDest = nullptr;
3334 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3335 ContiguousCases = &CasesA;
3336 ContiguousDest = DestA;
3338 } else if (CasesAreContiguous(CasesB)) {
3339 ContiguousCases = &CasesB;
3340 ContiguousDest = DestB;
3345 // Start building the compare and branch.
3347 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3348 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
3350 Value *Sub = SI->getCondition();
3351 if (!Offset->isNullValue())
3352 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3355 // If NumCases overflowed, then all possible values jump to the successor.
3356 if (NumCases->isNullValue() && !ContiguousCases->empty())
3357 Cmp = ConstantInt::getTrue(SI->getContext());
3359 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3360 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
3362 // Update weight for the newly-created conditional branch.
3363 if (HasBranchWeights(SI)) {
3364 SmallVector<uint64_t, 8> Weights;
3365 GetBranchWeights(SI, Weights);
3366 if (Weights.size() == 1 + SI->getNumCases()) {
3367 uint64_t TrueWeight = 0;
3368 uint64_t FalseWeight = 0;
3369 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3370 if (SI->getSuccessor(I) == ContiguousDest)
3371 TrueWeight += Weights[I];
3373 FalseWeight += Weights[I];
3375 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3379 NewBI->setMetadata(LLVMContext::MD_prof,
3380 MDBuilder(SI->getContext()).createBranchWeights(
3381 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
3385 // Prune obsolete incoming values off the successors' PHI nodes.
3386 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3387 unsigned PreviousEdges = ContiguousCases->size();
3388 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3389 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3390 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3392 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3393 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3394 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3395 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3396 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3400 SI->eraseFromParent();
3405 /// Compute masked bits for the condition of a switch
3406 /// and use it to remove dead cases.
3407 static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3408 const DataLayout &DL) {
3409 Value *Cond = SI->getCondition();
3410 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3411 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3412 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
3414 // Gather dead cases.
3415 SmallVector<ConstantInt*, 8> DeadCases;
3416 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3417 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3418 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3419 DeadCases.push_back(I.getCaseValue());
3420 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3421 << I.getCaseValue() << "' is dead.\n");
3425 // If we can prove that the cases must cover all possible values, the
3426 // default destination becomes dead and we can remove it.
3428 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3429 if (HasDefault && Bits < 64 /* avoid overflow */ &&
3430 SI->getNumCases() == (1ULL << Bits)) {
3431 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3432 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3433 SI->getParent(), "");
3434 SI->setDefaultDest(NewDefault);
3435 SplitBlock(NewDefault, NewDefault->begin());
3436 auto *OldTI = NewDefault->getTerminator();
3437 new UnreachableInst(SI->getContext(), OldTI);
3438 EraseTerminatorInstAndDCECond(OldTI);
3442 SmallVector<uint64_t, 8> Weights;
3443 bool HasWeight = HasBranchWeights(SI);
3445 GetBranchWeights(SI, Weights);
3446 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3449 // Remove dead cases from the switch.
3450 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3451 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3452 assert(Case != SI->case_default() &&
3453 "Case was not found. Probably mistake in DeadCases forming.");
3455 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3459 // Prune unused values from PHI nodes.
3460 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3461 SI->removeCase(Case);
3463 if (HasWeight && Weights.size() >= 2) {
3464 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3465 SI->setMetadata(LLVMContext::MD_prof,
3466 MDBuilder(SI->getParent()->getContext()).
3467 createBranchWeights(MDWeights));
3470 return !DeadCases.empty();
3473 /// If BB would be eligible for simplification by
3474 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3475 /// by an unconditional branch), look at the phi node for BB in the successor
3476 /// block and see if the incoming value is equal to CaseValue. If so, return
3477 /// the phi node, and set PhiIndex to BB's index in the phi node.
3478 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3481 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3482 return nullptr; // BB must be empty to be a candidate for simplification.
3483 if (!BB->getSinglePredecessor())
3484 return nullptr; // BB must be dominated by the switch.
3486 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3487 if (!Branch || !Branch->isUnconditional())
3488 return nullptr; // Terminator must be unconditional branch.
3490 BasicBlock *Succ = Branch->getSuccessor(0);
3492 BasicBlock::iterator I = Succ->begin();
3493 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3494 int Idx = PHI->getBasicBlockIndex(BB);
3495 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3497 Value *InValue = PHI->getIncomingValue(Idx);
3498 if (InValue != CaseValue) continue;
3507 /// Try to forward the condition of a switch instruction to a phi node
3508 /// dominated by the switch, if that would mean that some of the destination
3509 /// blocks of the switch can be folded away.
3510 /// Returns true if a change is made.
3511 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3512 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3513 ForwardingNodesMap ForwardingNodes;
3515 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3516 ConstantInt *CaseValue = I.getCaseValue();
3517 BasicBlock *CaseDest = I.getCaseSuccessor();
3520 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3524 ForwardingNodes[PHI].push_back(PhiIndex);
3527 bool Changed = false;
3529 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3530 E = ForwardingNodes.end(); I != E; ++I) {
3531 PHINode *Phi = I->first;
3532 SmallVectorImpl<int> &Indexes = I->second;
3534 if (Indexes.size() < 2) continue;
3536 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3537 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3544 /// Return true if the backend will be able to handle
3545 /// initializing an array of constants like C.
3546 static bool ValidLookupTableConstant(Constant *C) {
3547 if (C->isThreadDependent())
3549 if (C->isDLLImportDependent())
3552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3553 return CE->isGEPWithNoNotionalOverIndexing();
3555 return isa<ConstantFP>(C) ||
3556 isa<ConstantInt>(C) ||
3557 isa<ConstantPointerNull>(C) ||
3558 isa<GlobalValue>(C) ||
3562 /// If V is a Constant, return it. Otherwise, try to look up
3563 /// its constant value in ConstantPool, returning 0 if it's not there.
3564 static Constant *LookupConstant(Value *V,
3565 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3566 if (Constant *C = dyn_cast<Constant>(V))
3568 return ConstantPool.lookup(V);
3571 /// Try to fold instruction I into a constant. This works for
3572 /// simple instructions such as binary operations where both operands are
3573 /// constant or can be replaced by constants from the ConstantPool. Returns the
3574 /// resulting constant on success, 0 otherwise.
3576 ConstantFold(Instruction *I, const DataLayout &DL,
3577 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
3578 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3579 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3582 if (A->isAllOnesValue())
3583 return LookupConstant(Select->getTrueValue(), ConstantPool);
3584 if (A->isNullValue())
3585 return LookupConstant(Select->getFalseValue(), ConstantPool);
3589 SmallVector<Constant *, 4> COps;
3590 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3591 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3597 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3598 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3602 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3605 /// Try to determine the resulting constant values in phi nodes
3606 /// at the common destination basic block, *CommonDest, for one of the case
3607 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3608 /// case), of a switch instruction SI.
3610 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
3611 BasicBlock **CommonDest,
3612 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3613 const DataLayout &DL) {
3614 // The block from which we enter the common destination.
3615 BasicBlock *Pred = SI->getParent();
3617 // If CaseDest is empty except for some side-effect free instructions through
3618 // which we can constant-propagate the CaseVal, continue to its successor.
3619 SmallDenseMap<Value*, Constant*> ConstantPool;
3620 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3621 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3623 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3624 // If the terminator is a simple branch, continue to the next block.
3625 if (T->getNumSuccessors() != 1)
3628 CaseDest = T->getSuccessor(0);
3629 } else if (isa<DbgInfoIntrinsic>(I)) {
3630 // Skip debug intrinsic.
3632 } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) {
3633 // Instruction is side-effect free and constant.
3635 // If the instruction has uses outside this block or a phi node slot for
3636 // the block, it is not safe to bypass the instruction since it would then
3637 // no longer dominate all its uses.
3638 for (auto &Use : I->uses()) {
3639 User *User = Use.getUser();
3640 if (Instruction *I = dyn_cast<Instruction>(User))
3641 if (I->getParent() == CaseDest)
3643 if (PHINode *Phi = dyn_cast<PHINode>(User))
3644 if (Phi->getIncomingBlock(Use) == CaseDest)
3649 ConstantPool.insert(std::make_pair(I, C));
3655 // If we did not have a CommonDest before, use the current one.
3657 *CommonDest = CaseDest;
3658 // If the destination isn't the common one, abort.
3659 if (CaseDest != *CommonDest)
3662 // Get the values for this case from phi nodes in the destination block.
3663 BasicBlock::iterator I = (*CommonDest)->begin();
3664 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3665 int Idx = PHI->getBasicBlockIndex(Pred);
3669 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3674 // Be conservative about which kinds of constants we support.
3675 if (!ValidLookupTableConstant(ConstVal))
3678 Res.push_back(std::make_pair(PHI, ConstVal));
3681 return Res.size() > 0;
3684 // Helper function used to add CaseVal to the list of cases that generate
3686 static void MapCaseToResult(ConstantInt *CaseVal,
3687 SwitchCaseResultVectorTy &UniqueResults,
3689 for (auto &I : UniqueResults) {
3690 if (I.first == Result) {
3691 I.second.push_back(CaseVal);
3695 UniqueResults.push_back(std::make_pair(Result,
3696 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3699 // Helper function that initializes a map containing
3700 // results for the PHI node of the common destination block for a switch
3701 // instruction. Returns false if multiple PHI nodes have been found or if
3702 // there is not a common destination block for the switch.
3703 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3704 BasicBlock *&CommonDest,
3705 SwitchCaseResultVectorTy &UniqueResults,
3706 Constant *&DefaultResult,
3707 const DataLayout &DL) {
3708 for (auto &I : SI->cases()) {
3709 ConstantInt *CaseVal = I.getCaseValue();
3711 // Resulting value at phi nodes for this case value.
3712 SwitchCaseResultsTy Results;
3713 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3717 // Only one value per case is permitted
3718 if (Results.size() > 1)
3720 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3722 // Check the PHI consistency.
3724 PHI = Results[0].first;
3725 else if (PHI != Results[0].first)
3728 // Find the default result value.
3729 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3730 BasicBlock *DefaultDest = SI->getDefaultDest();
3731 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3733 // If the default value is not found abort unless the default destination
3736 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3737 if ((!DefaultResult &&
3738 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3744 // Helper function that checks if it is possible to transform a switch with only
3745 // two cases (or two cases + default) that produces a result into a select.
3748 // case 10: %0 = icmp eq i32 %a, 10
3749 // return 10; %1 = select i1 %0, i32 10, i32 4
3750 // case 20: ----> %2 = icmp eq i32 %a, 20
3751 // return 2; %3 = select i1 %2, i32 2, i32 %1
3756 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3757 Constant *DefaultResult, Value *Condition,
3758 IRBuilder<> &Builder) {
3759 assert(ResultVector.size() == 2 &&
3760 "We should have exactly two unique results at this point");
3761 // If we are selecting between only two cases transform into a simple
3762 // select or a two-way select if default is possible.
3763 if (ResultVector[0].second.size() == 1 &&
3764 ResultVector[1].second.size() == 1) {
3765 ConstantInt *const FirstCase = ResultVector[0].second[0];
3766 ConstantInt *const SecondCase = ResultVector[1].second[0];
3768 bool DefaultCanTrigger = DefaultResult;
3769 Value *SelectValue = ResultVector[1].first;
3770 if (DefaultCanTrigger) {
3771 Value *const ValueCompare =
3772 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3773 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3774 DefaultResult, "switch.select");
3776 Value *const ValueCompare =
3777 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3778 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3785 // Helper function to cleanup a switch instruction that has been converted into
3786 // a select, fixing up PHI nodes and basic blocks.
3787 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3789 IRBuilder<> &Builder) {
3790 BasicBlock *SelectBB = SI->getParent();
3791 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3792 PHI->removeIncomingValue(SelectBB);
3793 PHI->addIncoming(SelectValue, SelectBB);
3795 Builder.CreateBr(PHI->getParent());
3797 // Remove the switch.
3798 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3799 BasicBlock *Succ = SI->getSuccessor(i);
3801 if (Succ == PHI->getParent())
3803 Succ->removePredecessor(SelectBB);
3805 SI->eraseFromParent();
3808 /// If the switch is only used to initialize one or more
3809 /// phi nodes in a common successor block with only two different
3810 /// constant values, replace the switch with select.
3811 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3812 AssumptionCache *AC, const DataLayout &DL) {
3813 Value *const Cond = SI->getCondition();
3814 PHINode *PHI = nullptr;
3815 BasicBlock *CommonDest = nullptr;
3816 Constant *DefaultResult;
3817 SwitchCaseResultVectorTy UniqueResults;
3818 // Collect all the cases that will deliver the same value from the switch.
3819 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
3822 // Selects choose between maximum two values.
3823 if (UniqueResults.size() != 2)
3825 assert(PHI != nullptr && "PHI for value select not found");
3827 Builder.SetInsertPoint(SI);
3828 Value *SelectValue = ConvertTwoCaseSwitch(
3830 DefaultResult, Cond, Builder);
3832 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3835 // The switch couldn't be converted into a select.
3840 /// This class represents a lookup table that can be used to replace a switch.
3841 class SwitchLookupTable {
3843 /// Create a lookup table to use as a switch replacement with the contents
3844 /// of Values, using DefaultValue to fill any holes in the table.
3846 Module &M, uint64_t TableSize, ConstantInt *Offset,
3847 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3848 Constant *DefaultValue, const DataLayout &DL);
3850 /// Build instructions with Builder to retrieve the value at
3851 /// the position given by Index in the lookup table.
3852 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3854 /// Return true if a table with TableSize elements of
3855 /// type ElementType would fit in a target-legal register.
3856 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
3860 // Depending on the contents of the table, it can be represented in
3863 // For tables where each element contains the same value, we just have to
3864 // store that single value and return it for each lookup.
3867 // For tables where there is a linear relationship between table index
3868 // and values. We calculate the result with a simple multiplication
3869 // and addition instead of a table lookup.
3872 // For small tables with integer elements, we can pack them into a bitmap
3873 // that fits into a target-legal register. Values are retrieved by
3874 // shift and mask operations.
3877 // The table is stored as an array of values. Values are retrieved by load
3878 // instructions from the table.
3882 // For SingleValueKind, this is the single value.
3883 Constant *SingleValue;
3885 // For BitMapKind, this is the bitmap.
3886 ConstantInt *BitMap;
3887 IntegerType *BitMapElementTy;
3889 // For LinearMapKind, these are the constants used to derive the value.
3890 ConstantInt *LinearOffset;
3891 ConstantInt *LinearMultiplier;
3893 // For ArrayKind, this is the array.
3894 GlobalVariable *Array;
3898 SwitchLookupTable::SwitchLookupTable(
3899 Module &M, uint64_t TableSize, ConstantInt *Offset,
3900 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3901 Constant *DefaultValue, const DataLayout &DL)
3902 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3903 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3904 assert(Values.size() && "Can't build lookup table without values!");
3905 assert(TableSize >= Values.size() && "Can't fit values in table!");
3907 // If all values in the table are equal, this is that value.
3908 SingleValue = Values.begin()->second;
3910 Type *ValueType = Values.begin()->second->getType();
3912 // Build up the table contents.
3913 SmallVector<Constant*, 64> TableContents(TableSize);
3914 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3915 ConstantInt *CaseVal = Values[I].first;
3916 Constant *CaseRes = Values[I].second;
3917 assert(CaseRes->getType() == ValueType);
3919 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3921 TableContents[Idx] = CaseRes;
3923 if (CaseRes != SingleValue)
3924 SingleValue = nullptr;
3927 // Fill in any holes in the table with the default result.
3928 if (Values.size() < TableSize) {
3929 assert(DefaultValue &&
3930 "Need a default value to fill the lookup table holes.");
3931 assert(DefaultValue->getType() == ValueType);
3932 for (uint64_t I = 0; I < TableSize; ++I) {
3933 if (!TableContents[I])
3934 TableContents[I] = DefaultValue;
3937 if (DefaultValue != SingleValue)
3938 SingleValue = nullptr;
3941 // If each element in the table contains the same value, we only need to store
3942 // that single value.
3944 Kind = SingleValueKind;
3948 // Check if we can derive the value with a linear transformation from the
3950 if (isa<IntegerType>(ValueType)) {
3951 bool LinearMappingPossible = true;
3954 assert(TableSize >= 2 && "Should be a SingleValue table.");
3955 // Check if there is the same distance between two consecutive values.
3956 for (uint64_t I = 0; I < TableSize; ++I) {
3957 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3959 // This is an undef. We could deal with it, but undefs in lookup tables
3960 // are very seldom. It's probably not worth the additional complexity.
3961 LinearMappingPossible = false;
3964 APInt Val = ConstVal->getValue();
3966 APInt Dist = Val - PrevVal;
3969 } else if (Dist != DistToPrev) {
3970 LinearMappingPossible = false;
3976 if (LinearMappingPossible) {
3977 LinearOffset = cast<ConstantInt>(TableContents[0]);
3978 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3979 Kind = LinearMapKind;
3985 // If the type is integer and the table fits in a register, build a bitmap.
3986 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3987 IntegerType *IT = cast<IntegerType>(ValueType);
3988 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3989 for (uint64_t I = TableSize; I > 0; --I) {
3990 TableInt <<= IT->getBitWidth();
3991 // Insert values into the bitmap. Undef values are set to zero.
3992 if (!isa<UndefValue>(TableContents[I - 1])) {
3993 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3994 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3997 BitMap = ConstantInt::get(M.getContext(), TableInt);
3998 BitMapElementTy = IT;
4004 // Store the table in an array.
4005 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4006 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4008 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4009 GlobalVariable::PrivateLinkage,
4012 Array->setUnnamedAddr(true);
4016 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
4018 case SingleValueKind:
4020 case LinearMapKind: {
4021 // Derive the result value from the input value.
4022 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4023 false, "switch.idx.cast");
4024 if (!LinearMultiplier->isOne())
4025 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4026 if (!LinearOffset->isZero())
4027 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4031 // Type of the bitmap (e.g. i59).
4032 IntegerType *MapTy = BitMap->getType();
4034 // Cast Index to the same type as the bitmap.
4035 // Note: The Index is <= the number of elements in the table, so
4036 // truncating it to the width of the bitmask is safe.
4037 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
4039 // Multiply the shift amount by the element width.
4040 ShiftAmt = Builder.CreateMul(ShiftAmt,
4041 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4045 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4046 "switch.downshift");
4048 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4052 // Make sure the table index will not overflow when treated as signed.
4053 IntegerType *IT = cast<IntegerType>(Index->getType());
4054 uint64_t TableSize = Array->getInitializer()->getType()
4055 ->getArrayNumElements();
4056 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4057 Index = Builder.CreateZExt(Index,
4058 IntegerType::get(IT->getContext(),
4059 IT->getBitWidth() + 1),
4060 "switch.tableidx.zext");
4062 Value *GEPIndices[] = { Builder.getInt32(0), Index };
4063 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4064 GEPIndices, "switch.gep");
4065 return Builder.CreateLoad(GEP, "switch.load");
4068 llvm_unreachable("Unknown lookup table kind!");
4071 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
4073 Type *ElementType) {
4074 auto *IT = dyn_cast<IntegerType>(ElementType);
4077 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4078 // are <= 15, we could try to narrow the type.
4080 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4081 if (TableSize >= UINT_MAX/IT->getBitWidth())
4083 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
4086 /// Determine whether a lookup table should be built for this switch, based on
4087 /// the number of cases, size of the table, and the types of the results.
4089 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4090 const TargetTransformInfo &TTI, const DataLayout &DL,
4091 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
4092 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4093 return false; // TableSize overflowed, or mul below might overflow.
4095 bool AllTablesFitInRegister = true;
4096 bool HasIllegalType = false;
4097 for (const auto &I : ResultTypes) {
4098 Type *Ty = I.second;
4100 // Saturate this flag to true.
4101 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
4103 // Saturate this flag to false.
4104 AllTablesFitInRegister = AllTablesFitInRegister &&
4105 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
4107 // If both flags saturate, we're done. NOTE: This *only* works with
4108 // saturating flags, and all flags have to saturate first due to the
4109 // non-deterministic behavior of iterating over a dense map.
4110 if (HasIllegalType && !AllTablesFitInRegister)
4114 // If each table would fit in a register, we should build it anyway.
4115 if (AllTablesFitInRegister)
4118 // Don't build a table that doesn't fit in-register if it has illegal types.
4122 // The table density should be at least 40%. This is the same criterion as for
4123 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4124 // FIXME: Find the best cut-off.
4125 return SI->getNumCases() * 10 >= TableSize * 4;
4128 /// Try to reuse the switch table index compare. Following pattern:
4130 /// if (idx < tablesize)
4131 /// r = table[idx]; // table does not contain default_value
4133 /// r = default_value;
4134 /// if (r != default_value)
4137 /// Is optimized to:
4139 /// cond = idx < tablesize;
4143 /// r = default_value;
4147 /// Jump threading will then eliminate the second if(cond).
4148 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4149 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4150 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4152 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4156 // We require that the compare is in the same block as the phi so that jump
4157 // threading can do its work afterwards.
4158 if (CmpInst->getParent() != PhiBlock)
4161 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4165 Value *RangeCmp = RangeCheckBranch->getCondition();
4166 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4167 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4169 // Check if the compare with the default value is constant true or false.
4170 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4171 DefaultValue, CmpOp1, true);
4172 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4175 // Check if the compare with the case values is distinct from the default
4177 for (auto ValuePair : Values) {
4178 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4179 ValuePair.second, CmpOp1, true);
4180 if (!CaseConst || CaseConst == DefaultConst)
4182 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4183 "Expect true or false as compare result.");
4186 // Check if the branch instruction dominates the phi node. It's a simple
4187 // dominance check, but sufficient for our needs.
4188 // Although this check is invariant in the calling loops, it's better to do it
4189 // at this late stage. Practically we do it at most once for a switch.
4190 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4191 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4192 BasicBlock *Pred = *PI;
4193 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4197 if (DefaultConst == FalseConst) {
4198 // The compare yields the same result. We can replace it.
4199 CmpInst->replaceAllUsesWith(RangeCmp);
4200 ++NumTableCmpReuses;
4202 // The compare yields the same result, just inverted. We can replace it.
4203 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4204 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4206 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4207 ++NumTableCmpReuses;
4211 /// If the switch is only used to initialize one or more phi nodes in a common
4212 /// successor block with different constant values, replace the switch with
4214 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4215 const DataLayout &DL,
4216 const TargetTransformInfo &TTI) {
4217 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4219 // Only build lookup table when we have a target that supports it.
4220 if (!TTI.shouldBuildLookupTables())
4223 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4224 // split off a dense part and build a lookup table for that.
4226 // FIXME: This creates arrays of GEPs to constant strings, which means each
4227 // GEP needs a runtime relocation in PIC code. We should just build one big
4228 // string and lookup indices into that.
4230 // Ignore switches with less than three cases. Lookup tables will not make them
4231 // faster, so we don't analyze them.
4232 if (SI->getNumCases() < 3)
4235 // Figure out the corresponding result for each case value and phi node in the
4236 // common destination, as well as the min and max case values.
4237 assert(SI->case_begin() != SI->case_end());
4238 SwitchInst::CaseIt CI = SI->case_begin();
4239 ConstantInt *MinCaseVal = CI.getCaseValue();
4240 ConstantInt *MaxCaseVal = CI.getCaseValue();
4242 BasicBlock *CommonDest = nullptr;
4243 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4244 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4245 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4246 SmallDenseMap<PHINode*, Type*> ResultTypes;
4247 SmallVector<PHINode*, 4> PHIs;
4249 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4250 ConstantInt *CaseVal = CI.getCaseValue();
4251 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4252 MinCaseVal = CaseVal;
4253 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4254 MaxCaseVal = CaseVal;
4256 // Resulting value at phi nodes for this case value.
4257 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4259 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4263 // Append the result from this case to the list for each phi.
4264 for (const auto &I : Results) {
4265 PHINode *PHI = I.first;
4266 Constant *Value = I.second;
4267 if (!ResultLists.count(PHI))
4268 PHIs.push_back(PHI);
4269 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4273 // Keep track of the result types.
4274 for (PHINode *PHI : PHIs) {
4275 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4278 uint64_t NumResults = ResultLists[PHIs[0]].size();
4279 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4280 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4281 bool TableHasHoles = (NumResults < TableSize);
4283 // If the table has holes, we need a constant result for the default case
4284 // or a bitmask that fits in a register.
4285 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4286 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4287 &CommonDest, DefaultResultsList, DL);
4289 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4291 // As an extra penalty for the validity test we require more cases.
4292 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4294 if (!DL.fitsInLegalInteger(TableSize))
4298 for (const auto &I : DefaultResultsList) {
4299 PHINode *PHI = I.first;
4300 Constant *Result = I.second;
4301 DefaultResults[PHI] = Result;
4304 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4307 // Create the BB that does the lookups.
4308 Module &Mod = *CommonDest->getParent()->getParent();
4309 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4311 CommonDest->getParent(),
4314 // Compute the table index value.
4315 Builder.SetInsertPoint(SI);
4316 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4319 // Compute the maximum table size representable by the integer type we are
4321 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4322 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4323 assert(MaxTableSize >= TableSize &&
4324 "It is impossible for a switch to have more entries than the max "
4325 "representable value of its input integer type's size.");
4327 // If the default destination is unreachable, or if the lookup table covers
4328 // all values of the conditional variable, branch directly to the lookup table
4329 // BB. Otherwise, check that the condition is within the case range.
4330 const bool DefaultIsReachable =
4331 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4332 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
4333 BranchInst *RangeCheckBranch = nullptr;
4335 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4336 Builder.CreateBr(LookupBB);
4337 // Note: We call removeProdecessor later since we need to be able to get the
4338 // PHI value for the default case in case we're using a bit mask.
4340 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4341 MinCaseVal->getType(), TableSize));
4342 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4345 // Populate the BB that does the lookups.
4346 Builder.SetInsertPoint(LookupBB);
4349 // Before doing the lookup we do the hole check.
4350 // The LookupBB is therefore re-purposed to do the hole check
4351 // and we create a new LookupBB.
4352 BasicBlock *MaskBB = LookupBB;
4353 MaskBB->setName("switch.hole_check");
4354 LookupBB = BasicBlock::Create(Mod.getContext(),
4356 CommonDest->getParent(),
4359 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4360 // unnecessary illegal types.
4361 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4362 APInt MaskInt(TableSizePowOf2, 0);
4363 APInt One(TableSizePowOf2, 1);
4364 // Build bitmask; fill in a 1 bit for every case.
4365 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4366 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4367 uint64_t Idx = (ResultList[I].first->getValue() -
4368 MinCaseVal->getValue()).getLimitedValue();
4369 MaskInt |= One << Idx;
4371 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4373 // Get the TableIndex'th bit of the bitmask.
4374 // If this bit is 0 (meaning hole) jump to the default destination,
4375 // else continue with table lookup.
4376 IntegerType *MapTy = TableMask->getType();
4377 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4378 "switch.maskindex");
4379 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4381 Value *LoBit = Builder.CreateTrunc(Shifted,
4382 Type::getInt1Ty(Mod.getContext()),
4384 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4386 Builder.SetInsertPoint(LookupBB);
4387 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4390 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4391 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4392 // do not delete PHINodes here.
4393 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4394 /*DontDeleteUselessPHIs=*/true);
4397 bool ReturnedEarly = false;
4398 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4399 PHINode *PHI = PHIs[I];
4400 const ResultListTy &ResultList = ResultLists[PHI];
4402 // If using a bitmask, use any value to fill the lookup table holes.
4403 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4404 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4406 Value *Result = Table.BuildLookup(TableIndex, Builder);
4408 // If the result is used to return immediately from the function, we want to
4409 // do that right here.
4410 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4411 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4412 Builder.CreateRet(Result);
4413 ReturnedEarly = true;
4417 // Do a small peephole optimization: re-use the switch table compare if
4419 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4420 BasicBlock *PhiBlock = PHI->getParent();
4421 // Search for compare instructions which use the phi.
4422 for (auto *User : PHI->users()) {
4423 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4427 PHI->addIncoming(Result, LookupBB);
4431 Builder.CreateBr(CommonDest);
4433 // Remove the switch.
4434 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4435 BasicBlock *Succ = SI->getSuccessor(i);
4437 if (Succ == SI->getDefaultDest())
4439 Succ->removePredecessor(SI->getParent());
4441 SI->eraseFromParent();
4445 ++NumLookupTablesHoles;
4449 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4450 BasicBlock *BB = SI->getParent();
4452 if (isValueEqualityComparison(SI)) {
4453 // If we only have one predecessor, and if it is a branch on this value,
4454 // see if that predecessor totally determines the outcome of this switch.
4455 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4456 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4457 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4459 Value *Cond = SI->getCondition();
4460 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4461 if (SimplifySwitchOnSelect(SI, Select))
4462 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4464 // If the block only contains the switch, see if we can fold the block
4465 // away into any preds.
4466 BasicBlock::iterator BBI = BB->begin();
4467 // Ignore dbg intrinsics.
4468 while (isa<DbgInfoIntrinsic>(BBI))
4471 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4472 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4475 // Try to transform the switch into an icmp and a branch.
4476 if (TurnSwitchRangeIntoICmp(SI, Builder))
4477 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4479 // Remove unreachable cases.
4480 if (EliminateDeadSwitchCases(SI, AC, DL))
4481 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4483 if (SwitchToSelect(SI, Builder, AC, DL))
4484 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4486 if (ForwardSwitchConditionToPHI(SI))
4487 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4489 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4490 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4495 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4496 BasicBlock *BB = IBI->getParent();
4497 bool Changed = false;
4499 // Eliminate redundant destinations.
4500 SmallPtrSet<Value *, 8> Succs;
4501 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4502 BasicBlock *Dest = IBI->getDestination(i);
4503 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4504 Dest->removePredecessor(BB);
4505 IBI->removeDestination(i);
4511 if (IBI->getNumDestinations() == 0) {
4512 // If the indirectbr has no successors, change it to unreachable.
4513 new UnreachableInst(IBI->getContext(), IBI);
4514 EraseTerminatorInstAndDCECond(IBI);
4518 if (IBI->getNumDestinations() == 1) {
4519 // If the indirectbr has one successor, change it to a direct branch.
4520 BranchInst::Create(IBI->getDestination(0), IBI);
4521 EraseTerminatorInstAndDCECond(IBI);
4525 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4526 if (SimplifyIndirectBrOnSelect(IBI, SI))
4527 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4532 /// Given an block with only a single landing pad and a unconditional branch
4533 /// try to find another basic block which this one can be merged with. This
4534 /// handles cases where we have multiple invokes with unique landing pads, but
4535 /// a shared handler.
4537 /// We specifically choose to not worry about merging non-empty blocks
4538 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4539 /// practice, the optimizer produces empty landing pad blocks quite frequently
4540 /// when dealing with exception dense code. (see: instcombine, gvn, if-else
4541 /// sinking in this file)
4543 /// This is primarily a code size optimization. We need to avoid performing
4544 /// any transform which might inhibit optimization (such as our ability to
4545 /// specialize a particular handler via tail commoning). We do this by not
4546 /// merging any blocks which require us to introduce a phi. Since the same
4547 /// values are flowing through both blocks, we don't loose any ability to
4548 /// specialize. If anything, we make such specialization more likely.
4550 /// TODO - This transformation could remove entries from a phi in the target
4551 /// block when the inputs in the phi are the same for the two blocks being
4552 /// merged. In some cases, this could result in removal of the PHI entirely.
4553 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4555 auto Succ = BB->getUniqueSuccessor();
4557 // If there's a phi in the successor block, we'd likely have to introduce
4558 // a phi into the merged landing pad block.
4559 if (isa<PHINode>(*Succ->begin()))
4562 for (BasicBlock *OtherPred : predecessors(Succ)) {
4563 if (BB == OtherPred)
4565 BasicBlock::iterator I = OtherPred->begin();
4566 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4567 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4569 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4570 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4571 if (!BI2 || !BI2->isIdenticalTo(BI))
4574 // We've found an identical block. Update our predeccessors to take that
4575 // path instead and make ourselves dead.
4576 SmallSet<BasicBlock *, 16> Preds;
4577 Preds.insert(pred_begin(BB), pred_end(BB));
4578 for (BasicBlock *Pred : Preds) {
4579 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4580 assert(II->getNormalDest() != BB &&
4581 II->getUnwindDest() == BB && "unexpected successor");
4582 II->setUnwindDest(OtherPred);
4585 // The debug info in OtherPred doesn't cover the merged control flow that
4586 // used to go through BB. We need to delete it or update it.
4587 for (auto I = OtherPred->begin(), E = OtherPred->end();
4589 Instruction &Inst = *I; I++;
4590 if (isa<DbgInfoIntrinsic>(Inst))
4591 Inst.eraseFromParent();
4594 SmallSet<BasicBlock *, 16> Succs;
4595 Succs.insert(succ_begin(BB), succ_end(BB));
4596 for (BasicBlock *Succ : Succs) {
4597 Succ->removePredecessor(BB);
4600 IRBuilder<> Builder(BI);
4601 Builder.CreateUnreachable();
4602 BI->eraseFromParent();
4608 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4609 BasicBlock *BB = BI->getParent();
4611 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4614 // If the Terminator is the only non-phi instruction, simplify the block.
4615 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4616 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4617 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4620 // If the only instruction in the block is a seteq/setne comparison
4621 // against a constant, try to simplify the block.
4622 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4623 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4624 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4626 if (I->isTerminator() &&
4627 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4628 BonusInstThreshold, AC))
4632 // See if we can merge an empty landing pad block with another which is
4634 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4635 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4636 if (I->isTerminator() &&
4637 TryToMergeLandingPad(LPad, BI, BB))
4641 // If this basic block is ONLY a compare and a branch, and if a predecessor
4642 // branches to us and our successor, fold the comparison into the
4643 // predecessor and use logical operations to update the incoming value
4644 // for PHI nodes in common successor.
4645 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4646 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4651 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4652 BasicBlock *BB = BI->getParent();
4654 // Conditional branch
4655 if (isValueEqualityComparison(BI)) {
4656 // If we only have one predecessor, and if it is a branch on this value,
4657 // see if that predecessor totally determines the outcome of this
4659 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4660 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4661 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4663 // This block must be empty, except for the setcond inst, if it exists.
4664 // Ignore dbg intrinsics.
4665 BasicBlock::iterator I = BB->begin();
4666 // Ignore dbg intrinsics.
4667 while (isa<DbgInfoIntrinsic>(I))
4670 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4671 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4672 } else if (&*I == cast<Instruction>(BI->getCondition())){
4674 // Ignore dbg intrinsics.
4675 while (isa<DbgInfoIntrinsic>(I))
4677 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4678 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4682 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4683 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
4686 // If this basic block is ONLY a compare and a branch, and if a predecessor
4687 // branches to us and one of our successors, fold the comparison into the
4688 // predecessor and use logical operations to pick the right destination.
4689 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4690 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4692 // We have a conditional branch to two blocks that are only reachable
4693 // from BI. We know that the condbr dominates the two blocks, so see if
4694 // there is any identical code in the "then" and "else" blocks. If so, we
4695 // can hoist it up to the branching block.
4696 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4697 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4698 if (HoistThenElseCodeToIf(BI, TTI))
4699 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4701 // If Successor #1 has multiple preds, we may be able to conditionally
4702 // execute Successor #0 if it branches to Successor #1.
4703 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4704 if (Succ0TI->getNumSuccessors() == 1 &&
4705 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4706 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4707 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4709 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4710 // If Successor #0 has multiple preds, we may be able to conditionally
4711 // execute Successor #1 if it branches to Successor #0.
4712 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4713 if (Succ1TI->getNumSuccessors() == 1 &&
4714 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4715 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4716 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4719 // If this is a branch on a phi node in the current block, thread control
4720 // through this block if any PHI node entries are constants.
4721 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4722 if (PN->getParent() == BI->getParent())
4723 if (FoldCondBranchOnPHI(BI, DL))
4724 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4726 // Scan predecessor blocks for conditional branches.
4727 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4728 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4729 if (PBI != BI && PBI->isConditional())
4730 if (SimplifyCondBranchToCondBranch(PBI, BI))
4731 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4736 /// Check if passing a value to an instruction will cause undefined behavior.
4737 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4738 Constant *C = dyn_cast<Constant>(V);
4745 if (C->isNullValue()) {
4746 // Only look at the first use, avoid hurting compile time with long uselists
4747 User *Use = *I->user_begin();
4749 // Now make sure that there are no instructions in between that can alter
4750 // control flow (eg. calls)
4751 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4752 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4755 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4756 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4757 if (GEP->getPointerOperand() == I)
4758 return passingValueIsAlwaysUndefined(V, GEP);
4760 // Look through bitcasts.
4761 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4762 return passingValueIsAlwaysUndefined(V, BC);
4764 // Load from null is undefined.
4765 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4766 if (!LI->isVolatile())
4767 return LI->getPointerAddressSpace() == 0;
4769 // Store to null is undefined.
4770 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4771 if (!SI->isVolatile())
4772 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4777 /// If BB has an incoming value that will always trigger undefined behavior
4778 /// (eg. null pointer dereference), remove the branch leading here.
4779 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4780 for (BasicBlock::iterator i = BB->begin();
4781 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4782 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4783 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4784 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4785 IRBuilder<> Builder(T);
4786 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4787 BB->removePredecessor(PHI->getIncomingBlock(i));
4788 // Turn uncoditional branches into unreachables and remove the dead
4789 // destination from conditional branches.
4790 if (BI->isUnconditional())
4791 Builder.CreateUnreachable();
4793 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4794 BI->getSuccessor(0));
4795 BI->eraseFromParent();
4798 // TODO: SwitchInst.
4804 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4805 bool Changed = false;
4807 assert(BB && BB->getParent() && "Block not embedded in function!");
4808 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4810 // Remove basic blocks that have no predecessors (except the entry block)...
4811 // or that just have themself as a predecessor. These are unreachable.
4812 if ((pred_empty(BB) &&
4813 BB != &BB->getParent()->getEntryBlock()) ||
4814 BB->getSinglePredecessor() == BB) {
4815 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4816 DeleteDeadBlock(BB);
4820 // Check to see if we can constant propagate this terminator instruction
4822 Changed |= ConstantFoldTerminator(BB, true);
4824 // Check for and eliminate duplicate PHI nodes in this block.
4825 Changed |= EliminateDuplicatePHINodes(BB);
4827 // Check for and remove branches that will always cause undefined behavior.
4828 Changed |= removeUndefIntroducingPredecessor(BB);
4830 // Merge basic blocks into their predecessor if there is only one distinct
4831 // pred, and if there is only one distinct successor of the predecessor, and
4832 // if there are no PHI nodes.
4834 if (MergeBlockIntoPredecessor(BB))
4837 IRBuilder<> Builder(BB);
4839 // If there is a trivial two-entry PHI node in this basic block, and we can
4840 // eliminate it, do so now.
4841 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4842 if (PN->getNumIncomingValues() == 2)
4843 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
4845 Builder.SetInsertPoint(BB->getTerminator());
4846 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4847 if (BI->isUnconditional()) {
4848 if (SimplifyUncondBranch(BI, Builder)) return true;
4850 if (SimplifyCondBranch(BI, Builder)) return true;
4852 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4853 if (SimplifyReturn(RI, Builder)) return true;
4854 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4855 if (SimplifyResume(RI, Builder)) return true;
4856 } else if (CleanupReturnInst *RI =
4857 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
4858 if (SimplifyCleanupReturn(RI)) return true;
4859 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4860 if (SimplifySwitch(SI, Builder)) return true;
4861 } else if (UnreachableInst *UI =
4862 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4863 if (SimplifyUnreachable(UI)) return true;
4864 } else if (IndirectBrInst *IBI =
4865 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4866 if (SimplifyIndirectBr(IBI)) return true;
4872 /// This function is used to do simplification of a CFG.
4873 /// For example, it adjusts branches to branches to eliminate the extra hop,
4874 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4875 /// of the CFG. It returns true if a modification was made.
4877 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4878 unsigned BonusInstThreshold, AssumptionCache *AC) {
4879 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
4880 BonusInstThreshold, AC).run(BB);