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 static cl::opt<unsigned>
57 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
61 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
65 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
68 static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
72 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
73 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
74 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
75 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
76 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
77 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
80 // The first field contains the value that the switch produces when a certain
81 // case group is selected, and the second field is a vector containing the cases
82 // composing the case group.
83 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
84 SwitchCaseResultVectorTy;
85 // The first field contains the phi node that generates a result of the switch
86 // and the second field contains the value generated for a certain case in the switch
88 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
90 /// ValueEqualityComparisonCase - Represents a case of a switch.
91 struct ValueEqualityComparisonCase {
95 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
96 : Value(Value), Dest(Dest) {}
98 bool operator<(ValueEqualityComparisonCase RHS) const {
99 // Comparing pointers is ok as we only rely on the order for uniquing.
100 return Value < RHS.Value;
103 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
106 class SimplifyCFGOpt {
107 const TargetTransformInfo &TTI;
108 unsigned BonusInstThreshold;
109 const DataLayout *const DL;
110 AssumptionTracker *AT;
111 Value *isValueEqualityComparison(TerminatorInst *TI);
112 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
113 std::vector<ValueEqualityComparisonCase> &Cases);
114 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
116 IRBuilder<> &Builder);
117 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
118 IRBuilder<> &Builder);
120 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
121 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
122 bool SimplifyUnreachable(UnreachableInst *UI);
123 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
124 bool SimplifyIndirectBr(IndirectBrInst *IBI);
125 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
126 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
129 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
130 const DataLayout *DL, AssumptionTracker *AT)
131 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
132 bool run(BasicBlock *BB);
136 /// SafeToMergeTerminators - Return true if it is safe to merge these two
137 /// terminator instructions together.
139 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
140 if (SI1 == SI2) return false; // Can't merge with self!
142 // It is not safe to merge these two switch instructions if they have a common
143 // successor, and if that successor has a PHI node, and if *that* PHI node has
144 // conflicting incoming values from the two switch blocks.
145 BasicBlock *SI1BB = SI1->getParent();
146 BasicBlock *SI2BB = SI2->getParent();
147 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
149 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
150 if (SI1Succs.count(*I))
151 for (BasicBlock::iterator BBI = (*I)->begin();
152 isa<PHINode>(BBI); ++BBI) {
153 PHINode *PN = cast<PHINode>(BBI);
154 if (PN->getIncomingValueForBlock(SI1BB) !=
155 PN->getIncomingValueForBlock(SI2BB))
162 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
163 /// to merge these two terminator instructions together, where SI1 is an
164 /// unconditional branch. PhiNodes will store all PHI nodes in common
167 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
170 SmallVectorImpl<PHINode*> &PhiNodes) {
171 if (SI1 == SI2) return false; // Can't merge with self!
172 assert(SI1->isUnconditional() && SI2->isConditional());
174 // We fold the unconditional branch if we can easily update all PHI nodes in
175 // common successors:
176 // 1> We have a constant incoming value for the conditional branch;
177 // 2> We have "Cond" as the incoming value for the unconditional branch;
178 // 3> SI2->getCondition() and Cond have same operands.
179 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
180 if (!Ci2) return false;
181 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
182 Cond->getOperand(1) == Ci2->getOperand(1)) &&
183 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
184 Cond->getOperand(1) == Ci2->getOperand(0)))
187 BasicBlock *SI1BB = SI1->getParent();
188 BasicBlock *SI2BB = SI2->getParent();
189 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
190 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
191 if (SI1Succs.count(*I))
192 for (BasicBlock::iterator BBI = (*I)->begin();
193 isa<PHINode>(BBI); ++BBI) {
194 PHINode *PN = cast<PHINode>(BBI);
195 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
196 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
198 PhiNodes.push_back(PN);
203 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
204 /// now be entries in it from the 'NewPred' block. The values that will be
205 /// flowing into the PHI nodes will be the same as those coming in from
206 /// ExistPred, an existing predecessor of Succ.
207 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
208 BasicBlock *ExistPred) {
209 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
212 for (BasicBlock::iterator I = Succ->begin();
213 (PN = dyn_cast<PHINode>(I)); ++I)
214 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
217 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
218 /// given instruction, which is assumed to be safe to speculate. 1 means
219 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
220 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
221 assert(isSafeToSpeculativelyExecute(I, DL) &&
222 "Instruction is not safe to speculatively execute!");
223 switch (Operator::getOpcode(I)) {
225 // In doubt, be conservative.
227 case Instruction::GetElementPtr:
228 // GEPs are cheap if all indices are constant.
229 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
232 case Instruction::ExtractValue:
233 case Instruction::Load:
234 case Instruction::Add:
235 case Instruction::Sub:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor:
239 case Instruction::Shl:
240 case Instruction::LShr:
241 case Instruction::AShr:
242 case Instruction::ICmp:
243 case Instruction::Trunc:
244 case Instruction::ZExt:
245 case Instruction::SExt:
246 case Instruction::BitCast:
247 case Instruction::ExtractElement:
248 case Instruction::InsertElement:
249 return 1; // These are all cheap.
251 case Instruction::Call:
252 case Instruction::Select:
257 /// DominatesMergePoint - If we have a merge point of an "if condition" as
258 /// accepted above, return true if the specified value dominates the block. We
259 /// don't handle the true generality of domination here, just a special case
260 /// which works well enough for us.
262 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
263 /// see if V (which must be an instruction) and its recursive operands
264 /// that do not dominate BB have a combined cost lower than CostRemaining and
265 /// are non-trapping. If both are true, the instruction is inserted into the
266 /// set and true is returned.
268 /// The cost for most non-trapping instructions is defined as 1 except for
269 /// Select whose cost is 2.
271 /// After this function returns, CostRemaining is decreased by the cost of
272 /// V plus its non-dominating operands. If that cost is greater than
273 /// CostRemaining, false is returned and CostRemaining is undefined.
274 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
275 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
276 unsigned &CostRemaining,
277 const DataLayout *DL) {
278 Instruction *I = dyn_cast<Instruction>(V);
280 // Non-instructions all dominate instructions, but not all constantexprs
281 // can be executed unconditionally.
282 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
287 BasicBlock *PBB = I->getParent();
289 // We don't want to allow weird loops that might have the "if condition" in
290 // the bottom of this block.
291 if (PBB == BB) return false;
293 // If this instruction is defined in a block that contains an unconditional
294 // branch to BB, then it must be in the 'conditional' part of the "if
295 // statement". If not, it definitely dominates the region.
296 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
297 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
300 // If we aren't allowing aggressive promotion anymore, then don't consider
301 // instructions in the 'if region'.
302 if (!AggressiveInsts) return false;
304 // If we have seen this instruction before, don't count it again.
305 if (AggressiveInsts->count(I)) return true;
307 // Okay, it looks like the instruction IS in the "condition". Check to
308 // see if it's a cheap instruction to unconditionally compute, and if it
309 // only uses stuff defined outside of the condition. If so, hoist it out.
310 if (!isSafeToSpeculativelyExecute(I, DL))
313 unsigned Cost = ComputeSpeculationCost(I, DL);
315 if (Cost > CostRemaining)
318 CostRemaining -= Cost;
320 // Okay, we can only really hoist these out if their operands do
321 // not take us over the cost threshold.
322 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
323 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
325 // Okay, it's safe to do this! Remember this instruction.
326 AggressiveInsts->insert(I);
330 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
331 /// and PointerNullValue. Return NULL if value is not a constant int.
332 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
333 // Normal constant int.
334 ConstantInt *CI = dyn_cast<ConstantInt>(V);
335 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
338 // This is some kind of pointer constant. Turn it into a pointer-sized
339 // ConstantInt if possible.
340 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
342 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
343 if (isa<ConstantPointerNull>(V))
344 return ConstantInt::get(PtrTy, 0);
346 // IntToPtr const int.
347 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
348 if (CE->getOpcode() == Instruction::IntToPtr)
349 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
350 // The constant is very likely to have the right type already.
351 if (CI->getType() == PtrTy)
354 return cast<ConstantInt>
355 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
362 /// Given a chain of or (||) or and (&&) comparison of a value against a
363 /// constant, this will try to recover the information required for a switch
365 /// It will depth-first traverse the chain of comparison, seeking for patterns
366 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
367 /// representing the different cases for the switch.
368 /// Note that if the chain is composed of '||' it will build the set of elements
369 /// that matches the comparisons (i.e. any of this value validate the chain)
370 /// while for a chain of '&&' it will build the set elements that make the test
372 struct ConstantComparesGatherer {
374 Value *CompValue; /// Value found for the switch comparison
375 Value *Extra; /// Extra clause to be checked before the switch
376 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
377 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
379 /// Construct and compute the result for the comparison instruction Cond
380 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
381 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
386 ConstantComparesGatherer(const ConstantComparesGatherer &)
387 LLVM_DELETED_FUNCTION;
388 ConstantComparesGatherer &
389 operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION;
393 /// Try to set the current value used for the comparison, it succeeds only if
394 /// it wasn't set before or if the new value is the same as the old one
395 bool setValueOnce(Value *NewVal) {
396 if(CompValue && CompValue != NewVal) return false;
398 return (CompValue != nullptr);
401 /// Try to match Instruction "I" as a comparison against a constant and
402 /// populates the array Vals with the set of values that match (or do not
403 /// match depending on isEQ).
404 /// Return false on failure. On success, the Value the comparison matched
405 /// against is placed in CompValue.
406 /// If CompValue is already set, the function is expected to fail if a match
407 /// is found but the value compared to is different.
408 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
409 // If this is an icmp against a constant, handle this as one of the cases.
412 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
413 (C = GetConstantInt(I->getOperand(1), DL)))) {
420 // Pattern match a special case
421 // (x & ~2^x) == y --> x == y || x == y|2^x
422 // This undoes a transformation done by instcombine to fuse 2 compares.
423 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
424 if (match(ICI->getOperand(0),
425 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
426 APInt Not = ~RHSC->getValue();
427 if (Not.isPowerOf2()) {
428 // If we already have a value for the switch, it has to match!
429 if(!setValueOnce(RHSVal))
433 Vals.push_back(ConstantInt::get(C->getContext(),
434 C->getValue() | Not));
440 // If we already have a value for the switch, it has to match!
441 if(!setValueOnce(ICI->getOperand(0)))
446 return ICI->getOperand(0);
449 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
450 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
453 // Shift the range if the compare is fed by an add. This is the range
454 // compare idiom as emitted by instcombine.
455 Value *CandidateVal = I->getOperand(0);
456 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
457 Span = Span.subtract(RHSC->getValue());
458 CandidateVal = RHSVal;
461 // If this is an and/!= check, then we are looking to build the set of
462 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
465 Span = Span.inverse();
467 // If there are a ton of values, we don't want to make a ginormous switch.
468 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
472 // If we already have a value for the switch, it has to match!
473 if(!setValueOnce(CandidateVal))
476 // Add all values from the range to the set
477 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
478 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
485 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
486 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
487 /// the value being compared, and stick the list constants into the Vals
489 /// One "Extra" case is allowed to differ from the other.
490 void gather(Value *V, const DataLayout *DL) {
491 Instruction *I = dyn_cast<Instruction>(V);
492 bool isEQ = (I->getOpcode() == Instruction::Or);
494 // Keep a stack (SmallVector for efficiency) for depth-first traversal
495 SmallVector<Value *, 8> DFT;
500 while(!DFT.empty()) {
501 V = DFT.pop_back_val();
503 if (Instruction *I = dyn_cast<Instruction>(V)) {
504 // If it is a || (or && depending on isEQ), process the operands.
505 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
506 DFT.push_back(I->getOperand(1));
507 DFT.push_back(I->getOperand(0));
511 // Try to match the current instruction
512 if (matchInstruction(I, DL, isEQ))
513 // Match succeed, continue the loop
517 // One element of the sequence of || (or &&) could not be match as a
518 // comparison against the same value as the others.
519 // We allow only one "Extra" case to be checked before the switch
524 // Failed to parse a proper sequence, abort now
533 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
534 Instruction *Cond = nullptr;
535 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
536 Cond = dyn_cast<Instruction>(SI->getCondition());
537 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
538 if (BI->isConditional())
539 Cond = dyn_cast<Instruction>(BI->getCondition());
540 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
541 Cond = dyn_cast<Instruction>(IBI->getAddress());
544 TI->eraseFromParent();
545 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
548 /// isValueEqualityComparison - Return true if the specified terminator checks
549 /// to see if a value is equal to constant integer value.
550 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
552 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
553 // Do not permit merging of large switch instructions into their
554 // predecessors unless there is only one predecessor.
555 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
556 pred_end(SI->getParent())) <= 128)
557 CV = SI->getCondition();
558 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
559 if (BI->isConditional() && BI->getCondition()->hasOneUse())
560 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
561 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
562 CV = ICI->getOperand(0);
564 // Unwrap any lossless ptrtoint cast.
566 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
567 Value *Ptr = PTII->getPointerOperand();
568 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
575 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
576 /// decode all of the 'cases' that it represents and return the 'default' block.
577 BasicBlock *SimplifyCFGOpt::
578 GetValueEqualityComparisonCases(TerminatorInst *TI,
579 std::vector<ValueEqualityComparisonCase>
581 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
582 Cases.reserve(SI->getNumCases());
583 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
584 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
585 i.getCaseSuccessor()));
586 return SI->getDefaultDest();
589 BranchInst *BI = cast<BranchInst>(TI);
590 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
591 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
592 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
595 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
599 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
600 /// in the list that match the specified block.
601 static void EliminateBlockCases(BasicBlock *BB,
602 std::vector<ValueEqualityComparisonCase> &Cases) {
603 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
606 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
609 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
610 std::vector<ValueEqualityComparisonCase > &C2) {
611 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
613 // Make V1 be smaller than V2.
614 if (V1->size() > V2->size())
617 if (V1->size() == 0) return false;
618 if (V1->size() == 1) {
620 ConstantInt *TheVal = (*V1)[0].Value;
621 for (unsigned i = 0, e = V2->size(); i != e; ++i)
622 if (TheVal == (*V2)[i].Value)
626 // Otherwise, just sort both lists and compare element by element.
627 array_pod_sort(V1->begin(), V1->end());
628 array_pod_sort(V2->begin(), V2->end());
629 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
630 while (i1 != e1 && i2 != e2) {
631 if ((*V1)[i1].Value == (*V2)[i2].Value)
633 if ((*V1)[i1].Value < (*V2)[i2].Value)
641 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
642 /// terminator instruction and its block is known to only have a single
643 /// predecessor block, check to see if that predecessor is also a value
644 /// comparison with the same value, and if that comparison determines the
645 /// outcome of this comparison. If so, simplify TI. This does a very limited
646 /// form of jump threading.
647 bool SimplifyCFGOpt::
648 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
650 IRBuilder<> &Builder) {
651 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
652 if (!PredVal) return false; // Not a value comparison in predecessor.
654 Value *ThisVal = isValueEqualityComparison(TI);
655 assert(ThisVal && "This isn't a value comparison!!");
656 if (ThisVal != PredVal) return false; // Different predicates.
658 // TODO: Preserve branch weight metadata, similarly to how
659 // FoldValueComparisonIntoPredecessors preserves it.
661 // Find out information about when control will move from Pred to TI's block.
662 std::vector<ValueEqualityComparisonCase> PredCases;
663 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
665 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
667 // Find information about how control leaves this block.
668 std::vector<ValueEqualityComparisonCase> ThisCases;
669 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
670 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
672 // If TI's block is the default block from Pred's comparison, potentially
673 // simplify TI based on this knowledge.
674 if (PredDef == TI->getParent()) {
675 // If we are here, we know that the value is none of those cases listed in
676 // PredCases. If there are any cases in ThisCases that are in PredCases, we
678 if (!ValuesOverlap(PredCases, ThisCases))
681 if (isa<BranchInst>(TI)) {
682 // Okay, one of the successors of this condbr is dead. Convert it to a
684 assert(ThisCases.size() == 1 && "Branch can only have one case!");
685 // Insert the new branch.
686 Instruction *NI = Builder.CreateBr(ThisDef);
689 // Remove PHI node entries for the dead edge.
690 ThisCases[0].Dest->removePredecessor(TI->getParent());
692 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
693 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
695 EraseTerminatorInstAndDCECond(TI);
699 SwitchInst *SI = cast<SwitchInst>(TI);
700 // Okay, TI has cases that are statically dead, prune them away.
701 SmallPtrSet<Constant*, 16> DeadCases;
702 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
703 DeadCases.insert(PredCases[i].Value);
705 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
706 << "Through successor TI: " << *TI);
708 // Collect branch weights into a vector.
709 SmallVector<uint32_t, 8> Weights;
710 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
711 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
713 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
715 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
717 Weights.push_back(CI->getValue().getZExtValue());
719 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
721 if (DeadCases.count(i.getCaseValue())) {
723 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
726 i.getCaseSuccessor()->removePredecessor(TI->getParent());
730 if (HasWeight && Weights.size() >= 2)
731 SI->setMetadata(LLVMContext::MD_prof,
732 MDBuilder(SI->getParent()->getContext()).
733 createBranchWeights(Weights));
735 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
739 // Otherwise, TI's block must correspond to some matched value. Find out
740 // which value (or set of values) this is.
741 ConstantInt *TIV = nullptr;
742 BasicBlock *TIBB = TI->getParent();
743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].Dest == TIBB) {
746 return false; // Cannot handle multiple values coming to this block.
747 TIV = PredCases[i].Value;
749 assert(TIV && "No edge from pred to succ?");
751 // Okay, we found the one constant that our value can be if we get into TI's
752 // BB. Find out which successor will unconditionally be branched to.
753 BasicBlock *TheRealDest = nullptr;
754 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
755 if (ThisCases[i].Value == TIV) {
756 TheRealDest = ThisCases[i].Dest;
760 // If not handled by any explicit cases, it is handled by the default case.
761 if (!TheRealDest) TheRealDest = ThisDef;
763 // Remove PHI node entries for dead edges.
764 BasicBlock *CheckEdge = TheRealDest;
765 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
766 if (*SI != CheckEdge)
767 (*SI)->removePredecessor(TIBB);
771 // Insert the new branch.
772 Instruction *NI = Builder.CreateBr(TheRealDest);
775 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
776 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
778 EraseTerminatorInstAndDCECond(TI);
783 /// ConstantIntOrdering - This class implements a stable ordering of constant
784 /// integers that does not depend on their address. This is important for
785 /// applications that sort ConstantInt's to ensure uniqueness.
786 struct ConstantIntOrdering {
787 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
788 return LHS->getValue().ult(RHS->getValue());
793 static int ConstantIntSortPredicate(ConstantInt *const *P1,
794 ConstantInt *const *P2) {
795 const ConstantInt *LHS = *P1;
796 const ConstantInt *RHS = *P2;
797 if (LHS->getValue().ult(RHS->getValue()))
799 if (LHS->getValue() == RHS->getValue())
804 static inline bool HasBranchWeights(const Instruction* I) {
805 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
806 if (ProfMD && ProfMD->getOperand(0))
807 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
808 return MDS->getString().equals("branch_weights");
813 /// Get Weights of a given TerminatorInst, the default weight is at the front
814 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
816 static void GetBranchWeights(TerminatorInst *TI,
817 SmallVectorImpl<uint64_t> &Weights) {
818 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
820 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
821 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
822 Weights.push_back(CI->getValue().getZExtValue());
825 // If TI is a conditional eq, the default case is the false case,
826 // and the corresponding branch-weight data is at index 2. We swap the
827 // default weight to be the first entry.
828 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
829 assert(Weights.size() == 2);
830 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
831 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
832 std::swap(Weights.front(), Weights.back());
836 /// Keep halving the weights until all can fit in uint32_t.
837 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
838 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
839 if (Max > UINT_MAX) {
840 unsigned Offset = 32 - countLeadingZeros(Max);
841 for (uint64_t &I : Weights)
846 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
847 /// equality comparison instruction (either a switch or a branch on "X == c").
848 /// See if any of the predecessors of the terminator block are value comparisons
849 /// on the same value. If so, and if safe to do so, fold them together.
850 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
851 IRBuilder<> &Builder) {
852 BasicBlock *BB = TI->getParent();
853 Value *CV = isValueEqualityComparison(TI); // CondVal
854 assert(CV && "Not a comparison?");
855 bool Changed = false;
857 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
858 while (!Preds.empty()) {
859 BasicBlock *Pred = Preds.pop_back_val();
861 // See if the predecessor is a comparison with the same value.
862 TerminatorInst *PTI = Pred->getTerminator();
863 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
865 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
866 // Figure out which 'cases' to copy from SI to PSI.
867 std::vector<ValueEqualityComparisonCase> BBCases;
868 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
870 std::vector<ValueEqualityComparisonCase> PredCases;
871 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
873 // Based on whether the default edge from PTI goes to BB or not, fill in
874 // PredCases and PredDefault with the new switch cases we would like to
876 SmallVector<BasicBlock*, 8> NewSuccessors;
878 // Update the branch weight metadata along the way
879 SmallVector<uint64_t, 8> Weights;
880 bool PredHasWeights = HasBranchWeights(PTI);
881 bool SuccHasWeights = HasBranchWeights(TI);
883 if (PredHasWeights) {
884 GetBranchWeights(PTI, Weights);
885 // branch-weight metadata is inconsistent here.
886 if (Weights.size() != 1 + PredCases.size())
887 PredHasWeights = SuccHasWeights = false;
888 } else if (SuccHasWeights)
889 // If there are no predecessor weights but there are successor weights,
890 // populate Weights with 1, which will later be scaled to the sum of
891 // successor's weights
892 Weights.assign(1 + PredCases.size(), 1);
894 SmallVector<uint64_t, 8> SuccWeights;
895 if (SuccHasWeights) {
896 GetBranchWeights(TI, SuccWeights);
897 // branch-weight metadata is inconsistent here.
898 if (SuccWeights.size() != 1 + BBCases.size())
899 PredHasWeights = SuccHasWeights = false;
900 } else if (PredHasWeights)
901 SuccWeights.assign(1 + BBCases.size(), 1);
903 if (PredDefault == BB) {
904 // If this is the default destination from PTI, only the edges in TI
905 // that don't occur in PTI, or that branch to BB will be activated.
906 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
907 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
908 if (PredCases[i].Dest != BB)
909 PTIHandled.insert(PredCases[i].Value);
911 // The default destination is BB, we don't need explicit targets.
912 std::swap(PredCases[i], PredCases.back());
914 if (PredHasWeights || SuccHasWeights) {
915 // Increase weight for the default case.
916 Weights[0] += Weights[i+1];
917 std::swap(Weights[i+1], Weights.back());
921 PredCases.pop_back();
925 // Reconstruct the new switch statement we will be building.
926 if (PredDefault != BBDefault) {
927 PredDefault->removePredecessor(Pred);
928 PredDefault = BBDefault;
929 NewSuccessors.push_back(BBDefault);
932 unsigned CasesFromPred = Weights.size();
933 uint64_t ValidTotalSuccWeight = 0;
934 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
935 if (!PTIHandled.count(BBCases[i].Value) &&
936 BBCases[i].Dest != BBDefault) {
937 PredCases.push_back(BBCases[i]);
938 NewSuccessors.push_back(BBCases[i].Dest);
939 if (SuccHasWeights || PredHasWeights) {
940 // The default weight is at index 0, so weight for the ith case
941 // should be at index i+1. Scale the cases from successor by
942 // PredDefaultWeight (Weights[0]).
943 Weights.push_back(Weights[0] * SuccWeights[i+1]);
944 ValidTotalSuccWeight += SuccWeights[i+1];
948 if (SuccHasWeights || PredHasWeights) {
949 ValidTotalSuccWeight += SuccWeights[0];
950 // Scale the cases from predecessor by ValidTotalSuccWeight.
951 for (unsigned i = 1; i < CasesFromPred; ++i)
952 Weights[i] *= ValidTotalSuccWeight;
953 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
954 Weights[0] *= SuccWeights[0];
957 // If this is not the default destination from PSI, only the edges
958 // in SI that occur in PSI with a destination of BB will be
960 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
961 std::map<ConstantInt*, uint64_t> WeightsForHandled;
962 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
963 if (PredCases[i].Dest == BB) {
964 PTIHandled.insert(PredCases[i].Value);
966 if (PredHasWeights || SuccHasWeights) {
967 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
968 std::swap(Weights[i+1], Weights.back());
972 std::swap(PredCases[i], PredCases.back());
973 PredCases.pop_back();
977 // Okay, now we know which constants were sent to BB from the
978 // predecessor. Figure out where they will all go now.
979 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
980 if (PTIHandled.count(BBCases[i].Value)) {
981 // If this is one we are capable of getting...
982 if (PredHasWeights || SuccHasWeights)
983 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
984 PredCases.push_back(BBCases[i]);
985 NewSuccessors.push_back(BBCases[i].Dest);
986 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
989 // If there are any constants vectored to BB that TI doesn't handle,
990 // they must go to the default destination of TI.
991 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
993 E = PTIHandled.end(); I != E; ++I) {
994 if (PredHasWeights || SuccHasWeights)
995 Weights.push_back(WeightsForHandled[*I]);
996 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
997 NewSuccessors.push_back(BBDefault);
1001 // Okay, at this point, we know which new successor Pred will get. Make
1002 // sure we update the number of entries in the PHI nodes for these
1004 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
1005 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
1007 Builder.SetInsertPoint(PTI);
1008 // Convert pointer to int before we switch.
1009 if (CV->getType()->isPointerTy()) {
1010 assert(DL && "Cannot switch on pointer without DataLayout");
1011 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
1015 // Now that the successors are updated, create the new Switch instruction.
1016 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1018 NewSI->setDebugLoc(PTI->getDebugLoc());
1019 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1020 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
1022 if (PredHasWeights || SuccHasWeights) {
1023 // Halve the weights if any of them cannot fit in an uint32_t
1024 FitWeights(Weights);
1026 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1028 NewSI->setMetadata(LLVMContext::MD_prof,
1029 MDBuilder(BB->getContext()).
1030 createBranchWeights(MDWeights));
1033 EraseTerminatorInstAndDCECond(PTI);
1035 // Okay, last check. If BB is still a successor of PSI, then we must
1036 // have an infinite loop case. If so, add an infinitely looping block
1037 // to handle the case to preserve the behavior of the code.
1038 BasicBlock *InfLoopBlock = nullptr;
1039 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1040 if (NewSI->getSuccessor(i) == BB) {
1041 if (!InfLoopBlock) {
1042 // Insert it at the end of the function, because it's either code,
1043 // or it won't matter if it's hot. :)
1044 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1045 "infloop", BB->getParent());
1046 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1048 NewSI->setSuccessor(i, InfLoopBlock);
1057 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1058 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1059 // would need to do this), we can't hoist the invoke, as there is nowhere
1060 // to put the select in this case.
1061 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1062 Instruction *I1, Instruction *I2) {
1063 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1065 for (BasicBlock::iterator BBI = SI->begin();
1066 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1067 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1068 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1069 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1077 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1079 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1080 /// BB2, hoist any common code in the two blocks up into the branch block. The
1081 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1082 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1083 // This does very trivial matching, with limited scanning, to find identical
1084 // instructions in the two blocks. In particular, we don't want to get into
1085 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1086 // such, we currently just scan for obviously identical instructions in an
1088 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1089 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1091 BasicBlock::iterator BB1_Itr = BB1->begin();
1092 BasicBlock::iterator BB2_Itr = BB2->begin();
1094 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1095 // Skip debug info if it is not identical.
1096 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1097 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1098 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1099 while (isa<DbgInfoIntrinsic>(I1))
1101 while (isa<DbgInfoIntrinsic>(I2))
1104 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1105 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1108 BasicBlock *BIParent = BI->getParent();
1110 bool Changed = false;
1112 // If we are hoisting the terminator instruction, don't move one (making a
1113 // broken BB), instead clone it, and remove BI.
1114 if (isa<TerminatorInst>(I1))
1115 goto HoistTerminator;
1117 // For a normal instruction, we just move one to right before the branch,
1118 // then replace all uses of the other with the first. Finally, we remove
1119 // the now redundant second instruction.
1120 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1121 if (!I2->use_empty())
1122 I2->replaceAllUsesWith(I1);
1123 I1->intersectOptionalDataWith(I2);
1124 unsigned KnownIDs[] = {
1125 LLVMContext::MD_tbaa,
1126 LLVMContext::MD_range,
1127 LLVMContext::MD_fpmath,
1128 LLVMContext::MD_invariant_load,
1129 LLVMContext::MD_nonnull
1131 combineMetadata(I1, I2, KnownIDs);
1132 I2->eraseFromParent();
1137 // Skip debug info if it is not identical.
1138 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1139 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1140 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1141 while (isa<DbgInfoIntrinsic>(I1))
1143 while (isa<DbgInfoIntrinsic>(I2))
1146 } while (I1->isIdenticalToWhenDefined(I2));
1151 // It may not be possible to hoist an invoke.
1152 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1155 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1157 for (BasicBlock::iterator BBI = SI->begin();
1158 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1159 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1160 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1164 // Check for passingValueIsAlwaysUndefined here because we would rather
1165 // eliminate undefined control flow then converting it to a select.
1166 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1167 passingValueIsAlwaysUndefined(BB2V, PN))
1170 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1172 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1177 // Okay, it is safe to hoist the terminator.
1178 Instruction *NT = I1->clone();
1179 BIParent->getInstList().insert(BI, NT);
1180 if (!NT->getType()->isVoidTy()) {
1181 I1->replaceAllUsesWith(NT);
1182 I2->replaceAllUsesWith(NT);
1186 IRBuilder<true, NoFolder> Builder(NT);
1187 // Hoisting one of the terminators from our successor is a great thing.
1188 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1189 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1190 // nodes, so we insert select instruction to compute the final result.
1191 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1192 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1194 for (BasicBlock::iterator BBI = SI->begin();
1195 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1196 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1197 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1198 if (BB1V == BB2V) continue;
1200 // These values do not agree. Insert a select instruction before NT
1201 // that determines the right value.
1202 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1204 SI = cast<SelectInst>
1205 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1206 BB1V->getName()+"."+BB2V->getName()));
1208 // Make the PHI node use the select for all incoming values for BB1/BB2
1209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1210 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1211 PN->setIncomingValue(i, SI);
1215 // Update any PHI nodes in our new successors.
1216 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1217 AddPredecessorToBlock(*SI, BIParent, BB1);
1219 EraseTerminatorInstAndDCECond(BI);
1223 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1224 /// check whether BBEnd has only two predecessors and the other predecessor
1225 /// ends with an unconditional branch. If it is true, sink any common code
1226 /// in the two predecessors to BBEnd.
1227 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1228 assert(BI1->isUnconditional());
1229 BasicBlock *BB1 = BI1->getParent();
1230 BasicBlock *BBEnd = BI1->getSuccessor(0);
1232 // Check that BBEnd has two predecessors and the other predecessor ends with
1233 // an unconditional branch.
1234 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1235 BasicBlock *Pred0 = *PI++;
1236 if (PI == PE) // Only one predecessor.
1238 BasicBlock *Pred1 = *PI++;
1239 if (PI != PE) // More than two predecessors.
1241 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1242 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1243 if (!BI2 || !BI2->isUnconditional())
1246 // Gather the PHI nodes in BBEnd.
1247 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1248 Instruction *FirstNonPhiInBBEnd = nullptr;
1249 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1251 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1252 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1253 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1254 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1256 FirstNonPhiInBBEnd = &*I;
1260 if (!FirstNonPhiInBBEnd)
1264 // This does very trivial matching, with limited scanning, to find identical
1265 // instructions in the two blocks. We scan backward for obviously identical
1266 // instructions in an identical order.
1267 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1268 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1269 RE2 = BB2->getInstList().rend();
1271 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1274 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1277 // Skip the unconditional branches.
1281 bool Changed = false;
1282 while (RI1 != RE1 && RI2 != RE2) {
1284 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1287 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1291 Instruction *I1 = &*RI1, *I2 = &*RI2;
1292 // I1 and I2 should have a single use in the same PHI node, and they
1293 // perform the same operation.
1294 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1295 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1296 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1297 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1298 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1299 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1300 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1301 !I1->hasOneUse() || !I2->hasOneUse() ||
1302 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1303 MapValueFromBB1ToBB2[I1].first != I2)
1306 // Check whether we should swap the operands of ICmpInst.
1307 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1308 bool SwapOpnds = false;
1309 if (ICmp1 && ICmp2 &&
1310 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1311 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1312 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1313 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1314 ICmp2->swapOperands();
1317 if (!I1->isSameOperationAs(I2)) {
1319 ICmp2->swapOperands();
1323 // The operands should be either the same or they need to be generated
1324 // with a PHI node after sinking. We only handle the case where there is
1325 // a single pair of different operands.
1326 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1327 unsigned Op1Idx = 0;
1328 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1329 if (I1->getOperand(I) == I2->getOperand(I))
1331 // Early exit if we have more-than one pair of different operands or
1332 // the different operand is already in MapValueFromBB1ToBB2.
1333 // Early exit if we need a PHI node to replace a constant.
1335 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1336 MapValueFromBB1ToBB2.end() ||
1337 isa<Constant>(I1->getOperand(I)) ||
1338 isa<Constant>(I2->getOperand(I))) {
1339 // If we can't sink the instructions, undo the swapping.
1341 ICmp2->swapOperands();
1344 DifferentOp1 = I1->getOperand(I);
1346 DifferentOp2 = I2->getOperand(I);
1349 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1350 // remove (I1, I2) from MapValueFromBB1ToBB2.
1352 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1353 DifferentOp1->getName() + ".sink",
1355 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1356 // I1 should use NewPN instead of DifferentOp1.
1357 I1->setOperand(Op1Idx, NewPN);
1358 NewPN->addIncoming(DifferentOp1, BB1);
1359 NewPN->addIncoming(DifferentOp2, BB2);
1360 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1362 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1363 MapValueFromBB1ToBB2.erase(I1);
1365 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1366 DEBUG(dbgs() << " " << *I2 << "\n";);
1367 // We need to update RE1 and RE2 if we are going to sink the first
1368 // instruction in the basic block down.
1369 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1370 // Sink the instruction.
1371 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1372 if (!OldPN->use_empty())
1373 OldPN->replaceAllUsesWith(I1);
1374 OldPN->eraseFromParent();
1376 if (!I2->use_empty())
1377 I2->replaceAllUsesWith(I1);
1378 I1->intersectOptionalDataWith(I2);
1379 // TODO: Use combineMetadata here to preserve what metadata we can
1380 // (analogous to the hoisting case above).
1381 I2->eraseFromParent();
1384 RE1 = BB1->getInstList().rend();
1386 RE2 = BB2->getInstList().rend();
1387 FirstNonPhiInBBEnd = I1;
1394 /// \brief Determine if we can hoist sink a sole store instruction out of a
1395 /// conditional block.
1397 /// We are looking for code like the following:
1399 /// store i32 %add, i32* %arrayidx2
1400 /// ... // No other stores or function calls (we could be calling a memory
1401 /// ... // function).
1402 /// %cmp = icmp ult %x, %y
1403 /// br i1 %cmp, label %EndBB, label %ThenBB
1405 /// store i32 %add5, i32* %arrayidx2
1409 /// We are going to transform this into:
1411 /// store i32 %add, i32* %arrayidx2
1413 /// %cmp = icmp ult %x, %y
1414 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1415 /// store i32 %add.add5, i32* %arrayidx2
1418 /// \return The pointer to the value of the previous store if the store can be
1419 /// hoisted into the predecessor block. 0 otherwise.
1420 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1421 BasicBlock *StoreBB, BasicBlock *EndBB) {
1422 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1426 // Volatile or atomic.
1427 if (!StoreToHoist->isSimple())
1430 Value *StorePtr = StoreToHoist->getPointerOperand();
1432 // Look for a store to the same pointer in BrBB.
1433 unsigned MaxNumInstToLookAt = 10;
1434 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1435 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1436 Instruction *CurI = &*RI;
1438 // Could be calling an instruction that effects memory like free().
1439 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1442 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1443 // Found the previous store make sure it stores to the same location.
1444 if (SI && SI->getPointerOperand() == StorePtr)
1445 // Found the previous store, return its value operand.
1446 return SI->getValueOperand();
1448 return nullptr; // Unknown store.
1454 /// \brief Speculate a conditional basic block flattening the CFG.
1456 /// Note that this is a very risky transform currently. Speculating
1457 /// instructions like this is most often not desirable. Instead, there is an MI
1458 /// pass which can do it with full awareness of the resource constraints.
1459 /// However, some cases are "obvious" and we should do directly. An example of
1460 /// this is speculating a single, reasonably cheap instruction.
1462 /// There is only one distinct advantage to flattening the CFG at the IR level:
1463 /// it makes very common but simplistic optimizations such as are common in
1464 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1465 /// modeling their effects with easier to reason about SSA value graphs.
1468 /// An illustration of this transform is turning this IR:
1471 /// %cmp = icmp ult %x, %y
1472 /// br i1 %cmp, label %EndBB, label %ThenBB
1474 /// %sub = sub %x, %y
1477 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1484 /// %cmp = icmp ult %x, %y
1485 /// %sub = sub %x, %y
1486 /// %cond = select i1 %cmp, 0, %sub
1490 /// \returns true if the conditional block is removed.
1491 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1492 const DataLayout *DL) {
1493 // Be conservative for now. FP select instruction can often be expensive.
1494 Value *BrCond = BI->getCondition();
1495 if (isa<FCmpInst>(BrCond))
1498 BasicBlock *BB = BI->getParent();
1499 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1501 // If ThenBB is actually on the false edge of the conditional branch, remember
1502 // to swap the select operands later.
1503 bool Invert = false;
1504 if (ThenBB != BI->getSuccessor(0)) {
1505 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1508 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1510 // Keep a count of how many times instructions are used within CondBB when
1511 // they are candidates for sinking into CondBB. Specifically:
1512 // - They are defined in BB, and
1513 // - They have no side effects, and
1514 // - All of their uses are in CondBB.
1515 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1517 unsigned SpeculationCost = 0;
1518 Value *SpeculatedStoreValue = nullptr;
1519 StoreInst *SpeculatedStore = nullptr;
1520 for (BasicBlock::iterator BBI = ThenBB->begin(),
1521 BBE = std::prev(ThenBB->end());
1522 BBI != BBE; ++BBI) {
1523 Instruction *I = BBI;
1525 if (isa<DbgInfoIntrinsic>(I))
1528 // Only speculatively execution a single instruction (not counting the
1529 // terminator) for now.
1531 if (SpeculationCost > 1)
1534 // Don't hoist the instruction if it's unsafe or expensive.
1535 if (!isSafeToSpeculativelyExecute(I, DL) &&
1536 !(HoistCondStores &&
1537 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1540 if (!SpeculatedStoreValue &&
1541 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
1544 // Store the store speculation candidate.
1545 if (SpeculatedStoreValue)
1546 SpeculatedStore = cast<StoreInst>(I);
1548 // Do not hoist the instruction if any of its operands are defined but not
1549 // used in BB. The transformation will prevent the operand from
1550 // being sunk into the use block.
1551 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1553 Instruction *OpI = dyn_cast<Instruction>(*i);
1554 if (!OpI || OpI->getParent() != BB ||
1555 OpI->mayHaveSideEffects())
1556 continue; // Not a candidate for sinking.
1558 ++SinkCandidateUseCounts[OpI];
1562 // Consider any sink candidates which are only used in CondBB as costs for
1563 // speculation. Note, while we iterate over a DenseMap here, we are summing
1564 // and so iteration order isn't significant.
1565 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1566 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1568 if (I->first->getNumUses() == I->second) {
1570 if (SpeculationCost > 1)
1574 // Check that the PHI nodes can be converted to selects.
1575 bool HaveRewritablePHIs = false;
1576 for (BasicBlock::iterator I = EndBB->begin();
1577 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1578 Value *OrigV = PN->getIncomingValueForBlock(BB);
1579 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1581 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1582 // Skip PHIs which are trivial.
1586 // Don't convert to selects if we could remove undefined behavior instead.
1587 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1588 passingValueIsAlwaysUndefined(ThenV, PN))
1591 HaveRewritablePHIs = true;
1592 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1593 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1594 if (!OrigCE && !ThenCE)
1595 continue; // Known safe and cheap.
1597 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1598 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1600 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1601 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
1602 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1605 // Account for the cost of an unfolded ConstantExpr which could end up
1606 // getting expanded into Instructions.
1607 // FIXME: This doesn't account for how many operations are combined in the
1608 // constant expression.
1610 if (SpeculationCost > 1)
1614 // If there are no PHIs to process, bail early. This helps ensure idempotence
1616 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1619 // If we get here, we can hoist the instruction and if-convert.
1620 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1622 // Insert a select of the value of the speculated store.
1623 if (SpeculatedStoreValue) {
1624 IRBuilder<true, NoFolder> Builder(BI);
1625 Value *TrueV = SpeculatedStore->getValueOperand();
1626 Value *FalseV = SpeculatedStoreValue;
1628 std::swap(TrueV, FalseV);
1629 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1630 "." + FalseV->getName());
1631 SpeculatedStore->setOperand(0, S);
1634 // Hoist the instructions.
1635 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1636 std::prev(ThenBB->end()));
1638 // Insert selects and rewrite the PHI operands.
1639 IRBuilder<true, NoFolder> Builder(BI);
1640 for (BasicBlock::iterator I = EndBB->begin();
1641 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1642 unsigned OrigI = PN->getBasicBlockIndex(BB);
1643 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1644 Value *OrigV = PN->getIncomingValue(OrigI);
1645 Value *ThenV = PN->getIncomingValue(ThenI);
1647 // Skip PHIs which are trivial.
1651 // Create a select whose true value is the speculatively executed value and
1652 // false value is the preexisting value. Swap them if the branch
1653 // destinations were inverted.
1654 Value *TrueV = ThenV, *FalseV = OrigV;
1656 std::swap(TrueV, FalseV);
1657 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1658 TrueV->getName() + "." + FalseV->getName());
1659 PN->setIncomingValue(OrigI, V);
1660 PN->setIncomingValue(ThenI, V);
1667 /// \returns True if this block contains a CallInst with the NoDuplicate
1669 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1670 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1671 const CallInst *CI = dyn_cast<CallInst>(I);
1674 if (CI->cannotDuplicate())
1680 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1681 /// across this block.
1682 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1683 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1686 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1687 if (isa<DbgInfoIntrinsic>(BBI))
1689 if (Size > 10) return false; // Don't clone large BB's.
1692 // We can only support instructions that do not define values that are
1693 // live outside of the current basic block.
1694 for (User *U : BBI->users()) {
1695 Instruction *UI = cast<Instruction>(U);
1696 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1699 // Looks ok, continue checking.
1705 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1706 /// that is defined in the same block as the branch and if any PHI entries are
1707 /// constants, thread edges corresponding to that entry to be branches to their
1708 /// ultimate destination.
1709 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1710 BasicBlock *BB = BI->getParent();
1711 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1712 // NOTE: we currently cannot transform this case if the PHI node is used
1713 // outside of the block.
1714 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1717 // Degenerate case of a single entry PHI.
1718 if (PN->getNumIncomingValues() == 1) {
1719 FoldSingleEntryPHINodes(PN->getParent());
1723 // Now we know that this block has multiple preds and two succs.
1724 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1726 if (HasNoDuplicateCall(BB)) return false;
1728 // Okay, this is a simple enough basic block. See if any phi values are
1730 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1731 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1732 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1734 // Okay, we now know that all edges from PredBB should be revectored to
1735 // branch to RealDest.
1736 BasicBlock *PredBB = PN->getIncomingBlock(i);
1737 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1739 if (RealDest == BB) continue; // Skip self loops.
1740 // Skip if the predecessor's terminator is an indirect branch.
1741 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1743 // The dest block might have PHI nodes, other predecessors and other
1744 // difficult cases. Instead of being smart about this, just insert a new
1745 // block that jumps to the destination block, effectively splitting
1746 // the edge we are about to create.
1747 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1748 RealDest->getName()+".critedge",
1749 RealDest->getParent(), RealDest);
1750 BranchInst::Create(RealDest, EdgeBB);
1752 // Update PHI nodes.
1753 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1755 // BB may have instructions that are being threaded over. Clone these
1756 // instructions into EdgeBB. We know that there will be no uses of the
1757 // cloned instructions outside of EdgeBB.
1758 BasicBlock::iterator InsertPt = EdgeBB->begin();
1759 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1760 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1761 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1762 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1765 // Clone the instruction.
1766 Instruction *N = BBI->clone();
1767 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1769 // Update operands due to translation.
1770 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1772 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1773 if (PI != TranslateMap.end())
1777 // Check for trivial simplification.
1778 if (Value *V = SimplifyInstruction(N, DL)) {
1779 TranslateMap[BBI] = V;
1780 delete N; // Instruction folded away, don't need actual inst
1782 // Insert the new instruction into its new home.
1783 EdgeBB->getInstList().insert(InsertPt, N);
1784 if (!BBI->use_empty())
1785 TranslateMap[BBI] = N;
1789 // Loop over all of the edges from PredBB to BB, changing them to branch
1790 // to EdgeBB instead.
1791 TerminatorInst *PredBBTI = PredBB->getTerminator();
1792 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1793 if (PredBBTI->getSuccessor(i) == BB) {
1794 BB->removePredecessor(PredBB);
1795 PredBBTI->setSuccessor(i, EdgeBB);
1798 // Recurse, simplifying any other constants.
1799 return FoldCondBranchOnPHI(BI, DL) | true;
1805 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1806 /// PHI node, see if we can eliminate it.
1807 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1808 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1809 // statement", which has a very simple dominance structure. Basically, we
1810 // are trying to find the condition that is being branched on, which
1811 // subsequently causes this merge to happen. We really want control
1812 // dependence information for this check, but simplifycfg can't keep it up
1813 // to date, and this catches most of the cases we care about anyway.
1814 BasicBlock *BB = PN->getParent();
1815 BasicBlock *IfTrue, *IfFalse;
1816 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1818 // Don't bother if the branch will be constant folded trivially.
1819 isa<ConstantInt>(IfCond))
1822 // Okay, we found that we can merge this two-entry phi node into a select.
1823 // Doing so would require us to fold *all* two entry phi nodes in this block.
1824 // At some point this becomes non-profitable (particularly if the target
1825 // doesn't support cmov's). Only do this transformation if there are two or
1826 // fewer PHI nodes in this block.
1827 unsigned NumPhis = 0;
1828 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1832 // Loop over the PHI's seeing if we can promote them all to select
1833 // instructions. While we are at it, keep track of the instructions
1834 // that need to be moved to the dominating block.
1835 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1836 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1837 MaxCostVal1 = PHINodeFoldingThreshold;
1839 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1840 PHINode *PN = cast<PHINode>(II++);
1841 if (Value *V = SimplifyInstruction(PN, DL)) {
1842 PN->replaceAllUsesWith(V);
1843 PN->eraseFromParent();
1847 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1849 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1854 // If we folded the first phi, PN dangles at this point. Refresh it. If
1855 // we ran out of PHIs then we simplified them all.
1856 PN = dyn_cast<PHINode>(BB->begin());
1857 if (!PN) return true;
1859 // Don't fold i1 branches on PHIs which contain binary operators. These can
1860 // often be turned into switches and other things.
1861 if (PN->getType()->isIntegerTy(1) &&
1862 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1863 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1864 isa<BinaryOperator>(IfCond)))
1867 // If we all PHI nodes are promotable, check to make sure that all
1868 // instructions in the predecessor blocks can be promoted as well. If
1869 // not, we won't be able to get rid of the control flow, so it's not
1870 // worth promoting to select instructions.
1871 BasicBlock *DomBlock = nullptr;
1872 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1873 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1874 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1877 DomBlock = *pred_begin(IfBlock1);
1878 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1879 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1880 // This is not an aggressive instruction that we can promote.
1881 // Because of this, we won't be able to get rid of the control
1882 // flow, so the xform is not worth it.
1887 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1890 DomBlock = *pred_begin(IfBlock2);
1891 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1892 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1893 // This is not an aggressive instruction that we can promote.
1894 // Because of this, we won't be able to get rid of the control
1895 // flow, so the xform is not worth it.
1900 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1901 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1903 // If we can still promote the PHI nodes after this gauntlet of tests,
1904 // do all of the PHI's now.
1905 Instruction *InsertPt = DomBlock->getTerminator();
1906 IRBuilder<true, NoFolder> Builder(InsertPt);
1908 // Move all 'aggressive' instructions, which are defined in the
1909 // conditional parts of the if's up to the dominating block.
1911 DomBlock->getInstList().splice(InsertPt,
1912 IfBlock1->getInstList(), IfBlock1->begin(),
1913 IfBlock1->getTerminator());
1915 DomBlock->getInstList().splice(InsertPt,
1916 IfBlock2->getInstList(), IfBlock2->begin(),
1917 IfBlock2->getTerminator());
1919 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1920 // Change the PHI node into a select instruction.
1921 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1922 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1925 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1926 PN->replaceAllUsesWith(NV);
1928 PN->eraseFromParent();
1931 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1932 // has been flattened. Change DomBlock to jump directly to our new block to
1933 // avoid other simplifycfg's kicking in on the diamond.
1934 TerminatorInst *OldTI = DomBlock->getTerminator();
1935 Builder.SetInsertPoint(OldTI);
1936 Builder.CreateBr(BB);
1937 OldTI->eraseFromParent();
1941 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1942 /// to two returning blocks, try to merge them together into one return,
1943 /// introducing a select if the return values disagree.
1944 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1945 IRBuilder<> &Builder) {
1946 assert(BI->isConditional() && "Must be a conditional branch");
1947 BasicBlock *TrueSucc = BI->getSuccessor(0);
1948 BasicBlock *FalseSucc = BI->getSuccessor(1);
1949 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1950 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1952 // Check to ensure both blocks are empty (just a return) or optionally empty
1953 // with PHI nodes. If there are other instructions, merging would cause extra
1954 // computation on one path or the other.
1955 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1957 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1960 Builder.SetInsertPoint(BI);
1961 // Okay, we found a branch that is going to two return nodes. If
1962 // there is no return value for this function, just change the
1963 // branch into a return.
1964 if (FalseRet->getNumOperands() == 0) {
1965 TrueSucc->removePredecessor(BI->getParent());
1966 FalseSucc->removePredecessor(BI->getParent());
1967 Builder.CreateRetVoid();
1968 EraseTerminatorInstAndDCECond(BI);
1972 // Otherwise, figure out what the true and false return values are
1973 // so we can insert a new select instruction.
1974 Value *TrueValue = TrueRet->getReturnValue();
1975 Value *FalseValue = FalseRet->getReturnValue();
1977 // Unwrap any PHI nodes in the return blocks.
1978 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1979 if (TVPN->getParent() == TrueSucc)
1980 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1981 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1982 if (FVPN->getParent() == FalseSucc)
1983 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1985 // In order for this transformation to be safe, we must be able to
1986 // unconditionally execute both operands to the return. This is
1987 // normally the case, but we could have a potentially-trapping
1988 // constant expression that prevents this transformation from being
1990 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1993 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1997 // Okay, we collected all the mapped values and checked them for sanity, and
1998 // defined to really do this transformation. First, update the CFG.
1999 TrueSucc->removePredecessor(BI->getParent());
2000 FalseSucc->removePredecessor(BI->getParent());
2002 // Insert select instructions where needed.
2003 Value *BrCond = BI->getCondition();
2005 // Insert a select if the results differ.
2006 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2007 } else if (isa<UndefValue>(TrueValue)) {
2008 TrueValue = FalseValue;
2010 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2011 FalseValue, "retval");
2015 Value *RI = !TrueValue ?
2016 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2020 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2021 << "\n " << *BI << "NewRet = " << *RI
2022 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2024 EraseTerminatorInstAndDCECond(BI);
2029 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2030 /// probabilities of the branch taking each edge. Fills in the two APInt
2031 /// parameters and return true, or returns false if no or invalid metadata was
2033 static bool ExtractBranchMetadata(BranchInst *BI,
2034 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2035 assert(BI->isConditional() &&
2036 "Looking for probabilities on unconditional branch?");
2037 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2038 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2039 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
2040 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
2041 if (!CITrue || !CIFalse) return false;
2042 ProbTrue = CITrue->getValue().getZExtValue();
2043 ProbFalse = CIFalse->getValue().getZExtValue();
2047 /// checkCSEInPredecessor - Return true if the given instruction is available
2048 /// in its predecessor block. If yes, the instruction will be removed.
2050 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2051 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2053 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2054 Instruction *PBI = &*I;
2055 // Check whether Inst and PBI generate the same value.
2056 if (Inst->isIdenticalTo(PBI)) {
2057 Inst->replaceAllUsesWith(PBI);
2058 Inst->eraseFromParent();
2065 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2066 /// predecessor branches to us and one of our successors, fold the block into
2067 /// the predecessor and use logical operations to pick the right destination.
2068 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2069 unsigned BonusInstThreshold) {
2070 BasicBlock *BB = BI->getParent();
2072 Instruction *Cond = nullptr;
2073 if (BI->isConditional())
2074 Cond = dyn_cast<Instruction>(BI->getCondition());
2076 // For unconditional branch, check for a simple CFG pattern, where
2077 // BB has a single predecessor and BB's successor is also its predecessor's
2078 // successor. If such pattern exisits, check for CSE between BB and its
2080 if (BasicBlock *PB = BB->getSinglePredecessor())
2081 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2082 if (PBI->isConditional() &&
2083 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2084 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2085 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2087 Instruction *Curr = I++;
2088 if (isa<CmpInst>(Curr)) {
2092 // Quit if we can't remove this instruction.
2093 if (!checkCSEInPredecessor(Curr, PB))
2102 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2103 Cond->getParent() != BB || !Cond->hasOneUse())
2106 // Make sure the instruction after the condition is the cond branch.
2107 BasicBlock::iterator CondIt = Cond; ++CondIt;
2109 // Ignore dbg intrinsics.
2110 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2115 // Only allow this transformation if computing the condition doesn't involve
2116 // too many instructions and these involved instructions can be executed
2117 // unconditionally. We denote all involved instructions except the condition
2118 // as "bonus instructions", and only allow this transformation when the
2119 // number of the bonus instructions does not exceed a certain threshold.
2120 unsigned NumBonusInsts = 0;
2121 for (auto I = BB->begin(); Cond != I; ++I) {
2122 // Ignore dbg intrinsics.
2123 if (isa<DbgInfoIntrinsic>(I))
2125 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2127 // I has only one use and can be executed unconditionally.
2128 Instruction *User = dyn_cast<Instruction>(I->user_back());
2129 if (User == nullptr || User->getParent() != BB)
2131 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2132 // to use any other instruction, User must be an instruction between next(I)
2135 // Early exits once we reach the limit.
2136 if (NumBonusInsts > BonusInstThreshold)
2140 // Cond is known to be a compare or binary operator. Check to make sure that
2141 // neither operand is a potentially-trapping constant expression.
2142 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2145 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2149 // Finally, don't infinitely unroll conditional loops.
2150 BasicBlock *TrueDest = BI->getSuccessor(0);
2151 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2152 if (TrueDest == BB || FalseDest == BB)
2155 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2156 BasicBlock *PredBlock = *PI;
2157 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2159 // Check that we have two conditional branches. If there is a PHI node in
2160 // the common successor, verify that the same value flows in from both
2162 SmallVector<PHINode*, 4> PHIs;
2163 if (!PBI || PBI->isUnconditional() ||
2164 (BI->isConditional() &&
2165 !SafeToMergeTerminators(BI, PBI)) ||
2166 (!BI->isConditional() &&
2167 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2170 // Determine if the two branches share a common destination.
2171 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2172 bool InvertPredCond = false;
2174 if (BI->isConditional()) {
2175 if (PBI->getSuccessor(0) == TrueDest)
2176 Opc = Instruction::Or;
2177 else if (PBI->getSuccessor(1) == FalseDest)
2178 Opc = Instruction::And;
2179 else if (PBI->getSuccessor(0) == FalseDest)
2180 Opc = Instruction::And, InvertPredCond = true;
2181 else if (PBI->getSuccessor(1) == TrueDest)
2182 Opc = Instruction::Or, InvertPredCond = true;
2186 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2190 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2191 IRBuilder<> Builder(PBI);
2193 // If we need to invert the condition in the pred block to match, do so now.
2194 if (InvertPredCond) {
2195 Value *NewCond = PBI->getCondition();
2197 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2198 CmpInst *CI = cast<CmpInst>(NewCond);
2199 CI->setPredicate(CI->getInversePredicate());
2201 NewCond = Builder.CreateNot(NewCond,
2202 PBI->getCondition()->getName()+".not");
2205 PBI->setCondition(NewCond);
2206 PBI->swapSuccessors();
2209 // If we have bonus instructions, clone them into the predecessor block.
2210 // Note that there may be mutliple predecessor blocks, so we cannot move
2211 // bonus instructions to a predecessor block.
2212 ValueToValueMapTy VMap; // maps original values to cloned values
2213 // We already make sure Cond is the last instruction before BI. Therefore,
2214 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2216 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2217 if (isa<DbgInfoIntrinsic>(BonusInst))
2219 Instruction *NewBonusInst = BonusInst->clone();
2220 RemapInstruction(NewBonusInst, VMap,
2221 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2222 VMap[BonusInst] = NewBonusInst;
2224 // If we moved a load, we cannot any longer claim any knowledge about
2225 // its potential value. The previous information might have been valid
2226 // only given the branch precondition.
2227 // For an analogous reason, we must also drop all the metadata whose
2228 // semantics we don't understand.
2229 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2231 PredBlock->getInstList().insert(PBI, NewBonusInst);
2232 NewBonusInst->takeName(BonusInst);
2233 BonusInst->setName(BonusInst->getName() + ".old");
2236 // Clone Cond into the predecessor basic block, and or/and the
2237 // two conditions together.
2238 Instruction *New = Cond->clone();
2239 RemapInstruction(New, VMap,
2240 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2241 PredBlock->getInstList().insert(PBI, New);
2242 New->takeName(Cond);
2243 Cond->setName(New->getName() + ".old");
2245 if (BI->isConditional()) {
2246 Instruction *NewCond =
2247 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2249 PBI->setCondition(NewCond);
2251 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2252 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2254 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2256 SmallVector<uint64_t, 8> NewWeights;
2258 if (PBI->getSuccessor(0) == BB) {
2259 if (PredHasWeights && SuccHasWeights) {
2260 // PBI: br i1 %x, BB, FalseDest
2261 // BI: br i1 %y, TrueDest, FalseDest
2262 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2263 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2264 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2265 // TrueWeight for PBI * FalseWeight for BI.
2266 // We assume that total weights of a BranchInst can fit into 32 bits.
2267 // Therefore, we will not have overflow using 64-bit arithmetic.
2268 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2269 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2271 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2272 PBI->setSuccessor(0, TrueDest);
2274 if (PBI->getSuccessor(1) == BB) {
2275 if (PredHasWeights && SuccHasWeights) {
2276 // PBI: br i1 %x, TrueDest, BB
2277 // BI: br i1 %y, TrueDest, FalseDest
2278 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2279 // FalseWeight for PBI * TrueWeight for BI.
2280 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2281 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2282 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2283 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2285 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2286 PBI->setSuccessor(1, FalseDest);
2288 if (NewWeights.size() == 2) {
2289 // Halve the weights if any of them cannot fit in an uint32_t
2290 FitWeights(NewWeights);
2292 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2293 PBI->setMetadata(LLVMContext::MD_prof,
2294 MDBuilder(BI->getContext()).
2295 createBranchWeights(MDWeights));
2297 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2299 // Update PHI nodes in the common successors.
2300 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2301 ConstantInt *PBI_C = cast<ConstantInt>(
2302 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2303 assert(PBI_C->getType()->isIntegerTy(1));
2304 Instruction *MergedCond = nullptr;
2305 if (PBI->getSuccessor(0) == TrueDest) {
2306 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2307 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2308 // is false: !PBI_Cond and BI_Value
2309 Instruction *NotCond =
2310 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2313 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2318 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2319 PBI->getCondition(), MergedCond,
2322 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2323 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2324 // is false: PBI_Cond and BI_Value
2326 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2327 PBI->getCondition(), New,
2329 if (PBI_C->isOne()) {
2330 Instruction *NotCond =
2331 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2334 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2335 NotCond, MergedCond,
2340 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2343 // Change PBI from Conditional to Unconditional.
2344 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2345 EraseTerminatorInstAndDCECond(PBI);
2349 // TODO: If BB is reachable from all paths through PredBlock, then we
2350 // could replace PBI's branch probabilities with BI's.
2352 // Copy any debug value intrinsics into the end of PredBlock.
2353 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2354 if (isa<DbgInfoIntrinsic>(*I))
2355 I->clone()->insertBefore(PBI);
2362 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2363 /// predecessor of another block, this function tries to simplify it. We know
2364 /// that PBI and BI are both conditional branches, and BI is in one of the
2365 /// successor blocks of PBI - PBI branches to BI.
2366 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2367 assert(PBI->isConditional() && BI->isConditional());
2368 BasicBlock *BB = BI->getParent();
2370 // If this block ends with a branch instruction, and if there is a
2371 // predecessor that ends on a branch of the same condition, make
2372 // this conditional branch redundant.
2373 if (PBI->getCondition() == BI->getCondition() &&
2374 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2375 // Okay, the outcome of this conditional branch is statically
2376 // knowable. If this block had a single pred, handle specially.
2377 if (BB->getSinglePredecessor()) {
2378 // Turn this into a branch on constant.
2379 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2380 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2382 return true; // Nuke the branch on constant.
2385 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2386 // in the constant and simplify the block result. Subsequent passes of
2387 // simplifycfg will thread the block.
2388 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2389 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2390 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2391 std::distance(PB, PE),
2392 BI->getCondition()->getName() + ".pr",
2394 // Okay, we're going to insert the PHI node. Since PBI is not the only
2395 // predecessor, compute the PHI'd conditional value for all of the preds.
2396 // Any predecessor where the condition is not computable we keep symbolic.
2397 for (pred_iterator PI = PB; PI != PE; ++PI) {
2398 BasicBlock *P = *PI;
2399 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2400 PBI != BI && PBI->isConditional() &&
2401 PBI->getCondition() == BI->getCondition() &&
2402 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2403 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2404 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2407 NewPN->addIncoming(BI->getCondition(), P);
2411 BI->setCondition(NewPN);
2416 // If this is a conditional branch in an empty block, and if any
2417 // predecessors are a conditional branch to one of our destinations,
2418 // fold the conditions into logical ops and one cond br.
2419 BasicBlock::iterator BBI = BB->begin();
2420 // Ignore dbg intrinsics.
2421 while (isa<DbgInfoIntrinsic>(BBI))
2427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2432 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2434 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2435 PBIOp = 0, BIOp = 1;
2436 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2437 PBIOp = 1, BIOp = 0;
2438 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2443 // Check to make sure that the other destination of this branch
2444 // isn't BB itself. If so, this is an infinite loop that will
2445 // keep getting unwound.
2446 if (PBI->getSuccessor(PBIOp) == BB)
2449 // Do not perform this transformation if it would require
2450 // insertion of a large number of select instructions. For targets
2451 // without predication/cmovs, this is a big pessimization.
2453 // Also do not perform this transformation if any phi node in the common
2454 // destination block can trap when reached by BB or PBB (PR17073). In that
2455 // case, it would be unsafe to hoist the operation into a select instruction.
2457 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2458 unsigned NumPhis = 0;
2459 for (BasicBlock::iterator II = CommonDest->begin();
2460 isa<PHINode>(II); ++II, ++NumPhis) {
2461 if (NumPhis > 2) // Disable this xform.
2464 PHINode *PN = cast<PHINode>(II);
2465 Value *BIV = PN->getIncomingValueForBlock(BB);
2466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2470 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2471 Value *PBIV = PN->getIncomingValue(PBBIdx);
2472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2477 // Finally, if everything is ok, fold the branches to logical ops.
2478 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2480 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2481 << "AND: " << *BI->getParent());
2484 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2485 // branch in it, where one edge (OtherDest) goes back to itself but the other
2486 // exits. We don't *know* that the program avoids the infinite loop
2487 // (even though that seems likely). If we do this xform naively, we'll end up
2488 // recursively unpeeling the loop. Since we know that (after the xform is
2489 // done) that the block *is* infinite if reached, we just make it an obviously
2490 // infinite loop with no cond branch.
2491 if (OtherDest == BB) {
2492 // Insert it at the end of the function, because it's either code,
2493 // or it won't matter if it's hot. :)
2494 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2495 "infloop", BB->getParent());
2496 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2497 OtherDest = InfLoopBlock;
2500 DEBUG(dbgs() << *PBI->getParent()->getParent());
2502 // BI may have other predecessors. Because of this, we leave
2503 // it alone, but modify PBI.
2505 // Make sure we get to CommonDest on True&True directions.
2506 Value *PBICond = PBI->getCondition();
2507 IRBuilder<true, NoFolder> Builder(PBI);
2509 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2511 Value *BICond = BI->getCondition();
2513 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2515 // Merge the conditions.
2516 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2518 // Modify PBI to branch on the new condition to the new dests.
2519 PBI->setCondition(Cond);
2520 PBI->setSuccessor(0, CommonDest);
2521 PBI->setSuccessor(1, OtherDest);
2523 // Update branch weight for PBI.
2524 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2525 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2527 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2529 if (PredHasWeights && SuccHasWeights) {
2530 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2531 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2532 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2533 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2534 // The weight to CommonDest should be PredCommon * SuccTotal +
2535 // PredOther * SuccCommon.
2536 // The weight to OtherDest should be PredOther * SuccOther.
2537 SmallVector<uint64_t, 2> NewWeights;
2538 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2539 PredOther * SuccCommon);
2540 NewWeights.push_back(PredOther * SuccOther);
2541 // Halve the weights if any of them cannot fit in an uint32_t
2542 FitWeights(NewWeights);
2544 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2545 PBI->setMetadata(LLVMContext::MD_prof,
2546 MDBuilder(BI->getContext()).
2547 createBranchWeights(MDWeights));
2550 // OtherDest may have phi nodes. If so, add an entry from PBI's
2551 // block that are identical to the entries for BI's block.
2552 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2554 // We know that the CommonDest already had an edge from PBI to
2555 // it. If it has PHIs though, the PHIs may have different
2556 // entries for BB and PBI's BB. If so, insert a select to make
2559 for (BasicBlock::iterator II = CommonDest->begin();
2560 (PN = dyn_cast<PHINode>(II)); ++II) {
2561 Value *BIV = PN->getIncomingValueForBlock(BB);
2562 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2563 Value *PBIV = PN->getIncomingValue(PBBIdx);
2565 // Insert a select in PBI to pick the right value.
2566 Value *NV = cast<SelectInst>
2567 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2568 PN->setIncomingValue(PBBIdx, NV);
2572 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2573 DEBUG(dbgs() << *PBI->getParent()->getParent());
2575 // This basic block is probably dead. We know it has at least
2576 // one fewer predecessor.
2580 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2581 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2582 // Takes care of updating the successors and removing the old terminator.
2583 // Also makes sure not to introduce new successors by assuming that edges to
2584 // non-successor TrueBBs and FalseBBs aren't reachable.
2585 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2586 BasicBlock *TrueBB, BasicBlock *FalseBB,
2587 uint32_t TrueWeight,
2588 uint32_t FalseWeight){
2589 // Remove any superfluous successor edges from the CFG.
2590 // First, figure out which successors to preserve.
2591 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2593 BasicBlock *KeepEdge1 = TrueBB;
2594 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2596 // Then remove the rest.
2597 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2598 BasicBlock *Succ = OldTerm->getSuccessor(I);
2599 // Make sure only to keep exactly one copy of each edge.
2600 if (Succ == KeepEdge1)
2601 KeepEdge1 = nullptr;
2602 else if (Succ == KeepEdge2)
2603 KeepEdge2 = nullptr;
2605 Succ->removePredecessor(OldTerm->getParent());
2608 IRBuilder<> Builder(OldTerm);
2609 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2611 // Insert an appropriate new terminator.
2612 if (!KeepEdge1 && !KeepEdge2) {
2613 if (TrueBB == FalseBB)
2614 // We were only looking for one successor, and it was present.
2615 // Create an unconditional branch to it.
2616 Builder.CreateBr(TrueBB);
2618 // We found both of the successors we were looking for.
2619 // Create a conditional branch sharing the condition of the select.
2620 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2621 if (TrueWeight != FalseWeight)
2622 NewBI->setMetadata(LLVMContext::MD_prof,
2623 MDBuilder(OldTerm->getContext()).
2624 createBranchWeights(TrueWeight, FalseWeight));
2626 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2627 // Neither of the selected blocks were successors, so this
2628 // terminator must be unreachable.
2629 new UnreachableInst(OldTerm->getContext(), OldTerm);
2631 // One of the selected values was a successor, but the other wasn't.
2632 // Insert an unconditional branch to the one that was found;
2633 // the edge to the one that wasn't must be unreachable.
2635 // Only TrueBB was found.
2636 Builder.CreateBr(TrueBB);
2638 // Only FalseBB was found.
2639 Builder.CreateBr(FalseBB);
2642 EraseTerminatorInstAndDCECond(OldTerm);
2646 // SimplifySwitchOnSelect - Replaces
2647 // (switch (select cond, X, Y)) on constant X, Y
2648 // with a branch - conditional if X and Y lead to distinct BBs,
2649 // unconditional otherwise.
2650 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2651 // Check for constant integer values in the select.
2652 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2653 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2654 if (!TrueVal || !FalseVal)
2657 // Find the relevant condition and destinations.
2658 Value *Condition = Select->getCondition();
2659 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2660 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2662 // Get weight for TrueBB and FalseBB.
2663 uint32_t TrueWeight = 0, FalseWeight = 0;
2664 SmallVector<uint64_t, 8> Weights;
2665 bool HasWeights = HasBranchWeights(SI);
2667 GetBranchWeights(SI, Weights);
2668 if (Weights.size() == 1 + SI->getNumCases()) {
2669 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2670 getSuccessorIndex()];
2671 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2672 getSuccessorIndex()];
2676 // Perform the actual simplification.
2677 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2678 TrueWeight, FalseWeight);
2681 // SimplifyIndirectBrOnSelect - Replaces
2682 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2683 // blockaddress(@fn, BlockB)))
2685 // (br cond, BlockA, BlockB).
2686 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2687 // Check that both operands of the select are block addresses.
2688 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2689 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2693 // Extract the actual blocks.
2694 BasicBlock *TrueBB = TBA->getBasicBlock();
2695 BasicBlock *FalseBB = FBA->getBasicBlock();
2697 // Perform the actual simplification.
2698 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2702 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2703 /// instruction (a seteq/setne with a constant) as the only instruction in a
2704 /// block that ends with an uncond branch. We are looking for a very specific
2705 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2706 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2707 /// default value goes to an uncond block with a seteq in it, we get something
2710 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2712 /// %tmp = icmp eq i8 %A, 92
2715 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2717 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2718 /// the PHI, merging the third icmp into the switch.
2719 static bool TryToSimplifyUncondBranchWithICmpInIt(
2720 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2721 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
2722 BasicBlock *BB = ICI->getParent();
2724 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2726 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2728 Value *V = ICI->getOperand(0);
2729 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2731 // The pattern we're looking for is where our only predecessor is a switch on
2732 // 'V' and this block is the default case for the switch. In this case we can
2733 // fold the compared value into the switch to simplify things.
2734 BasicBlock *Pred = BB->getSinglePredecessor();
2735 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2737 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2738 if (SI->getCondition() != V)
2741 // If BB is reachable on a non-default case, then we simply know the value of
2742 // V in this block. Substitute it and constant fold the icmp instruction
2744 if (SI->getDefaultDest() != BB) {
2745 ConstantInt *VVal = SI->findCaseDest(BB);
2746 assert(VVal && "Should have a unique destination value");
2747 ICI->setOperand(0, VVal);
2749 if (Value *V = SimplifyInstruction(ICI, DL)) {
2750 ICI->replaceAllUsesWith(V);
2751 ICI->eraseFromParent();
2753 // BB is now empty, so it is likely to simplify away.
2754 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2757 // Ok, the block is reachable from the default dest. If the constant we're
2758 // comparing exists in one of the other edges, then we can constant fold ICI
2760 if (SI->findCaseValue(Cst) != SI->case_default()) {
2762 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2763 V = ConstantInt::getFalse(BB->getContext());
2765 V = ConstantInt::getTrue(BB->getContext());
2767 ICI->replaceAllUsesWith(V);
2768 ICI->eraseFromParent();
2769 // BB is now empty, so it is likely to simplify away.
2770 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2773 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2775 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2776 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2777 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2778 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2781 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2783 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2784 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2786 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2787 std::swap(DefaultCst, NewCst);
2789 // Replace ICI (which is used by the PHI for the default value) with true or
2790 // false depending on if it is EQ or NE.
2791 ICI->replaceAllUsesWith(DefaultCst);
2792 ICI->eraseFromParent();
2794 // Okay, the switch goes to this block on a default value. Add an edge from
2795 // the switch to the merge point on the compared value.
2796 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2797 BB->getParent(), BB);
2798 SmallVector<uint64_t, 8> Weights;
2799 bool HasWeights = HasBranchWeights(SI);
2801 GetBranchWeights(SI, Weights);
2802 if (Weights.size() == 1 + SI->getNumCases()) {
2803 // Split weight for default case to case for "Cst".
2804 Weights[0] = (Weights[0]+1) >> 1;
2805 Weights.push_back(Weights[0]);
2807 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2808 SI->setMetadata(LLVMContext::MD_prof,
2809 MDBuilder(SI->getContext()).
2810 createBranchWeights(MDWeights));
2813 SI->addCase(Cst, NewBB);
2815 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2816 Builder.SetInsertPoint(NewBB);
2817 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2818 Builder.CreateBr(SuccBlock);
2819 PHIUse->addIncoming(NewCst, NewBB);
2823 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2824 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2825 /// fold it into a switch instruction if so.
2826 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2827 IRBuilder<> &Builder) {
2828 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2829 if (!Cond) return false;
2831 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2832 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2833 // 'setne's and'ed together, collect them.
2835 // Try to gather values from a chain of and/or to be turned into a switch
2836 ConstantComparesGatherer ConstantCompare(Cond, DL);
2837 // Unpack the result
2838 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2839 Value *CompVal = ConstantCompare.CompValue;
2840 unsigned UsedICmps = ConstantCompare.UsedICmps;
2841 Value *ExtraCase = ConstantCompare.Extra;
2843 // If we didn't have a multiply compared value, fail.
2844 if (!CompVal) return false;
2846 // Avoid turning single icmps into a switch.
2850 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2852 // There might be duplicate constants in the list, which the switch
2853 // instruction can't handle, remove them now.
2854 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2855 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2857 // If Extra was used, we require at least two switch values to do the
2858 // transformation. A switch with one value is just an cond branch.
2859 if (ExtraCase && Values.size() < 2) return false;
2861 // TODO: Preserve branch weight metadata, similarly to how
2862 // FoldValueComparisonIntoPredecessors preserves it.
2864 // Figure out which block is which destination.
2865 BasicBlock *DefaultBB = BI->getSuccessor(1);
2866 BasicBlock *EdgeBB = BI->getSuccessor(0);
2867 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2869 BasicBlock *BB = BI->getParent();
2871 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2872 << " cases into SWITCH. BB is:\n" << *BB);
2874 // If there are any extra values that couldn't be folded into the switch
2875 // then we evaluate them with an explicit branch first. Split the block
2876 // right before the condbr to handle it.
2878 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2879 // Remove the uncond branch added to the old block.
2880 TerminatorInst *OldTI = BB->getTerminator();
2881 Builder.SetInsertPoint(OldTI);
2884 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2886 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2888 OldTI->eraseFromParent();
2890 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2891 // for the edge we just added.
2892 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2894 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2895 << "\nEXTRABB = " << *BB);
2899 Builder.SetInsertPoint(BI);
2900 // Convert pointer to int before we switch.
2901 if (CompVal->getType()->isPointerTy()) {
2902 assert(DL && "Cannot switch on pointer without DataLayout");
2903 CompVal = Builder.CreatePtrToInt(CompVal,
2904 DL->getIntPtrType(CompVal->getType()),
2908 // Create the new switch instruction now.
2909 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2911 // Add all of the 'cases' to the switch instruction.
2912 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2913 New->addCase(Values[i], EdgeBB);
2915 // We added edges from PI to the EdgeBB. As such, if there were any
2916 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2917 // the number of edges added.
2918 for (BasicBlock::iterator BBI = EdgeBB->begin();
2919 isa<PHINode>(BBI); ++BBI) {
2920 PHINode *PN = cast<PHINode>(BBI);
2921 Value *InVal = PN->getIncomingValueForBlock(BB);
2922 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2923 PN->addIncoming(InVal, BB);
2926 // Erase the old branch instruction.
2927 EraseTerminatorInstAndDCECond(BI);
2929 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2933 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2934 // If this is a trivial landing pad that just continues unwinding the caught
2935 // exception then zap the landing pad, turning its invokes into calls.
2936 BasicBlock *BB = RI->getParent();
2937 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2938 if (RI->getValue() != LPInst)
2939 // Not a landing pad, or the resume is not unwinding the exception that
2940 // caused control to branch here.
2943 // Check that there are no other instructions except for debug intrinsics.
2944 BasicBlock::iterator I = LPInst, E = RI;
2946 if (!isa<DbgInfoIntrinsic>(I))
2949 // Turn all invokes that unwind here into calls and delete the basic block.
2950 bool InvokeRequiresTableEntry = false;
2951 bool Changed = false;
2952 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2953 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2955 if (II->hasFnAttr(Attribute::UWTable)) {
2956 // Don't remove an `invoke' instruction if the ABI requires an entry into
2958 InvokeRequiresTableEntry = true;
2962 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2964 // Insert a call instruction before the invoke.
2965 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2967 Call->setCallingConv(II->getCallingConv());
2968 Call->setAttributes(II->getAttributes());
2969 Call->setDebugLoc(II->getDebugLoc());
2971 // Anything that used the value produced by the invoke instruction now uses
2972 // the value produced by the call instruction. Note that we do this even
2973 // for void functions and calls with no uses so that the callgraph edge is
2975 II->replaceAllUsesWith(Call);
2976 BB->removePredecessor(II->getParent());
2978 // Insert a branch to the normal destination right before the invoke.
2979 BranchInst::Create(II->getNormalDest(), II);
2981 // Finally, delete the invoke instruction!
2982 II->eraseFromParent();
2986 if (!InvokeRequiresTableEntry)
2987 // The landingpad is now unreachable. Zap it.
2988 BB->eraseFromParent();
2993 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2994 BasicBlock *BB = RI->getParent();
2995 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2997 // Find predecessors that end with branches.
2998 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2999 SmallVector<BranchInst*, 8> CondBranchPreds;
3000 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3001 BasicBlock *P = *PI;
3002 TerminatorInst *PTI = P->getTerminator();
3003 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3004 if (BI->isUnconditional())
3005 UncondBranchPreds.push_back(P);
3007 CondBranchPreds.push_back(BI);
3011 // If we found some, do the transformation!
3012 if (!UncondBranchPreds.empty() && DupRet) {
3013 while (!UncondBranchPreds.empty()) {
3014 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3015 DEBUG(dbgs() << "FOLDING: " << *BB
3016 << "INTO UNCOND BRANCH PRED: " << *Pred);
3017 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3020 // If we eliminated all predecessors of the block, delete the block now.
3021 if (pred_begin(BB) == pred_end(BB))
3022 // We know there are no successors, so just nuke the block.
3023 BB->eraseFromParent();
3028 // Check out all of the conditional branches going to this return
3029 // instruction. If any of them just select between returns, change the
3030 // branch itself into a select/return pair.
3031 while (!CondBranchPreds.empty()) {
3032 BranchInst *BI = CondBranchPreds.pop_back_val();
3034 // Check to see if the non-BB successor is also a return block.
3035 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3036 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3037 SimplifyCondBranchToTwoReturns(BI, Builder))
3043 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3044 BasicBlock *BB = UI->getParent();
3046 bool Changed = false;
3048 // If there are any instructions immediately before the unreachable that can
3049 // be removed, do so.
3050 while (UI != BB->begin()) {
3051 BasicBlock::iterator BBI = UI;
3053 // Do not delete instructions that can have side effects which might cause
3054 // the unreachable to not be reachable; specifically, calls and volatile
3055 // operations may have this effect.
3056 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3058 if (BBI->mayHaveSideEffects()) {
3059 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3060 if (SI->isVolatile())
3062 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3063 if (LI->isVolatile())
3065 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3066 if (RMWI->isVolatile())
3068 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3069 if (CXI->isVolatile())
3071 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3072 !isa<LandingPadInst>(BBI)) {
3075 // Note that deleting LandingPad's here is in fact okay, although it
3076 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3077 // all the predecessors of this block will be the unwind edges of Invokes,
3078 // and we can therefore guarantee this block will be erased.
3081 // Delete this instruction (any uses are guaranteed to be dead)
3082 if (!BBI->use_empty())
3083 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3084 BBI->eraseFromParent();
3088 // If the unreachable instruction is the first in the block, take a gander
3089 // at all of the predecessors of this instruction, and simplify them.
3090 if (&BB->front() != UI) return Changed;
3092 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3093 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3094 TerminatorInst *TI = Preds[i]->getTerminator();
3095 IRBuilder<> Builder(TI);
3096 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3097 if (BI->isUnconditional()) {
3098 if (BI->getSuccessor(0) == BB) {
3099 new UnreachableInst(TI->getContext(), TI);
3100 TI->eraseFromParent();
3104 if (BI->getSuccessor(0) == BB) {
3105 Builder.CreateBr(BI->getSuccessor(1));
3106 EraseTerminatorInstAndDCECond(BI);
3107 } else if (BI->getSuccessor(1) == BB) {
3108 Builder.CreateBr(BI->getSuccessor(0));
3109 EraseTerminatorInstAndDCECond(BI);
3113 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3114 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3116 if (i.getCaseSuccessor() == BB) {
3117 BB->removePredecessor(SI->getParent());
3122 // If the default value is unreachable, figure out the most popular
3123 // destination and make it the default.
3124 if (SI->getDefaultDest() == BB) {
3125 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3126 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3128 std::pair<unsigned, unsigned> &entry =
3129 Popularity[i.getCaseSuccessor()];
3130 if (entry.first == 0) {
3132 entry.second = i.getCaseIndex();
3138 // Find the most popular block.
3139 unsigned MaxPop = 0;
3140 unsigned MaxIndex = 0;
3141 BasicBlock *MaxBlock = nullptr;
3142 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3143 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3144 if (I->second.first > MaxPop ||
3145 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3146 MaxPop = I->second.first;
3147 MaxIndex = I->second.second;
3148 MaxBlock = I->first;
3152 // Make this the new default, allowing us to delete any explicit
3154 SI->setDefaultDest(MaxBlock);
3157 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3159 if (isa<PHINode>(MaxBlock->begin()))
3160 for (unsigned i = 0; i != MaxPop-1; ++i)
3161 MaxBlock->removePredecessor(SI->getParent());
3163 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3165 if (i.getCaseSuccessor() == MaxBlock) {
3171 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3172 if (II->getUnwindDest() == BB) {
3173 // Convert the invoke to a call instruction. This would be a good
3174 // place to note that the call does not throw though.
3175 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3176 II->removeFromParent(); // Take out of symbol table
3178 // Insert the call now...
3179 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3180 Builder.SetInsertPoint(BI);
3181 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3182 Args, II->getName());
3183 CI->setCallingConv(II->getCallingConv());
3184 CI->setAttributes(II->getAttributes());
3185 // If the invoke produced a value, the call does now instead.
3186 II->replaceAllUsesWith(CI);
3193 // If this block is now dead, remove it.
3194 if (pred_begin(BB) == pred_end(BB) &&
3195 BB != &BB->getParent()->getEntryBlock()) {
3196 // We know there are no successors, so just nuke the block.
3197 BB->eraseFromParent();
3204 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3205 /// integer range comparison into a sub, an icmp and a branch.
3206 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3207 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3209 // Make sure all cases point to the same destination and gather the values.
3210 SmallVector<ConstantInt *, 16> Cases;
3211 SwitchInst::CaseIt I = SI->case_begin();
3212 Cases.push_back(I.getCaseValue());
3213 SwitchInst::CaseIt PrevI = I++;
3214 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3215 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3217 Cases.push_back(I.getCaseValue());
3219 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3221 // Sort the case values, then check if they form a range we can transform.
3222 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3223 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3224 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3228 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3229 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3231 Value *Sub = SI->getCondition();
3232 if (!Offset->isNullValue())
3233 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3235 // If NumCases overflowed, then all possible values jump to the successor.
3236 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3237 Cmp = ConstantInt::getTrue(SI->getContext());
3239 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3240 BranchInst *NewBI = Builder.CreateCondBr(
3241 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3243 // Update weight for the newly-created conditional branch.
3244 SmallVector<uint64_t, 8> Weights;
3245 bool HasWeights = HasBranchWeights(SI);
3247 GetBranchWeights(SI, Weights);
3248 if (Weights.size() == 1 + SI->getNumCases()) {
3249 // Combine all weights for the cases to be the true weight of NewBI.
3250 // We assume that the sum of all weights for a Terminator can fit into 32
3252 uint32_t NewTrueWeight = 0;
3253 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3254 NewTrueWeight += (uint32_t)Weights[I];
3255 NewBI->setMetadata(LLVMContext::MD_prof,
3256 MDBuilder(SI->getContext()).
3257 createBranchWeights(NewTrueWeight,
3258 (uint32_t)Weights[0]));
3262 // Prune obsolete incoming values off the successor's PHI nodes.
3263 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3264 isa<PHINode>(BBI); ++BBI) {
3265 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3266 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3268 SI->eraseFromParent();
3273 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3274 /// and use it to remove dead cases.
3275 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3276 AssumptionTracker *AT) {
3277 Value *Cond = SI->getCondition();
3278 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3279 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3280 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3282 // Gather dead cases.
3283 SmallVector<ConstantInt*, 8> DeadCases;
3284 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3285 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3286 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3287 DeadCases.push_back(I.getCaseValue());
3288 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3289 << I.getCaseValue() << "' is dead.\n");
3293 SmallVector<uint64_t, 8> Weights;
3294 bool HasWeight = HasBranchWeights(SI);
3296 GetBranchWeights(SI, Weights);
3297 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3300 // Remove dead cases from the switch.
3301 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3302 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3303 assert(Case != SI->case_default() &&
3304 "Case was not found. Probably mistake in DeadCases forming.");
3306 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3310 // Prune unused values from PHI nodes.
3311 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3312 SI->removeCase(Case);
3314 if (HasWeight && Weights.size() >= 2) {
3315 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3316 SI->setMetadata(LLVMContext::MD_prof,
3317 MDBuilder(SI->getParent()->getContext()).
3318 createBranchWeights(MDWeights));
3321 return !DeadCases.empty();
3324 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3325 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3326 /// by an unconditional branch), look at the phi node for BB in the successor
3327 /// block and see if the incoming value is equal to CaseValue. If so, return
3328 /// the phi node, and set PhiIndex to BB's index in the phi node.
3329 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3332 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3333 return nullptr; // BB must be empty to be a candidate for simplification.
3334 if (!BB->getSinglePredecessor())
3335 return nullptr; // BB must be dominated by the switch.
3337 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3338 if (!Branch || !Branch->isUnconditional())
3339 return nullptr; // Terminator must be unconditional branch.
3341 BasicBlock *Succ = Branch->getSuccessor(0);
3343 BasicBlock::iterator I = Succ->begin();
3344 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3345 int Idx = PHI->getBasicBlockIndex(BB);
3346 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3348 Value *InValue = PHI->getIncomingValue(Idx);
3349 if (InValue != CaseValue) continue;
3358 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3359 /// instruction to a phi node dominated by the switch, if that would mean that
3360 /// some of the destination blocks of the switch can be folded away.
3361 /// Returns true if a change is made.
3362 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3363 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3364 ForwardingNodesMap ForwardingNodes;
3366 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3367 ConstantInt *CaseValue = I.getCaseValue();
3368 BasicBlock *CaseDest = I.getCaseSuccessor();
3371 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3375 ForwardingNodes[PHI].push_back(PhiIndex);
3378 bool Changed = false;
3380 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3381 E = ForwardingNodes.end(); I != E; ++I) {
3382 PHINode *Phi = I->first;
3383 SmallVectorImpl<int> &Indexes = I->second;
3385 if (Indexes.size() < 2) continue;
3387 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3388 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3395 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3396 /// initializing an array of constants like C.
3397 static bool ValidLookupTableConstant(Constant *C) {
3398 if (C->isThreadDependent())
3400 if (C->isDLLImportDependent())
3403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3404 return CE->isGEPWithNoNotionalOverIndexing();
3406 return isa<ConstantFP>(C) ||
3407 isa<ConstantInt>(C) ||
3408 isa<ConstantPointerNull>(C) ||
3409 isa<GlobalValue>(C) ||
3413 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3414 /// its constant value in ConstantPool, returning 0 if it's not there.
3415 static Constant *LookupConstant(Value *V,
3416 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3417 if (Constant *C = dyn_cast<Constant>(V))
3419 return ConstantPool.lookup(V);
3422 /// ConstantFold - Try to fold instruction I into a constant. This works for
3423 /// simple instructions such as binary operations where both operands are
3424 /// constant or can be replaced by constants from the ConstantPool. Returns the
3425 /// resulting constant on success, 0 otherwise.
3427 ConstantFold(Instruction *I,
3428 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3429 const DataLayout *DL) {
3430 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3431 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3434 if (A->isAllOnesValue())
3435 return LookupConstant(Select->getTrueValue(), ConstantPool);
3436 if (A->isNullValue())
3437 return LookupConstant(Select->getFalseValue(), ConstantPool);
3441 SmallVector<Constant *, 4> COps;
3442 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3443 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3449 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3450 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3453 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3456 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3457 /// at the common destination basic block, *CommonDest, for one of the case
3458 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3459 /// case), of a switch instruction SI.
3461 GetCaseResults(SwitchInst *SI,
3462 ConstantInt *CaseVal,
3463 BasicBlock *CaseDest,
3464 BasicBlock **CommonDest,
3465 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3466 const DataLayout *DL) {
3467 // The block from which we enter the common destination.
3468 BasicBlock *Pred = SI->getParent();
3470 // If CaseDest is empty except for some side-effect free instructions through
3471 // which we can constant-propagate the CaseVal, continue to its successor.
3472 SmallDenseMap<Value*, Constant*> ConstantPool;
3473 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3474 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3476 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3477 // If the terminator is a simple branch, continue to the next block.
3478 if (T->getNumSuccessors() != 1)
3481 CaseDest = T->getSuccessor(0);
3482 } else if (isa<DbgInfoIntrinsic>(I)) {
3483 // Skip debug intrinsic.
3485 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3486 // Instruction is side-effect free and constant.
3487 ConstantPool.insert(std::make_pair(I, C));
3493 // If we did not have a CommonDest before, use the current one.
3495 *CommonDest = CaseDest;
3496 // If the destination isn't the common one, abort.
3497 if (CaseDest != *CommonDest)
3500 // Get the values for this case from phi nodes in the destination block.
3501 BasicBlock::iterator I = (*CommonDest)->begin();
3502 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3503 int Idx = PHI->getBasicBlockIndex(Pred);
3507 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3512 // Note: If the constant comes from constant-propagating the case value
3513 // through the CaseDest basic block, it will be safe to remove the
3514 // instructions in that block. They cannot be used (except in the phi nodes
3515 // we visit) outside CaseDest, because that block does not dominate its
3516 // successor. If it did, we would not be in this phi node.
3518 // Be conservative about which kinds of constants we support.
3519 if (!ValidLookupTableConstant(ConstVal))
3522 Res.push_back(std::make_pair(PHI, ConstVal));
3525 return Res.size() > 0;
3528 // MapCaseToResult - Helper function used to
3529 // add CaseVal to the list of cases that generate Result.
3530 static void MapCaseToResult(ConstantInt *CaseVal,
3531 SwitchCaseResultVectorTy &UniqueResults,
3533 for (auto &I : UniqueResults) {
3534 if (I.first == Result) {
3535 I.second.push_back(CaseVal);
3539 UniqueResults.push_back(std::make_pair(Result,
3540 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3543 // InitializeUniqueCases - Helper function that initializes a map containing
3544 // results for the PHI node of the common destination block for a switch
3545 // instruction. Returns false if multiple PHI nodes have been found or if
3546 // there is not a common destination block for the switch.
3547 static bool InitializeUniqueCases(
3548 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3549 BasicBlock *&CommonDest,
3550 SwitchCaseResultVectorTy &UniqueResults,
3551 Constant *&DefaultResult) {
3552 for (auto &I : SI->cases()) {
3553 ConstantInt *CaseVal = I.getCaseValue();
3555 // Resulting value at phi nodes for this case value.
3556 SwitchCaseResultsTy Results;
3557 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3561 // Only one value per case is permitted
3562 if (Results.size() > 1)
3564 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3566 // Check the PHI consistency.
3568 PHI = Results[0].first;
3569 else if (PHI != Results[0].first)
3572 // Find the default result value.
3573 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3574 BasicBlock *DefaultDest = SI->getDefaultDest();
3575 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3577 // If the default value is not found abort unless the default destination
3580 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3581 if ((!DefaultResult &&
3582 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3588 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3589 // transform a switch with only two cases (or two cases + default)
3590 // that produces a result into a value select.
3593 // case 10: %0 = icmp eq i32 %a, 10
3594 // return 10; %1 = select i1 %0, i32 10, i32 4
3595 // case 20: ----> %2 = icmp eq i32 %a, 20
3596 // return 2; %3 = select i1 %2, i32 2, i32 %1
3601 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3602 Constant *DefaultResult, Value *Condition,
3603 IRBuilder<> &Builder) {
3604 assert(ResultVector.size() == 2 &&
3605 "We should have exactly two unique results at this point");
3606 // If we are selecting between only two cases transform into a simple
3607 // select or a two-way select if default is possible.
3608 if (ResultVector[0].second.size() == 1 &&
3609 ResultVector[1].second.size() == 1) {
3610 ConstantInt *const FirstCase = ResultVector[0].second[0];
3611 ConstantInt *const SecondCase = ResultVector[1].second[0];
3613 bool DefaultCanTrigger = DefaultResult;
3614 Value *SelectValue = ResultVector[1].first;
3615 if (DefaultCanTrigger) {
3616 Value *const ValueCompare =
3617 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3618 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3619 DefaultResult, "switch.select");
3621 Value *const ValueCompare =
3622 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3623 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3630 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3631 // instruction that has been converted into a select, fixing up PHI nodes and
3633 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3635 IRBuilder<> &Builder) {
3636 BasicBlock *SelectBB = SI->getParent();
3637 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3638 PHI->removeIncomingValue(SelectBB);
3639 PHI->addIncoming(SelectValue, SelectBB);
3641 Builder.CreateBr(PHI->getParent());
3643 // Remove the switch.
3644 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3645 BasicBlock *Succ = SI->getSuccessor(i);
3647 if (Succ == PHI->getParent())
3649 Succ->removePredecessor(SelectBB);
3651 SI->eraseFromParent();
3654 /// SwitchToSelect - If the switch is only used to initialize one or more
3655 /// phi nodes in a common successor block with only two different
3656 /// constant values, replace the switch with select.
3657 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3658 const DataLayout *DL, AssumptionTracker *AT) {
3659 Value *const Cond = SI->getCondition();
3660 PHINode *PHI = nullptr;
3661 BasicBlock *CommonDest = nullptr;
3662 Constant *DefaultResult;
3663 SwitchCaseResultVectorTy UniqueResults;
3664 // Collect all the cases that will deliver the same value from the switch.
3665 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3668 // Selects choose between maximum two values.
3669 if (UniqueResults.size() != 2)
3671 assert(PHI != nullptr && "PHI for value select not found");
3673 Builder.SetInsertPoint(SI);
3674 Value *SelectValue = ConvertTwoCaseSwitch(
3676 DefaultResult, Cond, Builder);
3678 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3681 // The switch couldn't be converted into a select.
3686 /// SwitchLookupTable - This class represents a lookup table that can be used
3687 /// to replace a switch.
3688 class SwitchLookupTable {
3690 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3691 /// with the contents of Values, using DefaultValue to fill any holes in the
3693 SwitchLookupTable(Module &M,
3695 ConstantInt *Offset,
3696 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3697 Constant *DefaultValue,
3698 const DataLayout *DL);
3700 /// BuildLookup - Build instructions with Builder to retrieve the value at
3701 /// the position given by Index in the lookup table.
3702 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3704 /// WouldFitInRegister - Return true if a table with TableSize elements of
3705 /// type ElementType would fit in a target-legal register.
3706 static bool WouldFitInRegister(const DataLayout *DL,
3708 const Type *ElementType);
3711 // Depending on the contents of the table, it can be represented in
3714 // For tables where each element contains the same value, we just have to
3715 // store that single value and return it for each lookup.
3718 // For tables where there is a linear relationship between table index
3719 // and values. We calculate the result with a simple multiplication
3720 // and addition instead of a table lookup.
3723 // For small tables with integer elements, we can pack them into a bitmap
3724 // that fits into a target-legal register. Values are retrieved by
3725 // shift and mask operations.
3728 // The table is stored as an array of values. Values are retrieved by load
3729 // instructions from the table.
3733 // For SingleValueKind, this is the single value.
3734 Constant *SingleValue;
3736 // For BitMapKind, this is the bitmap.
3737 ConstantInt *BitMap;
3738 IntegerType *BitMapElementTy;
3740 // For LinearMapKind, these are the constants used to derive the value.
3741 ConstantInt *LinearOffset;
3742 ConstantInt *LinearMultiplier;
3744 // For ArrayKind, this is the array.
3745 GlobalVariable *Array;
3749 SwitchLookupTable::SwitchLookupTable(Module &M,
3751 ConstantInt *Offset,
3752 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3753 Constant *DefaultValue,
3754 const DataLayout *DL)
3755 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3756 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3757 assert(Values.size() && "Can't build lookup table without values!");
3758 assert(TableSize >= Values.size() && "Can't fit values in table!");
3760 // If all values in the table are equal, this is that value.
3761 SingleValue = Values.begin()->second;
3763 Type *ValueType = Values.begin()->second->getType();
3765 // Build up the table contents.
3766 SmallVector<Constant*, 64> TableContents(TableSize);
3767 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3768 ConstantInt *CaseVal = Values[I].first;
3769 Constant *CaseRes = Values[I].second;
3770 assert(CaseRes->getType() == ValueType);
3772 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3774 TableContents[Idx] = CaseRes;
3776 if (CaseRes != SingleValue)
3777 SingleValue = nullptr;
3780 // Fill in any holes in the table with the default result.
3781 if (Values.size() < TableSize) {
3782 assert(DefaultValue &&
3783 "Need a default value to fill the lookup table holes.");
3784 assert(DefaultValue->getType() == ValueType);
3785 for (uint64_t I = 0; I < TableSize; ++I) {
3786 if (!TableContents[I])
3787 TableContents[I] = DefaultValue;
3790 if (DefaultValue != SingleValue)
3791 SingleValue = nullptr;
3794 // If each element in the table contains the same value, we only need to store
3795 // that single value.
3797 Kind = SingleValueKind;
3801 // Check if we can derive the value with a linear transformation from the
3803 if (isa<IntegerType>(ValueType)) {
3804 bool LinearMappingPossible = true;
3807 assert(TableSize >= 2 && "Should be a SingleValue table.");
3808 // Check if there is the same distance between two consecutive values.
3809 for (uint64_t I = 0; I < TableSize; ++I) {
3810 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3812 // This is an undef. We could deal with it, but undefs in lookup tables
3813 // are very seldom. It's probably not worth the additional complexity.
3814 LinearMappingPossible = false;
3817 APInt Val = ConstVal->getValue();
3819 APInt Dist = Val - PrevVal;
3822 } else if (Dist != DistToPrev) {
3823 LinearMappingPossible = false;
3829 if (LinearMappingPossible) {
3830 LinearOffset = cast<ConstantInt>(TableContents[0]);
3831 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3832 Kind = LinearMapKind;
3838 // If the type is integer and the table fits in a register, build a bitmap.
3839 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3840 IntegerType *IT = cast<IntegerType>(ValueType);
3841 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3842 for (uint64_t I = TableSize; I > 0; --I) {
3843 TableInt <<= IT->getBitWidth();
3844 // Insert values into the bitmap. Undef values are set to zero.
3845 if (!isa<UndefValue>(TableContents[I - 1])) {
3846 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3847 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3850 BitMap = ConstantInt::get(M.getContext(), TableInt);
3851 BitMapElementTy = IT;
3857 // Store the table in an array.
3858 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3859 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3861 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3862 GlobalVariable::PrivateLinkage,
3865 Array->setUnnamedAddr(true);
3869 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3871 case SingleValueKind:
3873 case LinearMapKind: {
3874 // Derive the result value from the input value.
3875 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3876 false, "switch.idx.cast");
3877 if (!LinearMultiplier->isOne())
3878 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3879 if (!LinearOffset->isZero())
3880 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3884 // Type of the bitmap (e.g. i59).
3885 IntegerType *MapTy = BitMap->getType();
3887 // Cast Index to the same type as the bitmap.
3888 // Note: The Index is <= the number of elements in the table, so
3889 // truncating it to the width of the bitmask is safe.
3890 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3892 // Multiply the shift amount by the element width.
3893 ShiftAmt = Builder.CreateMul(ShiftAmt,
3894 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3898 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3899 "switch.downshift");
3901 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3905 // Make sure the table index will not overflow when treated as signed.
3906 IntegerType *IT = cast<IntegerType>(Index->getType());
3907 uint64_t TableSize = Array->getInitializer()->getType()
3908 ->getArrayNumElements();
3909 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3910 Index = Builder.CreateZExt(Index,
3911 IntegerType::get(IT->getContext(),
3912 IT->getBitWidth() + 1),
3913 "switch.tableidx.zext");
3915 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3916 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3918 return Builder.CreateLoad(GEP, "switch.load");
3921 llvm_unreachable("Unknown lookup table kind!");
3924 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3926 const Type *ElementType) {
3929 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3932 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3933 // are <= 15, we could try to narrow the type.
3935 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3936 if (TableSize >= UINT_MAX/IT->getBitWidth())
3938 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3941 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3942 /// for this switch, based on the number of cases, size of the table and the
3943 /// types of the results.
3944 static bool ShouldBuildLookupTable(SwitchInst *SI,
3946 const TargetTransformInfo &TTI,
3947 const DataLayout *DL,
3948 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3949 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3950 return false; // TableSize overflowed, or mul below might overflow.
3952 bool AllTablesFitInRegister = true;
3953 bool HasIllegalType = false;
3954 for (const auto &I : ResultTypes) {
3955 Type *Ty = I.second;
3957 // Saturate this flag to true.
3958 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3960 // Saturate this flag to false.
3961 AllTablesFitInRegister = AllTablesFitInRegister &&
3962 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3964 // If both flags saturate, we're done. NOTE: This *only* works with
3965 // saturating flags, and all flags have to saturate first due to the
3966 // non-deterministic behavior of iterating over a dense map.
3967 if (HasIllegalType && !AllTablesFitInRegister)
3971 // If each table would fit in a register, we should build it anyway.
3972 if (AllTablesFitInRegister)
3975 // Don't build a table that doesn't fit in-register if it has illegal types.
3979 // The table density should be at least 40%. This is the same criterion as for
3980 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3981 // FIXME: Find the best cut-off.
3982 return SI->getNumCases() * 10 >= TableSize * 4;
3985 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3986 /// phi nodes in a common successor block with different constant values,
3987 /// replace the switch with lookup tables.
3988 static bool SwitchToLookupTable(SwitchInst *SI,
3989 IRBuilder<> &Builder,
3990 const TargetTransformInfo &TTI,
3991 const DataLayout* DL) {
3992 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3994 // Only build lookup table when we have a target that supports it.
3995 if (!TTI.shouldBuildLookupTables())
3998 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3999 // split off a dense part and build a lookup table for that.
4001 // FIXME: This creates arrays of GEPs to constant strings, which means each
4002 // GEP needs a runtime relocation in PIC code. We should just build one big
4003 // string and lookup indices into that.
4005 // Ignore switches with less than three cases. Lookup tables will not make them
4006 // faster, so we don't analyze them.
4007 if (SI->getNumCases() < 3)
4010 // Figure out the corresponding result for each case value and phi node in the
4011 // common destination, as well as the the min and max case values.
4012 assert(SI->case_begin() != SI->case_end());
4013 SwitchInst::CaseIt CI = SI->case_begin();
4014 ConstantInt *MinCaseVal = CI.getCaseValue();
4015 ConstantInt *MaxCaseVal = CI.getCaseValue();
4017 BasicBlock *CommonDest = nullptr;
4018 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4019 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4020 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4021 SmallDenseMap<PHINode*, Type*> ResultTypes;
4022 SmallVector<PHINode*, 4> PHIs;
4024 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4025 ConstantInt *CaseVal = CI.getCaseValue();
4026 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4027 MinCaseVal = CaseVal;
4028 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4029 MaxCaseVal = CaseVal;
4031 // Resulting value at phi nodes for this case value.
4032 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4034 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4038 // Append the result from this case to the list for each phi.
4039 for (const auto &I : Results) {
4040 PHINode *PHI = I.first;
4041 Constant *Value = I.second;
4042 if (!ResultLists.count(PHI))
4043 PHIs.push_back(PHI);
4044 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4048 // Keep track of the result types.
4049 for (PHINode *PHI : PHIs) {
4050 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4053 uint64_t NumResults = ResultLists[PHIs[0]].size();
4054 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4055 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4056 bool TableHasHoles = (NumResults < TableSize);
4058 // If the table has holes, we need a constant result for the default case
4059 // or a bitmask that fits in a register.
4060 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4061 bool HasDefaultResults = false;
4062 if (TableHasHoles) {
4063 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4064 &CommonDest, DefaultResultsList, DL);
4067 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4069 // As an extra penalty for the validity test we require more cases.
4070 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4072 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4076 for (const auto &I : DefaultResultsList) {
4077 PHINode *PHI = I.first;
4078 Constant *Result = I.second;
4079 DefaultResults[PHI] = Result;
4082 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4085 // Create the BB that does the lookups.
4086 Module &Mod = *CommonDest->getParent()->getParent();
4087 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4089 CommonDest->getParent(),
4092 // Compute the table index value.
4093 Builder.SetInsertPoint(SI);
4094 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4097 // Compute the maximum table size representable by the integer type we are
4099 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4100 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4101 assert(MaxTableSize >= TableSize &&
4102 "It is impossible for a switch to have more entries than the max "
4103 "representable value of its input integer type's size.");
4105 // If we have a fully covered lookup table, unconditionally branch to the
4106 // lookup table BB. Otherwise, check if the condition value is within the case
4107 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4109 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4110 if (GeneratingCoveredLookupTable) {
4111 Builder.CreateBr(LookupBB);
4112 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4113 // do not delete PHINodes here.
4114 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4115 true/*DontDeleteUselessPHIs*/);
4117 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4118 MinCaseVal->getType(), TableSize));
4119 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4122 // Populate the BB that does the lookups.
4123 Builder.SetInsertPoint(LookupBB);
4126 // Before doing the lookup we do the hole check.
4127 // The LookupBB is therefore re-purposed to do the hole check
4128 // and we create a new LookupBB.
4129 BasicBlock *MaskBB = LookupBB;
4130 MaskBB->setName("switch.hole_check");
4131 LookupBB = BasicBlock::Create(Mod.getContext(),
4133 CommonDest->getParent(),
4136 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4137 // unnecessary illegal types.
4138 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4139 APInt MaskInt(TableSizePowOf2, 0);
4140 APInt One(TableSizePowOf2, 1);
4141 // Build bitmask; fill in a 1 bit for every case.
4142 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4143 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4144 uint64_t Idx = (ResultList[I].first->getValue() -
4145 MinCaseVal->getValue()).getLimitedValue();
4146 MaskInt |= One << Idx;
4148 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4150 // Get the TableIndex'th bit of the bitmask.
4151 // If this bit is 0 (meaning hole) jump to the default destination,
4152 // else continue with table lookup.
4153 IntegerType *MapTy = TableMask->getType();
4154 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4155 "switch.maskindex");
4156 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4158 Value *LoBit = Builder.CreateTrunc(Shifted,
4159 Type::getInt1Ty(Mod.getContext()),
4161 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4163 Builder.SetInsertPoint(LookupBB);
4164 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4167 bool ReturnedEarly = false;
4168 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4169 PHINode *PHI = PHIs[I];
4171 // If using a bitmask, use any value to fill the lookup table holes.
4172 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4173 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
4176 Value *Result = Table.BuildLookup(TableIndex, Builder);
4178 // If the result is used to return immediately from the function, we want to
4179 // do that right here.
4180 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4181 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4182 Builder.CreateRet(Result);
4183 ReturnedEarly = true;
4187 PHI->addIncoming(Result, LookupBB);
4191 Builder.CreateBr(CommonDest);
4193 // Remove the switch.
4194 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4195 BasicBlock *Succ = SI->getSuccessor(i);
4197 if (Succ == SI->getDefaultDest())
4199 Succ->removePredecessor(SI->getParent());
4201 SI->eraseFromParent();
4205 ++NumLookupTablesHoles;
4209 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4210 BasicBlock *BB = SI->getParent();
4212 if (isValueEqualityComparison(SI)) {
4213 // If we only have one predecessor, and if it is a branch on this value,
4214 // see if that predecessor totally determines the outcome of this switch.
4215 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4216 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4217 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4219 Value *Cond = SI->getCondition();
4220 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4221 if (SimplifySwitchOnSelect(SI, Select))
4222 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4224 // If the block only contains the switch, see if we can fold the block
4225 // away into any preds.
4226 BasicBlock::iterator BBI = BB->begin();
4227 // Ignore dbg intrinsics.
4228 while (isa<DbgInfoIntrinsic>(BBI))
4231 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4232 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4235 // Try to transform the switch into an icmp and a branch.
4236 if (TurnSwitchRangeIntoICmp(SI, Builder))
4237 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4239 // Remove unreachable cases.
4240 if (EliminateDeadSwitchCases(SI, DL, AT))
4241 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4243 if (SwitchToSelect(SI, Builder, DL, AT))
4244 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4246 if (ForwardSwitchConditionToPHI(SI))
4247 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4249 if (SwitchToLookupTable(SI, Builder, TTI, DL))
4250 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4255 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4256 BasicBlock *BB = IBI->getParent();
4257 bool Changed = false;
4259 // Eliminate redundant destinations.
4260 SmallPtrSet<Value *, 8> Succs;
4261 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4262 BasicBlock *Dest = IBI->getDestination(i);
4263 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4264 Dest->removePredecessor(BB);
4265 IBI->removeDestination(i);
4271 if (IBI->getNumDestinations() == 0) {
4272 // If the indirectbr has no successors, change it to unreachable.
4273 new UnreachableInst(IBI->getContext(), IBI);
4274 EraseTerminatorInstAndDCECond(IBI);
4278 if (IBI->getNumDestinations() == 1) {
4279 // If the indirectbr has one successor, change it to a direct branch.
4280 BranchInst::Create(IBI->getDestination(0), IBI);
4281 EraseTerminatorInstAndDCECond(IBI);
4285 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4286 if (SimplifyIndirectBrOnSelect(IBI, SI))
4287 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4292 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4293 BasicBlock *BB = BI->getParent();
4295 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4298 // If the Terminator is the only non-phi instruction, simplify the block.
4299 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4300 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4301 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4304 // If the only instruction in the block is a seteq/setne comparison
4305 // against a constant, try to simplify the block.
4306 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4307 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4308 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4310 if (I->isTerminator() &&
4311 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4312 BonusInstThreshold, DL, AT))
4316 // If this basic block is ONLY a compare and a branch, and if a predecessor
4317 // branches to us and our successor, fold the comparison into the
4318 // predecessor and use logical operations to update the incoming value
4319 // for PHI nodes in common successor.
4320 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4321 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4326 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4327 BasicBlock *BB = BI->getParent();
4329 // Conditional branch
4330 if (isValueEqualityComparison(BI)) {
4331 // If we only have one predecessor, and if it is a branch on this value,
4332 // see if that predecessor totally determines the outcome of this
4334 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4335 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4336 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4338 // This block must be empty, except for the setcond inst, if it exists.
4339 // Ignore dbg intrinsics.
4340 BasicBlock::iterator I = BB->begin();
4341 // Ignore dbg intrinsics.
4342 while (isa<DbgInfoIntrinsic>(I))
4345 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4346 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4347 } else if (&*I == cast<Instruction>(BI->getCondition())){
4349 // Ignore dbg intrinsics.
4350 while (isa<DbgInfoIntrinsic>(I))
4352 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4353 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4357 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4358 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4361 // If this basic block is ONLY a compare and a branch, and if a predecessor
4362 // branches to us and one of our successors, fold the comparison into the
4363 // predecessor and use logical operations to pick the right destination.
4364 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4365 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4367 // We have a conditional branch to two blocks that are only reachable
4368 // from BI. We know that the condbr dominates the two blocks, so see if
4369 // there is any identical code in the "then" and "else" blocks. If so, we
4370 // can hoist it up to the branching block.
4371 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4372 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4373 if (HoistThenElseCodeToIf(BI, DL))
4374 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4376 // If Successor #1 has multiple preds, we may be able to conditionally
4377 // execute Successor #0 if it branches to Successor #1.
4378 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4379 if (Succ0TI->getNumSuccessors() == 1 &&
4380 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4381 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4382 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4384 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4385 // If Successor #0 has multiple preds, we may be able to conditionally
4386 // execute Successor #1 if it branches to Successor #0.
4387 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4388 if (Succ1TI->getNumSuccessors() == 1 &&
4389 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4390 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4391 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4394 // If this is a branch on a phi node in the current block, thread control
4395 // through this block if any PHI node entries are constants.
4396 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4397 if (PN->getParent() == BI->getParent())
4398 if (FoldCondBranchOnPHI(BI, DL))
4399 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4401 // Scan predecessor blocks for conditional branches.
4402 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4403 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4404 if (PBI != BI && PBI->isConditional())
4405 if (SimplifyCondBranchToCondBranch(PBI, BI))
4406 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4411 /// Check if passing a value to an instruction will cause undefined behavior.
4412 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4413 Constant *C = dyn_cast<Constant>(V);
4420 if (C->isNullValue()) {
4421 // Only look at the first use, avoid hurting compile time with long uselists
4422 User *Use = *I->user_begin();
4424 // Now make sure that there are no instructions in between that can alter
4425 // control flow (eg. calls)
4426 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4427 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4430 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4432 if (GEP->getPointerOperand() == I)
4433 return passingValueIsAlwaysUndefined(V, GEP);
4435 // Look through bitcasts.
4436 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4437 return passingValueIsAlwaysUndefined(V, BC);
4439 // Load from null is undefined.
4440 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4441 if (!LI->isVolatile())
4442 return LI->getPointerAddressSpace() == 0;
4444 // Store to null is undefined.
4445 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4446 if (!SI->isVolatile())
4447 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4452 /// If BB has an incoming value that will always trigger undefined behavior
4453 /// (eg. null pointer dereference), remove the branch leading here.
4454 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4455 for (BasicBlock::iterator i = BB->begin();
4456 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4457 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4458 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4459 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4460 IRBuilder<> Builder(T);
4461 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4462 BB->removePredecessor(PHI->getIncomingBlock(i));
4463 // Turn uncoditional branches into unreachables and remove the dead
4464 // destination from conditional branches.
4465 if (BI->isUnconditional())
4466 Builder.CreateUnreachable();
4468 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4469 BI->getSuccessor(0));
4470 BI->eraseFromParent();
4473 // TODO: SwitchInst.
4479 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4480 bool Changed = false;
4482 assert(BB && BB->getParent() && "Block not embedded in function!");
4483 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4485 // Remove basic blocks that have no predecessors (except the entry block)...
4486 // or that just have themself as a predecessor. These are unreachable.
4487 if ((pred_begin(BB) == pred_end(BB) &&
4488 BB != &BB->getParent()->getEntryBlock()) ||
4489 BB->getSinglePredecessor() == BB) {
4490 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4491 DeleteDeadBlock(BB);
4495 // Check to see if we can constant propagate this terminator instruction
4497 Changed |= ConstantFoldTerminator(BB, true);
4499 // Check for and eliminate duplicate PHI nodes in this block.
4500 Changed |= EliminateDuplicatePHINodes(BB);
4502 // Check for and remove branches that will always cause undefined behavior.
4503 Changed |= removeUndefIntroducingPredecessor(BB);
4505 // Merge basic blocks into their predecessor if there is only one distinct
4506 // pred, and if there is only one distinct successor of the predecessor, and
4507 // if there are no PHI nodes.
4509 if (MergeBlockIntoPredecessor(BB))
4512 IRBuilder<> Builder(BB);
4514 // If there is a trivial two-entry PHI node in this basic block, and we can
4515 // eliminate it, do so now.
4516 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4517 if (PN->getNumIncomingValues() == 2)
4518 Changed |= FoldTwoEntryPHINode(PN, DL);
4520 Builder.SetInsertPoint(BB->getTerminator());
4521 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4522 if (BI->isUnconditional()) {
4523 if (SimplifyUncondBranch(BI, Builder)) return true;
4525 if (SimplifyCondBranch(BI, Builder)) return true;
4527 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4528 if (SimplifyReturn(RI, Builder)) return true;
4529 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4530 if (SimplifyResume(RI, Builder)) return true;
4531 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4532 if (SimplifySwitch(SI, Builder)) return true;
4533 } else if (UnreachableInst *UI =
4534 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4535 if (SimplifyUnreachable(UI)) return true;
4536 } else if (IndirectBrInst *IBI =
4537 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4538 if (SimplifyIndirectBr(IBI)) return true;
4544 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4545 /// example, it adjusts branches to branches to eliminate the extra hop, it
4546 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4547 /// of the CFG. It returns true if a modification was made.
4549 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4550 unsigned BonusInstThreshold,
4551 const DataLayout *DL, AssumptionTracker *AT) {
4552 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);