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 // Try to match Instruction I as a comparison against a constant and populates
363 // Vals with the set of value that match (or does not depending on isEQ).
364 // Return nullptr on failure, or return the Value the comparison matched against
366 // CurrValue, if supplied, is the value we want to match against. The function
367 // is expected to fail if a match is found but the value compared to is not the
368 // one expected. If CurrValue is supplied, the return value has to be either
369 // nullptr or CurrValue
370 static Value* GatherConstantComparesMatch(Instruction *I,
372 SmallVectorImpl<ConstantInt*> &Vals,
373 const DataLayout *DL,
377 // If this is an icmp against a constant, handle this as one of the cases.
380 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
381 (C = GetConstantInt(I->getOperand(1), DL)))) {
388 // Pattern match a special case
389 // (x & ~2^x) == y --> x == y || x == y|2^x
390 // This undoes a transformation done by instcombine to fuse 2 compares.
391 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
392 if (match(ICI->getOperand(0),
393 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
394 APInt Not = ~RHSC->getValue();
395 if (Not.isPowerOf2()) {
396 // If we already have a value for the switch, it has to match!
397 if(CurrValue && CurrValue != RHSVal)
401 Vals.push_back(ConstantInt::get(C->getContext(),
402 C->getValue() | Not));
408 // If we already have a value for the switch, it has to match!
409 if(CurrValue && CurrValue != ICI->getOperand(0))
414 return ICI->getOperand(0);
417 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
418 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
421 // Shift the range if the compare is fed by an add. This is the range
422 // compare idiom as emitted by instcombine.
423 Value *CandidateVal = I->getOperand(0);
424 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
425 Span = Span.subtract(RHSC->getValue());
426 CandidateVal = RHSVal;
429 // If we already have a value for the switch, it has to match!
430 if(CurrValue && CurrValue != CandidateVal)
433 // If this is an and/!= check, then we are looking to build the set of
434 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
437 Span = Span.inverse();
439 // If there are a ton of values, we don't want to make a ginormous switch.
440 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
444 // Add all values from the range to the set
445 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
446 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
453 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
454 /// collection of icmp eq/ne instructions that compare a value against a
455 /// constant, return the value being compared, and stick the constant into the
457 /// One "Extra" case is allowed to differ from the other.
459 GatherConstantCompares(Value *V, SmallVectorImpl<ConstantInt*> &Vals, Value *&Extra,
460 const DataLayout *DL, unsigned &UsedICmps) {
461 Instruction *I = dyn_cast<Instruction>(V);
462 if (!I) return nullptr;
464 bool isEQ = (I->getOpcode() == Instruction::Or);
466 // Keep a stack (SmallVector for efficiency) for depth-first traversal
467 SmallVector<Value *, 8> DFT;
472 // Will hold the value used for the switch comparison
473 Value *CurrValue = nullptr;
475 while(!DFT.empty()) {
476 V = DFT.pop_back_val();
478 if (Instruction *I = dyn_cast<Instruction>(V)) {
480 // If it is a || (or && depending on isEQ), process the operands.
481 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
482 DFT.push_back(I->getOperand(1));
483 DFT.push_back(I->getOperand(0));
487 // Try to match the current instruction
488 if (Value *Matched = GatherConstantComparesMatch(I,
494 // Match succeed, continue the loop
500 // One element of the sequence of || (or &&) could not be match as a
501 // comparison against the same value as the others.
502 // We allow only one "Extra" case to be checked before the switch
503 if (Extra == nullptr) {
511 // Return the value to be used for the switch comparison (if any)
515 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
516 Instruction *Cond = nullptr;
517 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
518 Cond = dyn_cast<Instruction>(SI->getCondition());
519 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
520 if (BI->isConditional())
521 Cond = dyn_cast<Instruction>(BI->getCondition());
522 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
523 Cond = dyn_cast<Instruction>(IBI->getAddress());
526 TI->eraseFromParent();
527 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
530 /// isValueEqualityComparison - Return true if the specified terminator checks
531 /// to see if a value is equal to constant integer value.
532 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
534 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
535 // Do not permit merging of large switch instructions into their
536 // predecessors unless there is only one predecessor.
537 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
538 pred_end(SI->getParent())) <= 128)
539 CV = SI->getCondition();
540 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
541 if (BI->isConditional() && BI->getCondition()->hasOneUse())
542 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
543 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
544 CV = ICI->getOperand(0);
546 // Unwrap any lossless ptrtoint cast.
548 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
549 Value *Ptr = PTII->getPointerOperand();
550 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
557 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
558 /// decode all of the 'cases' that it represents and return the 'default' block.
559 BasicBlock *SimplifyCFGOpt::
560 GetValueEqualityComparisonCases(TerminatorInst *TI,
561 std::vector<ValueEqualityComparisonCase>
563 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
564 Cases.reserve(SI->getNumCases());
565 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
566 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
567 i.getCaseSuccessor()));
568 return SI->getDefaultDest();
571 BranchInst *BI = cast<BranchInst>(TI);
572 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
573 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
574 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
577 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
581 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
582 /// in the list that match the specified block.
583 static void EliminateBlockCases(BasicBlock *BB,
584 std::vector<ValueEqualityComparisonCase> &Cases) {
585 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
588 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
591 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
592 std::vector<ValueEqualityComparisonCase > &C2) {
593 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
595 // Make V1 be smaller than V2.
596 if (V1->size() > V2->size())
599 if (V1->size() == 0) return false;
600 if (V1->size() == 1) {
602 ConstantInt *TheVal = (*V1)[0].Value;
603 for (unsigned i = 0, e = V2->size(); i != e; ++i)
604 if (TheVal == (*V2)[i].Value)
608 // Otherwise, just sort both lists and compare element by element.
609 array_pod_sort(V1->begin(), V1->end());
610 array_pod_sort(V2->begin(), V2->end());
611 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
612 while (i1 != e1 && i2 != e2) {
613 if ((*V1)[i1].Value == (*V2)[i2].Value)
615 if ((*V1)[i1].Value < (*V2)[i2].Value)
623 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
624 /// terminator instruction and its block is known to only have a single
625 /// predecessor block, check to see if that predecessor is also a value
626 /// comparison with the same value, and if that comparison determines the
627 /// outcome of this comparison. If so, simplify TI. This does a very limited
628 /// form of jump threading.
629 bool SimplifyCFGOpt::
630 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
632 IRBuilder<> &Builder) {
633 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
634 if (!PredVal) return false; // Not a value comparison in predecessor.
636 Value *ThisVal = isValueEqualityComparison(TI);
637 assert(ThisVal && "This isn't a value comparison!!");
638 if (ThisVal != PredVal) return false; // Different predicates.
640 // TODO: Preserve branch weight metadata, similarly to how
641 // FoldValueComparisonIntoPredecessors preserves it.
643 // Find out information about when control will move from Pred to TI's block.
644 std::vector<ValueEqualityComparisonCase> PredCases;
645 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
647 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
649 // Find information about how control leaves this block.
650 std::vector<ValueEqualityComparisonCase> ThisCases;
651 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
652 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
654 // If TI's block is the default block from Pred's comparison, potentially
655 // simplify TI based on this knowledge.
656 if (PredDef == TI->getParent()) {
657 // If we are here, we know that the value is none of those cases listed in
658 // PredCases. If there are any cases in ThisCases that are in PredCases, we
660 if (!ValuesOverlap(PredCases, ThisCases))
663 if (isa<BranchInst>(TI)) {
664 // Okay, one of the successors of this condbr is dead. Convert it to a
666 assert(ThisCases.size() == 1 && "Branch can only have one case!");
667 // Insert the new branch.
668 Instruction *NI = Builder.CreateBr(ThisDef);
671 // Remove PHI node entries for the dead edge.
672 ThisCases[0].Dest->removePredecessor(TI->getParent());
674 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
675 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
677 EraseTerminatorInstAndDCECond(TI);
681 SwitchInst *SI = cast<SwitchInst>(TI);
682 // Okay, TI has cases that are statically dead, prune them away.
683 SmallPtrSet<Constant*, 16> DeadCases;
684 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
685 DeadCases.insert(PredCases[i].Value);
687 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
688 << "Through successor TI: " << *TI);
690 // Collect branch weights into a vector.
691 SmallVector<uint32_t, 8> Weights;
692 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
693 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
695 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
697 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
699 Weights.push_back(CI->getValue().getZExtValue());
701 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
703 if (DeadCases.count(i.getCaseValue())) {
705 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
708 i.getCaseSuccessor()->removePredecessor(TI->getParent());
712 if (HasWeight && Weights.size() >= 2)
713 SI->setMetadata(LLVMContext::MD_prof,
714 MDBuilder(SI->getParent()->getContext()).
715 createBranchWeights(Weights));
717 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
721 // Otherwise, TI's block must correspond to some matched value. Find out
722 // which value (or set of values) this is.
723 ConstantInt *TIV = nullptr;
724 BasicBlock *TIBB = TI->getParent();
725 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
726 if (PredCases[i].Dest == TIBB) {
728 return false; // Cannot handle multiple values coming to this block.
729 TIV = PredCases[i].Value;
731 assert(TIV && "No edge from pred to succ?");
733 // Okay, we found the one constant that our value can be if we get into TI's
734 // BB. Find out which successor will unconditionally be branched to.
735 BasicBlock *TheRealDest = nullptr;
736 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
737 if (ThisCases[i].Value == TIV) {
738 TheRealDest = ThisCases[i].Dest;
742 // If not handled by any explicit cases, it is handled by the default case.
743 if (!TheRealDest) TheRealDest = ThisDef;
745 // Remove PHI node entries for dead edges.
746 BasicBlock *CheckEdge = TheRealDest;
747 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
748 if (*SI != CheckEdge)
749 (*SI)->removePredecessor(TIBB);
753 // Insert the new branch.
754 Instruction *NI = Builder.CreateBr(TheRealDest);
757 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
758 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
760 EraseTerminatorInstAndDCECond(TI);
765 /// ConstantIntOrdering - This class implements a stable ordering of constant
766 /// integers that does not depend on their address. This is important for
767 /// applications that sort ConstantInt's to ensure uniqueness.
768 struct ConstantIntOrdering {
769 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
770 return LHS->getValue().ult(RHS->getValue());
775 static int ConstantIntSortPredicate(ConstantInt *const *P1,
776 ConstantInt *const *P2) {
777 const ConstantInt *LHS = *P1;
778 const ConstantInt *RHS = *P2;
779 if (LHS->getValue().ult(RHS->getValue()))
781 if (LHS->getValue() == RHS->getValue())
786 static inline bool HasBranchWeights(const Instruction* I) {
787 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
788 if (ProfMD && ProfMD->getOperand(0))
789 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
790 return MDS->getString().equals("branch_weights");
795 /// Get Weights of a given TerminatorInst, the default weight is at the front
796 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
798 static void GetBranchWeights(TerminatorInst *TI,
799 SmallVectorImpl<uint64_t> &Weights) {
800 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
802 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
803 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
804 Weights.push_back(CI->getValue().getZExtValue());
807 // If TI is a conditional eq, the default case is the false case,
808 // and the corresponding branch-weight data is at index 2. We swap the
809 // default weight to be the first entry.
810 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
811 assert(Weights.size() == 2);
812 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
813 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
814 std::swap(Weights.front(), Weights.back());
818 /// Keep halving the weights until all can fit in uint32_t.
819 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
820 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
821 if (Max > UINT_MAX) {
822 unsigned Offset = 32 - countLeadingZeros(Max);
823 for (uint64_t &I : Weights)
828 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
829 /// equality comparison instruction (either a switch or a branch on "X == c").
830 /// See if any of the predecessors of the terminator block are value comparisons
831 /// on the same value. If so, and if safe to do so, fold them together.
832 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
833 IRBuilder<> &Builder) {
834 BasicBlock *BB = TI->getParent();
835 Value *CV = isValueEqualityComparison(TI); // CondVal
836 assert(CV && "Not a comparison?");
837 bool Changed = false;
839 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
840 while (!Preds.empty()) {
841 BasicBlock *Pred = Preds.pop_back_val();
843 // See if the predecessor is a comparison with the same value.
844 TerminatorInst *PTI = Pred->getTerminator();
845 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
847 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
848 // Figure out which 'cases' to copy from SI to PSI.
849 std::vector<ValueEqualityComparisonCase> BBCases;
850 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
852 std::vector<ValueEqualityComparisonCase> PredCases;
853 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
855 // Based on whether the default edge from PTI goes to BB or not, fill in
856 // PredCases and PredDefault with the new switch cases we would like to
858 SmallVector<BasicBlock*, 8> NewSuccessors;
860 // Update the branch weight metadata along the way
861 SmallVector<uint64_t, 8> Weights;
862 bool PredHasWeights = HasBranchWeights(PTI);
863 bool SuccHasWeights = HasBranchWeights(TI);
865 if (PredHasWeights) {
866 GetBranchWeights(PTI, Weights);
867 // branch-weight metadata is inconsistent here.
868 if (Weights.size() != 1 + PredCases.size())
869 PredHasWeights = SuccHasWeights = false;
870 } else if (SuccHasWeights)
871 // If there are no predecessor weights but there are successor weights,
872 // populate Weights with 1, which will later be scaled to the sum of
873 // successor's weights
874 Weights.assign(1 + PredCases.size(), 1);
876 SmallVector<uint64_t, 8> SuccWeights;
877 if (SuccHasWeights) {
878 GetBranchWeights(TI, SuccWeights);
879 // branch-weight metadata is inconsistent here.
880 if (SuccWeights.size() != 1 + BBCases.size())
881 PredHasWeights = SuccHasWeights = false;
882 } else if (PredHasWeights)
883 SuccWeights.assign(1 + BBCases.size(), 1);
885 if (PredDefault == BB) {
886 // If this is the default destination from PTI, only the edges in TI
887 // that don't occur in PTI, or that branch to BB will be activated.
888 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
889 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
890 if (PredCases[i].Dest != BB)
891 PTIHandled.insert(PredCases[i].Value);
893 // The default destination is BB, we don't need explicit targets.
894 std::swap(PredCases[i], PredCases.back());
896 if (PredHasWeights || SuccHasWeights) {
897 // Increase weight for the default case.
898 Weights[0] += Weights[i+1];
899 std::swap(Weights[i+1], Weights.back());
903 PredCases.pop_back();
907 // Reconstruct the new switch statement we will be building.
908 if (PredDefault != BBDefault) {
909 PredDefault->removePredecessor(Pred);
910 PredDefault = BBDefault;
911 NewSuccessors.push_back(BBDefault);
914 unsigned CasesFromPred = Weights.size();
915 uint64_t ValidTotalSuccWeight = 0;
916 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
917 if (!PTIHandled.count(BBCases[i].Value) &&
918 BBCases[i].Dest != BBDefault) {
919 PredCases.push_back(BBCases[i]);
920 NewSuccessors.push_back(BBCases[i].Dest);
921 if (SuccHasWeights || PredHasWeights) {
922 // The default weight is at index 0, so weight for the ith case
923 // should be at index i+1. Scale the cases from successor by
924 // PredDefaultWeight (Weights[0]).
925 Weights.push_back(Weights[0] * SuccWeights[i+1]);
926 ValidTotalSuccWeight += SuccWeights[i+1];
930 if (SuccHasWeights || PredHasWeights) {
931 ValidTotalSuccWeight += SuccWeights[0];
932 // Scale the cases from predecessor by ValidTotalSuccWeight.
933 for (unsigned i = 1; i < CasesFromPred; ++i)
934 Weights[i] *= ValidTotalSuccWeight;
935 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
936 Weights[0] *= SuccWeights[0];
939 // If this is not the default destination from PSI, only the edges
940 // in SI that occur in PSI with a destination of BB will be
942 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
943 std::map<ConstantInt*, uint64_t> WeightsForHandled;
944 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
945 if (PredCases[i].Dest == BB) {
946 PTIHandled.insert(PredCases[i].Value);
948 if (PredHasWeights || SuccHasWeights) {
949 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
950 std::swap(Weights[i+1], Weights.back());
954 std::swap(PredCases[i], PredCases.back());
955 PredCases.pop_back();
959 // Okay, now we know which constants were sent to BB from the
960 // predecessor. Figure out where they will all go now.
961 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
962 if (PTIHandled.count(BBCases[i].Value)) {
963 // If this is one we are capable of getting...
964 if (PredHasWeights || SuccHasWeights)
965 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
966 PredCases.push_back(BBCases[i]);
967 NewSuccessors.push_back(BBCases[i].Dest);
968 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
971 // If there are any constants vectored to BB that TI doesn't handle,
972 // they must go to the default destination of TI.
973 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
975 E = PTIHandled.end(); I != E; ++I) {
976 if (PredHasWeights || SuccHasWeights)
977 Weights.push_back(WeightsForHandled[*I]);
978 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
979 NewSuccessors.push_back(BBDefault);
983 // Okay, at this point, we know which new successor Pred will get. Make
984 // sure we update the number of entries in the PHI nodes for these
986 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
987 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
989 Builder.SetInsertPoint(PTI);
990 // Convert pointer to int before we switch.
991 if (CV->getType()->isPointerTy()) {
992 assert(DL && "Cannot switch on pointer without DataLayout");
993 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
997 // Now that the successors are updated, create the new Switch instruction.
998 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1000 NewSI->setDebugLoc(PTI->getDebugLoc());
1001 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1002 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
1004 if (PredHasWeights || SuccHasWeights) {
1005 // Halve the weights if any of them cannot fit in an uint32_t
1006 FitWeights(Weights);
1008 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1010 NewSI->setMetadata(LLVMContext::MD_prof,
1011 MDBuilder(BB->getContext()).
1012 createBranchWeights(MDWeights));
1015 EraseTerminatorInstAndDCECond(PTI);
1017 // Okay, last check. If BB is still a successor of PSI, then we must
1018 // have an infinite loop case. If so, add an infinitely looping block
1019 // to handle the case to preserve the behavior of the code.
1020 BasicBlock *InfLoopBlock = nullptr;
1021 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1022 if (NewSI->getSuccessor(i) == BB) {
1023 if (!InfLoopBlock) {
1024 // Insert it at the end of the function, because it's either code,
1025 // or it won't matter if it's hot. :)
1026 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1027 "infloop", BB->getParent());
1028 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1030 NewSI->setSuccessor(i, InfLoopBlock);
1039 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1040 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1041 // would need to do this), we can't hoist the invoke, as there is nowhere
1042 // to put the select in this case.
1043 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1044 Instruction *I1, Instruction *I2) {
1045 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1047 for (BasicBlock::iterator BBI = SI->begin();
1048 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1049 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1050 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1051 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1059 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1061 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1062 /// BB2, hoist any common code in the two blocks up into the branch block. The
1063 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1064 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1065 // This does very trivial matching, with limited scanning, to find identical
1066 // instructions in the two blocks. In particular, we don't want to get into
1067 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1068 // such, we currently just scan for obviously identical instructions in an
1070 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1071 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1073 BasicBlock::iterator BB1_Itr = BB1->begin();
1074 BasicBlock::iterator BB2_Itr = BB2->begin();
1076 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1077 // Skip debug info if it is not identical.
1078 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1079 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1080 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1081 while (isa<DbgInfoIntrinsic>(I1))
1083 while (isa<DbgInfoIntrinsic>(I2))
1086 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1087 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1090 BasicBlock *BIParent = BI->getParent();
1092 bool Changed = false;
1094 // If we are hoisting the terminator instruction, don't move one (making a
1095 // broken BB), instead clone it, and remove BI.
1096 if (isa<TerminatorInst>(I1))
1097 goto HoistTerminator;
1099 // For a normal instruction, we just move one to right before the branch,
1100 // then replace all uses of the other with the first. Finally, we remove
1101 // the now redundant second instruction.
1102 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1103 if (!I2->use_empty())
1104 I2->replaceAllUsesWith(I1);
1105 I1->intersectOptionalDataWith(I2);
1106 unsigned KnownIDs[] = {
1107 LLVMContext::MD_tbaa,
1108 LLVMContext::MD_range,
1109 LLVMContext::MD_fpmath,
1110 LLVMContext::MD_invariant_load,
1111 LLVMContext::MD_nonnull
1113 combineMetadata(I1, I2, KnownIDs);
1114 I2->eraseFromParent();
1119 // Skip debug info if it is not identical.
1120 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1121 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1122 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1123 while (isa<DbgInfoIntrinsic>(I1))
1125 while (isa<DbgInfoIntrinsic>(I2))
1128 } while (I1->isIdenticalToWhenDefined(I2));
1133 // It may not be possible to hoist an invoke.
1134 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1137 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1139 for (BasicBlock::iterator BBI = SI->begin();
1140 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1141 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1142 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1146 // Check for passingValueIsAlwaysUndefined here because we would rather
1147 // eliminate undefined control flow then converting it to a select.
1148 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1149 passingValueIsAlwaysUndefined(BB2V, PN))
1152 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1154 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1159 // Okay, it is safe to hoist the terminator.
1160 Instruction *NT = I1->clone();
1161 BIParent->getInstList().insert(BI, NT);
1162 if (!NT->getType()->isVoidTy()) {
1163 I1->replaceAllUsesWith(NT);
1164 I2->replaceAllUsesWith(NT);
1168 IRBuilder<true, NoFolder> Builder(NT);
1169 // Hoisting one of the terminators from our successor is a great thing.
1170 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1171 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1172 // nodes, so we insert select instruction to compute the final result.
1173 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1174 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1176 for (BasicBlock::iterator BBI = SI->begin();
1177 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1178 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1179 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1180 if (BB1V == BB2V) continue;
1182 // These values do not agree. Insert a select instruction before NT
1183 // that determines the right value.
1184 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1186 SI = cast<SelectInst>
1187 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1188 BB1V->getName()+"."+BB2V->getName()));
1190 // Make the PHI node use the select for all incoming values for BB1/BB2
1191 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1192 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1193 PN->setIncomingValue(i, SI);
1197 // Update any PHI nodes in our new successors.
1198 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1199 AddPredecessorToBlock(*SI, BIParent, BB1);
1201 EraseTerminatorInstAndDCECond(BI);
1205 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1206 /// check whether BBEnd has only two predecessors and the other predecessor
1207 /// ends with an unconditional branch. If it is true, sink any common code
1208 /// in the two predecessors to BBEnd.
1209 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1210 assert(BI1->isUnconditional());
1211 BasicBlock *BB1 = BI1->getParent();
1212 BasicBlock *BBEnd = BI1->getSuccessor(0);
1214 // Check that BBEnd has two predecessors and the other predecessor ends with
1215 // an unconditional branch.
1216 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1217 BasicBlock *Pred0 = *PI++;
1218 if (PI == PE) // Only one predecessor.
1220 BasicBlock *Pred1 = *PI++;
1221 if (PI != PE) // More than two predecessors.
1223 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1224 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1225 if (!BI2 || !BI2->isUnconditional())
1228 // Gather the PHI nodes in BBEnd.
1229 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1230 Instruction *FirstNonPhiInBBEnd = nullptr;
1231 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1233 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1234 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1235 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1236 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1238 FirstNonPhiInBBEnd = &*I;
1242 if (!FirstNonPhiInBBEnd)
1246 // This does very trivial matching, with limited scanning, to find identical
1247 // instructions in the two blocks. We scan backward for obviously identical
1248 // instructions in an identical order.
1249 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1250 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1251 RE2 = BB2->getInstList().rend();
1253 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1256 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1259 // Skip the unconditional branches.
1263 bool Changed = false;
1264 while (RI1 != RE1 && RI2 != RE2) {
1266 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1269 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1273 Instruction *I1 = &*RI1, *I2 = &*RI2;
1274 // I1 and I2 should have a single use in the same PHI node, and they
1275 // perform the same operation.
1276 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1277 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1278 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1279 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1280 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1281 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1282 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1283 !I1->hasOneUse() || !I2->hasOneUse() ||
1284 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1285 MapValueFromBB1ToBB2[I1].first != I2)
1288 // Check whether we should swap the operands of ICmpInst.
1289 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1290 bool SwapOpnds = false;
1291 if (ICmp1 && ICmp2 &&
1292 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1293 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1294 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1295 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1296 ICmp2->swapOperands();
1299 if (!I1->isSameOperationAs(I2)) {
1301 ICmp2->swapOperands();
1305 // The operands should be either the same or they need to be generated
1306 // with a PHI node after sinking. We only handle the case where there is
1307 // a single pair of different operands.
1308 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1309 unsigned Op1Idx = 0;
1310 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1311 if (I1->getOperand(I) == I2->getOperand(I))
1313 // Early exit if we have more-than one pair of different operands or
1314 // the different operand is already in MapValueFromBB1ToBB2.
1315 // Early exit if we need a PHI node to replace a constant.
1317 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1318 MapValueFromBB1ToBB2.end() ||
1319 isa<Constant>(I1->getOperand(I)) ||
1320 isa<Constant>(I2->getOperand(I))) {
1321 // If we can't sink the instructions, undo the swapping.
1323 ICmp2->swapOperands();
1326 DifferentOp1 = I1->getOperand(I);
1328 DifferentOp2 = I2->getOperand(I);
1331 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1332 // remove (I1, I2) from MapValueFromBB1ToBB2.
1334 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1335 DifferentOp1->getName() + ".sink",
1337 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1338 // I1 should use NewPN instead of DifferentOp1.
1339 I1->setOperand(Op1Idx, NewPN);
1340 NewPN->addIncoming(DifferentOp1, BB1);
1341 NewPN->addIncoming(DifferentOp2, BB2);
1342 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1344 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1345 MapValueFromBB1ToBB2.erase(I1);
1347 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1348 DEBUG(dbgs() << " " << *I2 << "\n";);
1349 // We need to update RE1 and RE2 if we are going to sink the first
1350 // instruction in the basic block down.
1351 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1352 // Sink the instruction.
1353 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1354 if (!OldPN->use_empty())
1355 OldPN->replaceAllUsesWith(I1);
1356 OldPN->eraseFromParent();
1358 if (!I2->use_empty())
1359 I2->replaceAllUsesWith(I1);
1360 I1->intersectOptionalDataWith(I2);
1361 // TODO: Use combineMetadata here to preserve what metadata we can
1362 // (analogous to the hoisting case above).
1363 I2->eraseFromParent();
1366 RE1 = BB1->getInstList().rend();
1368 RE2 = BB2->getInstList().rend();
1369 FirstNonPhiInBBEnd = I1;
1376 /// \brief Determine if we can hoist sink a sole store instruction out of a
1377 /// conditional block.
1379 /// We are looking for code like the following:
1381 /// store i32 %add, i32* %arrayidx2
1382 /// ... // No other stores or function calls (we could be calling a memory
1383 /// ... // function).
1384 /// %cmp = icmp ult %x, %y
1385 /// br i1 %cmp, label %EndBB, label %ThenBB
1387 /// store i32 %add5, i32* %arrayidx2
1391 /// We are going to transform this into:
1393 /// store i32 %add, i32* %arrayidx2
1395 /// %cmp = icmp ult %x, %y
1396 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1397 /// store i32 %add.add5, i32* %arrayidx2
1400 /// \return The pointer to the value of the previous store if the store can be
1401 /// hoisted into the predecessor block. 0 otherwise.
1402 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1403 BasicBlock *StoreBB, BasicBlock *EndBB) {
1404 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1408 // Volatile or atomic.
1409 if (!StoreToHoist->isSimple())
1412 Value *StorePtr = StoreToHoist->getPointerOperand();
1414 // Look for a store to the same pointer in BrBB.
1415 unsigned MaxNumInstToLookAt = 10;
1416 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1417 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1418 Instruction *CurI = &*RI;
1420 // Could be calling an instruction that effects memory like free().
1421 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1424 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1425 // Found the previous store make sure it stores to the same location.
1426 if (SI && SI->getPointerOperand() == StorePtr)
1427 // Found the previous store, return its value operand.
1428 return SI->getValueOperand();
1430 return nullptr; // Unknown store.
1436 /// \brief Speculate a conditional basic block flattening the CFG.
1438 /// Note that this is a very risky transform currently. Speculating
1439 /// instructions like this is most often not desirable. Instead, there is an MI
1440 /// pass which can do it with full awareness of the resource constraints.
1441 /// However, some cases are "obvious" and we should do directly. An example of
1442 /// this is speculating a single, reasonably cheap instruction.
1444 /// There is only one distinct advantage to flattening the CFG at the IR level:
1445 /// it makes very common but simplistic optimizations such as are common in
1446 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1447 /// modeling their effects with easier to reason about SSA value graphs.
1450 /// An illustration of this transform is turning this IR:
1453 /// %cmp = icmp ult %x, %y
1454 /// br i1 %cmp, label %EndBB, label %ThenBB
1456 /// %sub = sub %x, %y
1459 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1466 /// %cmp = icmp ult %x, %y
1467 /// %sub = sub %x, %y
1468 /// %cond = select i1 %cmp, 0, %sub
1472 /// \returns true if the conditional block is removed.
1473 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1474 const DataLayout *DL) {
1475 // Be conservative for now. FP select instruction can often be expensive.
1476 Value *BrCond = BI->getCondition();
1477 if (isa<FCmpInst>(BrCond))
1480 BasicBlock *BB = BI->getParent();
1481 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1483 // If ThenBB is actually on the false edge of the conditional branch, remember
1484 // to swap the select operands later.
1485 bool Invert = false;
1486 if (ThenBB != BI->getSuccessor(0)) {
1487 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1490 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1492 // Keep a count of how many times instructions are used within CondBB when
1493 // they are candidates for sinking into CondBB. Specifically:
1494 // - They are defined in BB, and
1495 // - They have no side effects, and
1496 // - All of their uses are in CondBB.
1497 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1499 unsigned SpeculationCost = 0;
1500 Value *SpeculatedStoreValue = nullptr;
1501 StoreInst *SpeculatedStore = nullptr;
1502 for (BasicBlock::iterator BBI = ThenBB->begin(),
1503 BBE = std::prev(ThenBB->end());
1504 BBI != BBE; ++BBI) {
1505 Instruction *I = BBI;
1507 if (isa<DbgInfoIntrinsic>(I))
1510 // Only speculatively execution a single instruction (not counting the
1511 // terminator) for now.
1513 if (SpeculationCost > 1)
1516 // Don't hoist the instruction if it's unsafe or expensive.
1517 if (!isSafeToSpeculativelyExecute(I, DL) &&
1518 !(HoistCondStores &&
1519 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1522 if (!SpeculatedStoreValue &&
1523 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
1526 // Store the store speculation candidate.
1527 if (SpeculatedStoreValue)
1528 SpeculatedStore = cast<StoreInst>(I);
1530 // Do not hoist the instruction if any of its operands are defined but not
1531 // used in BB. The transformation will prevent the operand from
1532 // being sunk into the use block.
1533 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1535 Instruction *OpI = dyn_cast<Instruction>(*i);
1536 if (!OpI || OpI->getParent() != BB ||
1537 OpI->mayHaveSideEffects())
1538 continue; // Not a candidate for sinking.
1540 ++SinkCandidateUseCounts[OpI];
1544 // Consider any sink candidates which are only used in CondBB as costs for
1545 // speculation. Note, while we iterate over a DenseMap here, we are summing
1546 // and so iteration order isn't significant.
1547 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1548 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1550 if (I->first->getNumUses() == I->second) {
1552 if (SpeculationCost > 1)
1556 // Check that the PHI nodes can be converted to selects.
1557 bool HaveRewritablePHIs = false;
1558 for (BasicBlock::iterator I = EndBB->begin();
1559 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1560 Value *OrigV = PN->getIncomingValueForBlock(BB);
1561 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1563 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1564 // Skip PHIs which are trivial.
1568 // Don't convert to selects if we could remove undefined behavior instead.
1569 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1570 passingValueIsAlwaysUndefined(ThenV, PN))
1573 HaveRewritablePHIs = true;
1574 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1575 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1576 if (!OrigCE && !ThenCE)
1577 continue; // Known safe and cheap.
1579 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1580 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1582 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1583 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
1584 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1587 // Account for the cost of an unfolded ConstantExpr which could end up
1588 // getting expanded into Instructions.
1589 // FIXME: This doesn't account for how many operations are combined in the
1590 // constant expression.
1592 if (SpeculationCost > 1)
1596 // If there are no PHIs to process, bail early. This helps ensure idempotence
1598 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1601 // If we get here, we can hoist the instruction and if-convert.
1602 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1604 // Insert a select of the value of the speculated store.
1605 if (SpeculatedStoreValue) {
1606 IRBuilder<true, NoFolder> Builder(BI);
1607 Value *TrueV = SpeculatedStore->getValueOperand();
1608 Value *FalseV = SpeculatedStoreValue;
1610 std::swap(TrueV, FalseV);
1611 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1612 "." + FalseV->getName());
1613 SpeculatedStore->setOperand(0, S);
1616 // Hoist the instructions.
1617 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1618 std::prev(ThenBB->end()));
1620 // Insert selects and rewrite the PHI operands.
1621 IRBuilder<true, NoFolder> Builder(BI);
1622 for (BasicBlock::iterator I = EndBB->begin();
1623 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1624 unsigned OrigI = PN->getBasicBlockIndex(BB);
1625 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1626 Value *OrigV = PN->getIncomingValue(OrigI);
1627 Value *ThenV = PN->getIncomingValue(ThenI);
1629 // Skip PHIs which are trivial.
1633 // Create a select whose true value is the speculatively executed value and
1634 // false value is the preexisting value. Swap them if the branch
1635 // destinations were inverted.
1636 Value *TrueV = ThenV, *FalseV = OrigV;
1638 std::swap(TrueV, FalseV);
1639 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1640 TrueV->getName() + "." + FalseV->getName());
1641 PN->setIncomingValue(OrigI, V);
1642 PN->setIncomingValue(ThenI, V);
1649 /// \returns True if this block contains a CallInst with the NoDuplicate
1651 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1652 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1653 const CallInst *CI = dyn_cast<CallInst>(I);
1656 if (CI->cannotDuplicate())
1662 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1663 /// across this block.
1664 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1665 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1668 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1669 if (isa<DbgInfoIntrinsic>(BBI))
1671 if (Size > 10) return false; // Don't clone large BB's.
1674 // We can only support instructions that do not define values that are
1675 // live outside of the current basic block.
1676 for (User *U : BBI->users()) {
1677 Instruction *UI = cast<Instruction>(U);
1678 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1681 // Looks ok, continue checking.
1687 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1688 /// that is defined in the same block as the branch and if any PHI entries are
1689 /// constants, thread edges corresponding to that entry to be branches to their
1690 /// ultimate destination.
1691 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1692 BasicBlock *BB = BI->getParent();
1693 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1694 // NOTE: we currently cannot transform this case if the PHI node is used
1695 // outside of the block.
1696 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1699 // Degenerate case of a single entry PHI.
1700 if (PN->getNumIncomingValues() == 1) {
1701 FoldSingleEntryPHINodes(PN->getParent());
1705 // Now we know that this block has multiple preds and two succs.
1706 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1708 if (HasNoDuplicateCall(BB)) return false;
1710 // Okay, this is a simple enough basic block. See if any phi values are
1712 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1713 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1714 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1716 // Okay, we now know that all edges from PredBB should be revectored to
1717 // branch to RealDest.
1718 BasicBlock *PredBB = PN->getIncomingBlock(i);
1719 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1721 if (RealDest == BB) continue; // Skip self loops.
1722 // Skip if the predecessor's terminator is an indirect branch.
1723 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1725 // The dest block might have PHI nodes, other predecessors and other
1726 // difficult cases. Instead of being smart about this, just insert a new
1727 // block that jumps to the destination block, effectively splitting
1728 // the edge we are about to create.
1729 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1730 RealDest->getName()+".critedge",
1731 RealDest->getParent(), RealDest);
1732 BranchInst::Create(RealDest, EdgeBB);
1734 // Update PHI nodes.
1735 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1737 // BB may have instructions that are being threaded over. Clone these
1738 // instructions into EdgeBB. We know that there will be no uses of the
1739 // cloned instructions outside of EdgeBB.
1740 BasicBlock::iterator InsertPt = EdgeBB->begin();
1741 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1742 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1743 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1744 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1747 // Clone the instruction.
1748 Instruction *N = BBI->clone();
1749 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1751 // Update operands due to translation.
1752 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1754 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1755 if (PI != TranslateMap.end())
1759 // Check for trivial simplification.
1760 if (Value *V = SimplifyInstruction(N, DL)) {
1761 TranslateMap[BBI] = V;
1762 delete N; // Instruction folded away, don't need actual inst
1764 // Insert the new instruction into its new home.
1765 EdgeBB->getInstList().insert(InsertPt, N);
1766 if (!BBI->use_empty())
1767 TranslateMap[BBI] = N;
1771 // Loop over all of the edges from PredBB to BB, changing them to branch
1772 // to EdgeBB instead.
1773 TerminatorInst *PredBBTI = PredBB->getTerminator();
1774 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1775 if (PredBBTI->getSuccessor(i) == BB) {
1776 BB->removePredecessor(PredBB);
1777 PredBBTI->setSuccessor(i, EdgeBB);
1780 // Recurse, simplifying any other constants.
1781 return FoldCondBranchOnPHI(BI, DL) | true;
1787 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1788 /// PHI node, see if we can eliminate it.
1789 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1790 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1791 // statement", which has a very simple dominance structure. Basically, we
1792 // are trying to find the condition that is being branched on, which
1793 // subsequently causes this merge to happen. We really want control
1794 // dependence information for this check, but simplifycfg can't keep it up
1795 // to date, and this catches most of the cases we care about anyway.
1796 BasicBlock *BB = PN->getParent();
1797 BasicBlock *IfTrue, *IfFalse;
1798 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1800 // Don't bother if the branch will be constant folded trivially.
1801 isa<ConstantInt>(IfCond))
1804 // Okay, we found that we can merge this two-entry phi node into a select.
1805 // Doing so would require us to fold *all* two entry phi nodes in this block.
1806 // At some point this becomes non-profitable (particularly if the target
1807 // doesn't support cmov's). Only do this transformation if there are two or
1808 // fewer PHI nodes in this block.
1809 unsigned NumPhis = 0;
1810 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1814 // Loop over the PHI's seeing if we can promote them all to select
1815 // instructions. While we are at it, keep track of the instructions
1816 // that need to be moved to the dominating block.
1817 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1818 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1819 MaxCostVal1 = PHINodeFoldingThreshold;
1821 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1822 PHINode *PN = cast<PHINode>(II++);
1823 if (Value *V = SimplifyInstruction(PN, DL)) {
1824 PN->replaceAllUsesWith(V);
1825 PN->eraseFromParent();
1829 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1831 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1836 // If we folded the first phi, PN dangles at this point. Refresh it. If
1837 // we ran out of PHIs then we simplified them all.
1838 PN = dyn_cast<PHINode>(BB->begin());
1839 if (!PN) return true;
1841 // Don't fold i1 branches on PHIs which contain binary operators. These can
1842 // often be turned into switches and other things.
1843 if (PN->getType()->isIntegerTy(1) &&
1844 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1845 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1846 isa<BinaryOperator>(IfCond)))
1849 // If we all PHI nodes are promotable, check to make sure that all
1850 // instructions in the predecessor blocks can be promoted as well. If
1851 // not, we won't be able to get rid of the control flow, so it's not
1852 // worth promoting to select instructions.
1853 BasicBlock *DomBlock = nullptr;
1854 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1855 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1856 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1859 DomBlock = *pred_begin(IfBlock1);
1860 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1861 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1862 // This is not an aggressive instruction that we can promote.
1863 // Because of this, we won't be able to get rid of the control
1864 // flow, so the xform is not worth it.
1869 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1872 DomBlock = *pred_begin(IfBlock2);
1873 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1874 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1875 // This is not an aggressive instruction that we can promote.
1876 // Because of this, we won't be able to get rid of the control
1877 // flow, so the xform is not worth it.
1882 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1883 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1885 // If we can still promote the PHI nodes after this gauntlet of tests,
1886 // do all of the PHI's now.
1887 Instruction *InsertPt = DomBlock->getTerminator();
1888 IRBuilder<true, NoFolder> Builder(InsertPt);
1890 // Move all 'aggressive' instructions, which are defined in the
1891 // conditional parts of the if's up to the dominating block.
1893 DomBlock->getInstList().splice(InsertPt,
1894 IfBlock1->getInstList(), IfBlock1->begin(),
1895 IfBlock1->getTerminator());
1897 DomBlock->getInstList().splice(InsertPt,
1898 IfBlock2->getInstList(), IfBlock2->begin(),
1899 IfBlock2->getTerminator());
1901 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1902 // Change the PHI node into a select instruction.
1903 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1904 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1907 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1908 PN->replaceAllUsesWith(NV);
1910 PN->eraseFromParent();
1913 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1914 // has been flattened. Change DomBlock to jump directly to our new block to
1915 // avoid other simplifycfg's kicking in on the diamond.
1916 TerminatorInst *OldTI = DomBlock->getTerminator();
1917 Builder.SetInsertPoint(OldTI);
1918 Builder.CreateBr(BB);
1919 OldTI->eraseFromParent();
1923 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1924 /// to two returning blocks, try to merge them together into one return,
1925 /// introducing a select if the return values disagree.
1926 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1927 IRBuilder<> &Builder) {
1928 assert(BI->isConditional() && "Must be a conditional branch");
1929 BasicBlock *TrueSucc = BI->getSuccessor(0);
1930 BasicBlock *FalseSucc = BI->getSuccessor(1);
1931 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1932 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1934 // Check to ensure both blocks are empty (just a return) or optionally empty
1935 // with PHI nodes. If there are other instructions, merging would cause extra
1936 // computation on one path or the other.
1937 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1939 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1942 Builder.SetInsertPoint(BI);
1943 // Okay, we found a branch that is going to two return nodes. If
1944 // there is no return value for this function, just change the
1945 // branch into a return.
1946 if (FalseRet->getNumOperands() == 0) {
1947 TrueSucc->removePredecessor(BI->getParent());
1948 FalseSucc->removePredecessor(BI->getParent());
1949 Builder.CreateRetVoid();
1950 EraseTerminatorInstAndDCECond(BI);
1954 // Otherwise, figure out what the true and false return values are
1955 // so we can insert a new select instruction.
1956 Value *TrueValue = TrueRet->getReturnValue();
1957 Value *FalseValue = FalseRet->getReturnValue();
1959 // Unwrap any PHI nodes in the return blocks.
1960 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1961 if (TVPN->getParent() == TrueSucc)
1962 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1963 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1964 if (FVPN->getParent() == FalseSucc)
1965 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1967 // In order for this transformation to be safe, we must be able to
1968 // unconditionally execute both operands to the return. This is
1969 // normally the case, but we could have a potentially-trapping
1970 // constant expression that prevents this transformation from being
1972 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1975 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1979 // Okay, we collected all the mapped values and checked them for sanity, and
1980 // defined to really do this transformation. First, update the CFG.
1981 TrueSucc->removePredecessor(BI->getParent());
1982 FalseSucc->removePredecessor(BI->getParent());
1984 // Insert select instructions where needed.
1985 Value *BrCond = BI->getCondition();
1987 // Insert a select if the results differ.
1988 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1989 } else if (isa<UndefValue>(TrueValue)) {
1990 TrueValue = FalseValue;
1992 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1993 FalseValue, "retval");
1997 Value *RI = !TrueValue ?
1998 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2002 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2003 << "\n " << *BI << "NewRet = " << *RI
2004 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2006 EraseTerminatorInstAndDCECond(BI);
2011 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2012 /// probabilities of the branch taking each edge. Fills in the two APInt
2013 /// parameters and return true, or returns false if no or invalid metadata was
2015 static bool ExtractBranchMetadata(BranchInst *BI,
2016 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2017 assert(BI->isConditional() &&
2018 "Looking for probabilities on unconditional branch?");
2019 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2020 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2021 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
2022 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
2023 if (!CITrue || !CIFalse) return false;
2024 ProbTrue = CITrue->getValue().getZExtValue();
2025 ProbFalse = CIFalse->getValue().getZExtValue();
2029 /// checkCSEInPredecessor - Return true if the given instruction is available
2030 /// in its predecessor block. If yes, the instruction will be removed.
2032 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2033 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2035 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2036 Instruction *PBI = &*I;
2037 // Check whether Inst and PBI generate the same value.
2038 if (Inst->isIdenticalTo(PBI)) {
2039 Inst->replaceAllUsesWith(PBI);
2040 Inst->eraseFromParent();
2047 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2048 /// predecessor branches to us and one of our successors, fold the block into
2049 /// the predecessor and use logical operations to pick the right destination.
2050 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2051 unsigned BonusInstThreshold) {
2052 BasicBlock *BB = BI->getParent();
2054 Instruction *Cond = nullptr;
2055 if (BI->isConditional())
2056 Cond = dyn_cast<Instruction>(BI->getCondition());
2058 // For unconditional branch, check for a simple CFG pattern, where
2059 // BB has a single predecessor and BB's successor is also its predecessor's
2060 // successor. If such pattern exisits, check for CSE between BB and its
2062 if (BasicBlock *PB = BB->getSinglePredecessor())
2063 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2064 if (PBI->isConditional() &&
2065 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2066 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2067 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2069 Instruction *Curr = I++;
2070 if (isa<CmpInst>(Curr)) {
2074 // Quit if we can't remove this instruction.
2075 if (!checkCSEInPredecessor(Curr, PB))
2084 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2085 Cond->getParent() != BB || !Cond->hasOneUse())
2088 // Make sure the instruction after the condition is the cond branch.
2089 BasicBlock::iterator CondIt = Cond; ++CondIt;
2091 // Ignore dbg intrinsics.
2092 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2097 // Only allow this transformation if computing the condition doesn't involve
2098 // too many instructions and these involved instructions can be executed
2099 // unconditionally. We denote all involved instructions except the condition
2100 // as "bonus instructions", and only allow this transformation when the
2101 // number of the bonus instructions does not exceed a certain threshold.
2102 unsigned NumBonusInsts = 0;
2103 for (auto I = BB->begin(); Cond != I; ++I) {
2104 // Ignore dbg intrinsics.
2105 if (isa<DbgInfoIntrinsic>(I))
2107 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2109 // I has only one use and can be executed unconditionally.
2110 Instruction *User = dyn_cast<Instruction>(I->user_back());
2111 if (User == nullptr || User->getParent() != BB)
2113 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2114 // to use any other instruction, User must be an instruction between next(I)
2117 // Early exits once we reach the limit.
2118 if (NumBonusInsts > BonusInstThreshold)
2122 // Cond is known to be a compare or binary operator. Check to make sure that
2123 // neither operand is a potentially-trapping constant expression.
2124 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2131 // Finally, don't infinitely unroll conditional loops.
2132 BasicBlock *TrueDest = BI->getSuccessor(0);
2133 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2134 if (TrueDest == BB || FalseDest == BB)
2137 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2138 BasicBlock *PredBlock = *PI;
2139 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2141 // Check that we have two conditional branches. If there is a PHI node in
2142 // the common successor, verify that the same value flows in from both
2144 SmallVector<PHINode*, 4> PHIs;
2145 if (!PBI || PBI->isUnconditional() ||
2146 (BI->isConditional() &&
2147 !SafeToMergeTerminators(BI, PBI)) ||
2148 (!BI->isConditional() &&
2149 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2152 // Determine if the two branches share a common destination.
2153 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2154 bool InvertPredCond = false;
2156 if (BI->isConditional()) {
2157 if (PBI->getSuccessor(0) == TrueDest)
2158 Opc = Instruction::Or;
2159 else if (PBI->getSuccessor(1) == FalseDest)
2160 Opc = Instruction::And;
2161 else if (PBI->getSuccessor(0) == FalseDest)
2162 Opc = Instruction::And, InvertPredCond = true;
2163 else if (PBI->getSuccessor(1) == TrueDest)
2164 Opc = Instruction::Or, InvertPredCond = true;
2168 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2172 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2173 IRBuilder<> Builder(PBI);
2175 // If we need to invert the condition in the pred block to match, do so now.
2176 if (InvertPredCond) {
2177 Value *NewCond = PBI->getCondition();
2179 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2180 CmpInst *CI = cast<CmpInst>(NewCond);
2181 CI->setPredicate(CI->getInversePredicate());
2183 NewCond = Builder.CreateNot(NewCond,
2184 PBI->getCondition()->getName()+".not");
2187 PBI->setCondition(NewCond);
2188 PBI->swapSuccessors();
2191 // If we have bonus instructions, clone them into the predecessor block.
2192 // Note that there may be mutliple predecessor blocks, so we cannot move
2193 // bonus instructions to a predecessor block.
2194 ValueToValueMapTy VMap; // maps original values to cloned values
2195 // We already make sure Cond is the last instruction before BI. Therefore,
2196 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2198 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2199 if (isa<DbgInfoIntrinsic>(BonusInst))
2201 Instruction *NewBonusInst = BonusInst->clone();
2202 RemapInstruction(NewBonusInst, VMap,
2203 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2204 VMap[BonusInst] = NewBonusInst;
2206 // If we moved a load, we cannot any longer claim any knowledge about
2207 // its potential value. The previous information might have been valid
2208 // only given the branch precondition.
2209 // For an analogous reason, we must also drop all the metadata whose
2210 // semantics we don't understand.
2211 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2213 PredBlock->getInstList().insert(PBI, NewBonusInst);
2214 NewBonusInst->takeName(BonusInst);
2215 BonusInst->setName(BonusInst->getName() + ".old");
2218 // Clone Cond into the predecessor basic block, and or/and the
2219 // two conditions together.
2220 Instruction *New = Cond->clone();
2221 RemapInstruction(New, VMap,
2222 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2223 PredBlock->getInstList().insert(PBI, New);
2224 New->takeName(Cond);
2225 Cond->setName(New->getName() + ".old");
2227 if (BI->isConditional()) {
2228 Instruction *NewCond =
2229 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2231 PBI->setCondition(NewCond);
2233 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2234 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2236 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2238 SmallVector<uint64_t, 8> NewWeights;
2240 if (PBI->getSuccessor(0) == BB) {
2241 if (PredHasWeights && SuccHasWeights) {
2242 // PBI: br i1 %x, BB, FalseDest
2243 // BI: br i1 %y, TrueDest, FalseDest
2244 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2245 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2246 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2247 // TrueWeight for PBI * FalseWeight for BI.
2248 // We assume that total weights of a BranchInst can fit into 32 bits.
2249 // Therefore, we will not have overflow using 64-bit arithmetic.
2250 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2251 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2253 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2254 PBI->setSuccessor(0, TrueDest);
2256 if (PBI->getSuccessor(1) == BB) {
2257 if (PredHasWeights && SuccHasWeights) {
2258 // PBI: br i1 %x, TrueDest, BB
2259 // BI: br i1 %y, TrueDest, FalseDest
2260 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2261 // FalseWeight for PBI * TrueWeight for BI.
2262 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2263 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2264 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2265 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2267 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2268 PBI->setSuccessor(1, FalseDest);
2270 if (NewWeights.size() == 2) {
2271 // Halve the weights if any of them cannot fit in an uint32_t
2272 FitWeights(NewWeights);
2274 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2275 PBI->setMetadata(LLVMContext::MD_prof,
2276 MDBuilder(BI->getContext()).
2277 createBranchWeights(MDWeights));
2279 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2281 // Update PHI nodes in the common successors.
2282 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2283 ConstantInt *PBI_C = cast<ConstantInt>(
2284 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2285 assert(PBI_C->getType()->isIntegerTy(1));
2286 Instruction *MergedCond = nullptr;
2287 if (PBI->getSuccessor(0) == TrueDest) {
2288 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2289 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2290 // is false: !PBI_Cond and BI_Value
2291 Instruction *NotCond =
2292 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2295 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2300 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2301 PBI->getCondition(), MergedCond,
2304 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2305 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2306 // is false: PBI_Cond and BI_Value
2308 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2309 PBI->getCondition(), New,
2311 if (PBI_C->isOne()) {
2312 Instruction *NotCond =
2313 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2316 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2317 NotCond, MergedCond,
2322 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2325 // Change PBI from Conditional to Unconditional.
2326 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2327 EraseTerminatorInstAndDCECond(PBI);
2331 // TODO: If BB is reachable from all paths through PredBlock, then we
2332 // could replace PBI's branch probabilities with BI's.
2334 // Copy any debug value intrinsics into the end of PredBlock.
2335 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2336 if (isa<DbgInfoIntrinsic>(*I))
2337 I->clone()->insertBefore(PBI);
2344 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2345 /// predecessor of another block, this function tries to simplify it. We know
2346 /// that PBI and BI are both conditional branches, and BI is in one of the
2347 /// successor blocks of PBI - PBI branches to BI.
2348 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2349 assert(PBI->isConditional() && BI->isConditional());
2350 BasicBlock *BB = BI->getParent();
2352 // If this block ends with a branch instruction, and if there is a
2353 // predecessor that ends on a branch of the same condition, make
2354 // this conditional branch redundant.
2355 if (PBI->getCondition() == BI->getCondition() &&
2356 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2357 // Okay, the outcome of this conditional branch is statically
2358 // knowable. If this block had a single pred, handle specially.
2359 if (BB->getSinglePredecessor()) {
2360 // Turn this into a branch on constant.
2361 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2362 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2364 return true; // Nuke the branch on constant.
2367 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2368 // in the constant and simplify the block result. Subsequent passes of
2369 // simplifycfg will thread the block.
2370 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2371 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2372 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2373 std::distance(PB, PE),
2374 BI->getCondition()->getName() + ".pr",
2376 // Okay, we're going to insert the PHI node. Since PBI is not the only
2377 // predecessor, compute the PHI'd conditional value for all of the preds.
2378 // Any predecessor where the condition is not computable we keep symbolic.
2379 for (pred_iterator PI = PB; PI != PE; ++PI) {
2380 BasicBlock *P = *PI;
2381 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2382 PBI != BI && PBI->isConditional() &&
2383 PBI->getCondition() == BI->getCondition() &&
2384 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2385 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2386 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2389 NewPN->addIncoming(BI->getCondition(), P);
2393 BI->setCondition(NewPN);
2398 // If this is a conditional branch in an empty block, and if any
2399 // predecessors are a conditional branch to one of our destinations,
2400 // fold the conditions into logical ops and one cond br.
2401 BasicBlock::iterator BBI = BB->begin();
2402 // Ignore dbg intrinsics.
2403 while (isa<DbgInfoIntrinsic>(BBI))
2409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2414 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2416 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2417 PBIOp = 0, BIOp = 1;
2418 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2419 PBIOp = 1, BIOp = 0;
2420 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2425 // Check to make sure that the other destination of this branch
2426 // isn't BB itself. If so, this is an infinite loop that will
2427 // keep getting unwound.
2428 if (PBI->getSuccessor(PBIOp) == BB)
2431 // Do not perform this transformation if it would require
2432 // insertion of a large number of select instructions. For targets
2433 // without predication/cmovs, this is a big pessimization.
2435 // Also do not perform this transformation if any phi node in the common
2436 // destination block can trap when reached by BB or PBB (PR17073). In that
2437 // case, it would be unsafe to hoist the operation into a select instruction.
2439 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2440 unsigned NumPhis = 0;
2441 for (BasicBlock::iterator II = CommonDest->begin();
2442 isa<PHINode>(II); ++II, ++NumPhis) {
2443 if (NumPhis > 2) // Disable this xform.
2446 PHINode *PN = cast<PHINode>(II);
2447 Value *BIV = PN->getIncomingValueForBlock(BB);
2448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2452 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2453 Value *PBIV = PN->getIncomingValue(PBBIdx);
2454 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2459 // Finally, if everything is ok, fold the branches to logical ops.
2460 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2462 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2463 << "AND: " << *BI->getParent());
2466 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2467 // branch in it, where one edge (OtherDest) goes back to itself but the other
2468 // exits. We don't *know* that the program avoids the infinite loop
2469 // (even though that seems likely). If we do this xform naively, we'll end up
2470 // recursively unpeeling the loop. Since we know that (after the xform is
2471 // done) that the block *is* infinite if reached, we just make it an obviously
2472 // infinite loop with no cond branch.
2473 if (OtherDest == BB) {
2474 // Insert it at the end of the function, because it's either code,
2475 // or it won't matter if it's hot. :)
2476 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2477 "infloop", BB->getParent());
2478 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2479 OtherDest = InfLoopBlock;
2482 DEBUG(dbgs() << *PBI->getParent()->getParent());
2484 // BI may have other predecessors. Because of this, we leave
2485 // it alone, but modify PBI.
2487 // Make sure we get to CommonDest on True&True directions.
2488 Value *PBICond = PBI->getCondition();
2489 IRBuilder<true, NoFolder> Builder(PBI);
2491 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2493 Value *BICond = BI->getCondition();
2495 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2497 // Merge the conditions.
2498 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2500 // Modify PBI to branch on the new condition to the new dests.
2501 PBI->setCondition(Cond);
2502 PBI->setSuccessor(0, CommonDest);
2503 PBI->setSuccessor(1, OtherDest);
2505 // Update branch weight for PBI.
2506 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2507 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2509 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2511 if (PredHasWeights && SuccHasWeights) {
2512 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2513 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2514 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2515 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2516 // The weight to CommonDest should be PredCommon * SuccTotal +
2517 // PredOther * SuccCommon.
2518 // The weight to OtherDest should be PredOther * SuccOther.
2519 SmallVector<uint64_t, 2> NewWeights;
2520 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2521 PredOther * SuccCommon);
2522 NewWeights.push_back(PredOther * SuccOther);
2523 // Halve the weights if any of them cannot fit in an uint32_t
2524 FitWeights(NewWeights);
2526 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2527 PBI->setMetadata(LLVMContext::MD_prof,
2528 MDBuilder(BI->getContext()).
2529 createBranchWeights(MDWeights));
2532 // OtherDest may have phi nodes. If so, add an entry from PBI's
2533 // block that are identical to the entries for BI's block.
2534 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2536 // We know that the CommonDest already had an edge from PBI to
2537 // it. If it has PHIs though, the PHIs may have different
2538 // entries for BB and PBI's BB. If so, insert a select to make
2541 for (BasicBlock::iterator II = CommonDest->begin();
2542 (PN = dyn_cast<PHINode>(II)); ++II) {
2543 Value *BIV = PN->getIncomingValueForBlock(BB);
2544 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2545 Value *PBIV = PN->getIncomingValue(PBBIdx);
2547 // Insert a select in PBI to pick the right value.
2548 Value *NV = cast<SelectInst>
2549 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2550 PN->setIncomingValue(PBBIdx, NV);
2554 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2555 DEBUG(dbgs() << *PBI->getParent()->getParent());
2557 // This basic block is probably dead. We know it has at least
2558 // one fewer predecessor.
2562 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2563 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2564 // Takes care of updating the successors and removing the old terminator.
2565 // Also makes sure not to introduce new successors by assuming that edges to
2566 // non-successor TrueBBs and FalseBBs aren't reachable.
2567 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2568 BasicBlock *TrueBB, BasicBlock *FalseBB,
2569 uint32_t TrueWeight,
2570 uint32_t FalseWeight){
2571 // Remove any superfluous successor edges from the CFG.
2572 // First, figure out which successors to preserve.
2573 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2575 BasicBlock *KeepEdge1 = TrueBB;
2576 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2578 // Then remove the rest.
2579 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2580 BasicBlock *Succ = OldTerm->getSuccessor(I);
2581 // Make sure only to keep exactly one copy of each edge.
2582 if (Succ == KeepEdge1)
2583 KeepEdge1 = nullptr;
2584 else if (Succ == KeepEdge2)
2585 KeepEdge2 = nullptr;
2587 Succ->removePredecessor(OldTerm->getParent());
2590 IRBuilder<> Builder(OldTerm);
2591 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2593 // Insert an appropriate new terminator.
2594 if (!KeepEdge1 && !KeepEdge2) {
2595 if (TrueBB == FalseBB)
2596 // We were only looking for one successor, and it was present.
2597 // Create an unconditional branch to it.
2598 Builder.CreateBr(TrueBB);
2600 // We found both of the successors we were looking for.
2601 // Create a conditional branch sharing the condition of the select.
2602 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2603 if (TrueWeight != FalseWeight)
2604 NewBI->setMetadata(LLVMContext::MD_prof,
2605 MDBuilder(OldTerm->getContext()).
2606 createBranchWeights(TrueWeight, FalseWeight));
2608 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2609 // Neither of the selected blocks were successors, so this
2610 // terminator must be unreachable.
2611 new UnreachableInst(OldTerm->getContext(), OldTerm);
2613 // One of the selected values was a successor, but the other wasn't.
2614 // Insert an unconditional branch to the one that was found;
2615 // the edge to the one that wasn't must be unreachable.
2617 // Only TrueBB was found.
2618 Builder.CreateBr(TrueBB);
2620 // Only FalseBB was found.
2621 Builder.CreateBr(FalseBB);
2624 EraseTerminatorInstAndDCECond(OldTerm);
2628 // SimplifySwitchOnSelect - Replaces
2629 // (switch (select cond, X, Y)) on constant X, Y
2630 // with a branch - conditional if X and Y lead to distinct BBs,
2631 // unconditional otherwise.
2632 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2633 // Check for constant integer values in the select.
2634 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2635 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2636 if (!TrueVal || !FalseVal)
2639 // Find the relevant condition and destinations.
2640 Value *Condition = Select->getCondition();
2641 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2642 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2644 // Get weight for TrueBB and FalseBB.
2645 uint32_t TrueWeight = 0, FalseWeight = 0;
2646 SmallVector<uint64_t, 8> Weights;
2647 bool HasWeights = HasBranchWeights(SI);
2649 GetBranchWeights(SI, Weights);
2650 if (Weights.size() == 1 + SI->getNumCases()) {
2651 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2652 getSuccessorIndex()];
2653 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2654 getSuccessorIndex()];
2658 // Perform the actual simplification.
2659 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2660 TrueWeight, FalseWeight);
2663 // SimplifyIndirectBrOnSelect - Replaces
2664 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2665 // blockaddress(@fn, BlockB)))
2667 // (br cond, BlockA, BlockB).
2668 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2669 // Check that both operands of the select are block addresses.
2670 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2671 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2675 // Extract the actual blocks.
2676 BasicBlock *TrueBB = TBA->getBasicBlock();
2677 BasicBlock *FalseBB = FBA->getBasicBlock();
2679 // Perform the actual simplification.
2680 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2684 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2685 /// instruction (a seteq/setne with a constant) as the only instruction in a
2686 /// block that ends with an uncond branch. We are looking for a very specific
2687 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2688 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2689 /// default value goes to an uncond block with a seteq in it, we get something
2692 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2694 /// %tmp = icmp eq i8 %A, 92
2697 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2699 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2700 /// the PHI, merging the third icmp into the switch.
2701 static bool TryToSimplifyUncondBranchWithICmpInIt(
2702 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2703 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
2704 BasicBlock *BB = ICI->getParent();
2706 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2708 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2710 Value *V = ICI->getOperand(0);
2711 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2713 // The pattern we're looking for is where our only predecessor is a switch on
2714 // 'V' and this block is the default case for the switch. In this case we can
2715 // fold the compared value into the switch to simplify things.
2716 BasicBlock *Pred = BB->getSinglePredecessor();
2717 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2719 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2720 if (SI->getCondition() != V)
2723 // If BB is reachable on a non-default case, then we simply know the value of
2724 // V in this block. Substitute it and constant fold the icmp instruction
2726 if (SI->getDefaultDest() != BB) {
2727 ConstantInt *VVal = SI->findCaseDest(BB);
2728 assert(VVal && "Should have a unique destination value");
2729 ICI->setOperand(0, VVal);
2731 if (Value *V = SimplifyInstruction(ICI, DL)) {
2732 ICI->replaceAllUsesWith(V);
2733 ICI->eraseFromParent();
2735 // BB is now empty, so it is likely to simplify away.
2736 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2739 // Ok, the block is reachable from the default dest. If the constant we're
2740 // comparing exists in one of the other edges, then we can constant fold ICI
2742 if (SI->findCaseValue(Cst) != SI->case_default()) {
2744 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2745 V = ConstantInt::getFalse(BB->getContext());
2747 V = ConstantInt::getTrue(BB->getContext());
2749 ICI->replaceAllUsesWith(V);
2750 ICI->eraseFromParent();
2751 // BB is now empty, so it is likely to simplify away.
2752 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2755 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2757 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2758 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2759 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2760 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2763 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2765 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2766 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2768 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2769 std::swap(DefaultCst, NewCst);
2771 // Replace ICI (which is used by the PHI for the default value) with true or
2772 // false depending on if it is EQ or NE.
2773 ICI->replaceAllUsesWith(DefaultCst);
2774 ICI->eraseFromParent();
2776 // Okay, the switch goes to this block on a default value. Add an edge from
2777 // the switch to the merge point on the compared value.
2778 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2779 BB->getParent(), BB);
2780 SmallVector<uint64_t, 8> Weights;
2781 bool HasWeights = HasBranchWeights(SI);
2783 GetBranchWeights(SI, Weights);
2784 if (Weights.size() == 1 + SI->getNumCases()) {
2785 // Split weight for default case to case for "Cst".
2786 Weights[0] = (Weights[0]+1) >> 1;
2787 Weights.push_back(Weights[0]);
2789 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2790 SI->setMetadata(LLVMContext::MD_prof,
2791 MDBuilder(SI->getContext()).
2792 createBranchWeights(MDWeights));
2795 SI->addCase(Cst, NewBB);
2797 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2798 Builder.SetInsertPoint(NewBB);
2799 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2800 Builder.CreateBr(SuccBlock);
2801 PHIUse->addIncoming(NewCst, NewBB);
2805 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2806 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2807 /// fold it into a switch instruction if so.
2808 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2809 IRBuilder<> &Builder) {
2810 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2811 if (!Cond) return false;
2814 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2815 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2816 // 'setne's and'ed together, collect them.
2817 Value *CompVal = nullptr;
2818 SmallVector<ConstantInt*, 8> Values;
2819 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2820 Value *ExtraCase = nullptr;
2821 unsigned UsedICmps = 0;
2823 // Try to gather values from a chain of and/or to be turned into a switch
2824 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, UsedICmps);
2826 // If we didn't have a multiply compared value, fail.
2827 if (!CompVal) return false;
2829 // Avoid turning single icmps into a switch.
2833 // There might be duplicate constants in the list, which the switch
2834 // instruction can't handle, remove them now.
2835 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2836 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2838 // If Extra was used, we require at least two switch values to do the
2839 // transformation. A switch with one value is just an cond branch.
2840 if (ExtraCase && Values.size() < 2) return false;
2842 // TODO: Preserve branch weight metadata, similarly to how
2843 // FoldValueComparisonIntoPredecessors preserves it.
2845 // Figure out which block is which destination.
2846 BasicBlock *DefaultBB = BI->getSuccessor(1);
2847 BasicBlock *EdgeBB = BI->getSuccessor(0);
2848 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2850 BasicBlock *BB = BI->getParent();
2852 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2853 << " cases into SWITCH. BB is:\n" << *BB);
2855 // If there are any extra values that couldn't be folded into the switch
2856 // then we evaluate them with an explicit branch first. Split the block
2857 // right before the condbr to handle it.
2859 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2860 // Remove the uncond branch added to the old block.
2861 TerminatorInst *OldTI = BB->getTerminator();
2862 Builder.SetInsertPoint(OldTI);
2865 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2867 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2869 OldTI->eraseFromParent();
2871 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2872 // for the edge we just added.
2873 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2875 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2876 << "\nEXTRABB = " << *BB);
2880 Builder.SetInsertPoint(BI);
2881 // Convert pointer to int before we switch.
2882 if (CompVal->getType()->isPointerTy()) {
2883 assert(DL && "Cannot switch on pointer without DataLayout");
2884 CompVal = Builder.CreatePtrToInt(CompVal,
2885 DL->getIntPtrType(CompVal->getType()),
2889 // Create the new switch instruction now.
2890 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2892 // Add all of the 'cases' to the switch instruction.
2893 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2894 New->addCase(Values[i], EdgeBB);
2896 // We added edges from PI to the EdgeBB. As such, if there were any
2897 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2898 // the number of edges added.
2899 for (BasicBlock::iterator BBI = EdgeBB->begin();
2900 isa<PHINode>(BBI); ++BBI) {
2901 PHINode *PN = cast<PHINode>(BBI);
2902 Value *InVal = PN->getIncomingValueForBlock(BB);
2903 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2904 PN->addIncoming(InVal, BB);
2907 // Erase the old branch instruction.
2908 EraseTerminatorInstAndDCECond(BI);
2910 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2914 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2915 // If this is a trivial landing pad that just continues unwinding the caught
2916 // exception then zap the landing pad, turning its invokes into calls.
2917 BasicBlock *BB = RI->getParent();
2918 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2919 if (RI->getValue() != LPInst)
2920 // Not a landing pad, or the resume is not unwinding the exception that
2921 // caused control to branch here.
2924 // Check that there are no other instructions except for debug intrinsics.
2925 BasicBlock::iterator I = LPInst, E = RI;
2927 if (!isa<DbgInfoIntrinsic>(I))
2930 // Turn all invokes that unwind here into calls and delete the basic block.
2931 bool InvokeRequiresTableEntry = false;
2932 bool Changed = false;
2933 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2934 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2936 if (II->hasFnAttr(Attribute::UWTable)) {
2937 // Don't remove an `invoke' instruction if the ABI requires an entry into
2939 InvokeRequiresTableEntry = true;
2943 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2945 // Insert a call instruction before the invoke.
2946 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2948 Call->setCallingConv(II->getCallingConv());
2949 Call->setAttributes(II->getAttributes());
2950 Call->setDebugLoc(II->getDebugLoc());
2952 // Anything that used the value produced by the invoke instruction now uses
2953 // the value produced by the call instruction. Note that we do this even
2954 // for void functions and calls with no uses so that the callgraph edge is
2956 II->replaceAllUsesWith(Call);
2957 BB->removePredecessor(II->getParent());
2959 // Insert a branch to the normal destination right before the invoke.
2960 BranchInst::Create(II->getNormalDest(), II);
2962 // Finally, delete the invoke instruction!
2963 II->eraseFromParent();
2967 if (!InvokeRequiresTableEntry)
2968 // The landingpad is now unreachable. Zap it.
2969 BB->eraseFromParent();
2974 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2975 BasicBlock *BB = RI->getParent();
2976 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2978 // Find predecessors that end with branches.
2979 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2980 SmallVector<BranchInst*, 8> CondBranchPreds;
2981 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2982 BasicBlock *P = *PI;
2983 TerminatorInst *PTI = P->getTerminator();
2984 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2985 if (BI->isUnconditional())
2986 UncondBranchPreds.push_back(P);
2988 CondBranchPreds.push_back(BI);
2992 // If we found some, do the transformation!
2993 if (!UncondBranchPreds.empty() && DupRet) {
2994 while (!UncondBranchPreds.empty()) {
2995 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2996 DEBUG(dbgs() << "FOLDING: " << *BB
2997 << "INTO UNCOND BRANCH PRED: " << *Pred);
2998 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3001 // If we eliminated all predecessors of the block, delete the block now.
3002 if (pred_begin(BB) == pred_end(BB))
3003 // We know there are no successors, so just nuke the block.
3004 BB->eraseFromParent();
3009 // Check out all of the conditional branches going to this return
3010 // instruction. If any of them just select between returns, change the
3011 // branch itself into a select/return pair.
3012 while (!CondBranchPreds.empty()) {
3013 BranchInst *BI = CondBranchPreds.pop_back_val();
3015 // Check to see if the non-BB successor is also a return block.
3016 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3017 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3018 SimplifyCondBranchToTwoReturns(BI, Builder))
3024 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3025 BasicBlock *BB = UI->getParent();
3027 bool Changed = false;
3029 // If there are any instructions immediately before the unreachable that can
3030 // be removed, do so.
3031 while (UI != BB->begin()) {
3032 BasicBlock::iterator BBI = UI;
3034 // Do not delete instructions that can have side effects which might cause
3035 // the unreachable to not be reachable; specifically, calls and volatile
3036 // operations may have this effect.
3037 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3039 if (BBI->mayHaveSideEffects()) {
3040 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3041 if (SI->isVolatile())
3043 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3044 if (LI->isVolatile())
3046 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3047 if (RMWI->isVolatile())
3049 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3050 if (CXI->isVolatile())
3052 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3053 !isa<LandingPadInst>(BBI)) {
3056 // Note that deleting LandingPad's here is in fact okay, although it
3057 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3058 // all the predecessors of this block will be the unwind edges of Invokes,
3059 // and we can therefore guarantee this block will be erased.
3062 // Delete this instruction (any uses are guaranteed to be dead)
3063 if (!BBI->use_empty())
3064 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3065 BBI->eraseFromParent();
3069 // If the unreachable instruction is the first in the block, take a gander
3070 // at all of the predecessors of this instruction, and simplify them.
3071 if (&BB->front() != UI) return Changed;
3073 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3074 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3075 TerminatorInst *TI = Preds[i]->getTerminator();
3076 IRBuilder<> Builder(TI);
3077 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3078 if (BI->isUnconditional()) {
3079 if (BI->getSuccessor(0) == BB) {
3080 new UnreachableInst(TI->getContext(), TI);
3081 TI->eraseFromParent();
3085 if (BI->getSuccessor(0) == BB) {
3086 Builder.CreateBr(BI->getSuccessor(1));
3087 EraseTerminatorInstAndDCECond(BI);
3088 } else if (BI->getSuccessor(1) == BB) {
3089 Builder.CreateBr(BI->getSuccessor(0));
3090 EraseTerminatorInstAndDCECond(BI);
3094 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3095 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3097 if (i.getCaseSuccessor() == BB) {
3098 BB->removePredecessor(SI->getParent());
3103 // If the default value is unreachable, figure out the most popular
3104 // destination and make it the default.
3105 if (SI->getDefaultDest() == BB) {
3106 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3107 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3109 std::pair<unsigned, unsigned> &entry =
3110 Popularity[i.getCaseSuccessor()];
3111 if (entry.first == 0) {
3113 entry.second = i.getCaseIndex();
3119 // Find the most popular block.
3120 unsigned MaxPop = 0;
3121 unsigned MaxIndex = 0;
3122 BasicBlock *MaxBlock = nullptr;
3123 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3124 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3125 if (I->second.first > MaxPop ||
3126 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3127 MaxPop = I->second.first;
3128 MaxIndex = I->second.second;
3129 MaxBlock = I->first;
3133 // Make this the new default, allowing us to delete any explicit
3135 SI->setDefaultDest(MaxBlock);
3138 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3140 if (isa<PHINode>(MaxBlock->begin()))
3141 for (unsigned i = 0; i != MaxPop-1; ++i)
3142 MaxBlock->removePredecessor(SI->getParent());
3144 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3146 if (i.getCaseSuccessor() == MaxBlock) {
3152 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3153 if (II->getUnwindDest() == BB) {
3154 // Convert the invoke to a call instruction. This would be a good
3155 // place to note that the call does not throw though.
3156 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3157 II->removeFromParent(); // Take out of symbol table
3159 // Insert the call now...
3160 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3161 Builder.SetInsertPoint(BI);
3162 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3163 Args, II->getName());
3164 CI->setCallingConv(II->getCallingConv());
3165 CI->setAttributes(II->getAttributes());
3166 // If the invoke produced a value, the call does now instead.
3167 II->replaceAllUsesWith(CI);
3174 // If this block is now dead, remove it.
3175 if (pred_begin(BB) == pred_end(BB) &&
3176 BB != &BB->getParent()->getEntryBlock()) {
3177 // We know there are no successors, so just nuke the block.
3178 BB->eraseFromParent();
3185 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3186 /// integer range comparison into a sub, an icmp and a branch.
3187 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3188 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3190 // Make sure all cases point to the same destination and gather the values.
3191 SmallVector<ConstantInt *, 16> Cases;
3192 SwitchInst::CaseIt I = SI->case_begin();
3193 Cases.push_back(I.getCaseValue());
3194 SwitchInst::CaseIt PrevI = I++;
3195 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3196 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3198 Cases.push_back(I.getCaseValue());
3200 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3202 // Sort the case values, then check if they form a range we can transform.
3203 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3204 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3205 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3209 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3210 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3212 Value *Sub = SI->getCondition();
3213 if (!Offset->isNullValue())
3214 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3216 // If NumCases overflowed, then all possible values jump to the successor.
3217 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3218 Cmp = ConstantInt::getTrue(SI->getContext());
3220 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3221 BranchInst *NewBI = Builder.CreateCondBr(
3222 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3224 // Update weight for the newly-created conditional branch.
3225 SmallVector<uint64_t, 8> Weights;
3226 bool HasWeights = HasBranchWeights(SI);
3228 GetBranchWeights(SI, Weights);
3229 if (Weights.size() == 1 + SI->getNumCases()) {
3230 // Combine all weights for the cases to be the true weight of NewBI.
3231 // We assume that the sum of all weights for a Terminator can fit into 32
3233 uint32_t NewTrueWeight = 0;
3234 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3235 NewTrueWeight += (uint32_t)Weights[I];
3236 NewBI->setMetadata(LLVMContext::MD_prof,
3237 MDBuilder(SI->getContext()).
3238 createBranchWeights(NewTrueWeight,
3239 (uint32_t)Weights[0]));
3243 // Prune obsolete incoming values off the successor's PHI nodes.
3244 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3245 isa<PHINode>(BBI); ++BBI) {
3246 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3247 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3249 SI->eraseFromParent();
3254 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3255 /// and use it to remove dead cases.
3256 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3257 AssumptionTracker *AT) {
3258 Value *Cond = SI->getCondition();
3259 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3260 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3261 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3263 // Gather dead cases.
3264 SmallVector<ConstantInt*, 8> DeadCases;
3265 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3266 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3267 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3268 DeadCases.push_back(I.getCaseValue());
3269 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3270 << I.getCaseValue() << "' is dead.\n");
3274 SmallVector<uint64_t, 8> Weights;
3275 bool HasWeight = HasBranchWeights(SI);
3277 GetBranchWeights(SI, Weights);
3278 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3281 // Remove dead cases from the switch.
3282 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3283 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3284 assert(Case != SI->case_default() &&
3285 "Case was not found. Probably mistake in DeadCases forming.");
3287 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3291 // Prune unused values from PHI nodes.
3292 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3293 SI->removeCase(Case);
3295 if (HasWeight && Weights.size() >= 2) {
3296 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3297 SI->setMetadata(LLVMContext::MD_prof,
3298 MDBuilder(SI->getParent()->getContext()).
3299 createBranchWeights(MDWeights));
3302 return !DeadCases.empty();
3305 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3306 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3307 /// by an unconditional branch), look at the phi node for BB in the successor
3308 /// block and see if the incoming value is equal to CaseValue. If so, return
3309 /// the phi node, and set PhiIndex to BB's index in the phi node.
3310 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3313 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3314 return nullptr; // BB must be empty to be a candidate for simplification.
3315 if (!BB->getSinglePredecessor())
3316 return nullptr; // BB must be dominated by the switch.
3318 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3319 if (!Branch || !Branch->isUnconditional())
3320 return nullptr; // Terminator must be unconditional branch.
3322 BasicBlock *Succ = Branch->getSuccessor(0);
3324 BasicBlock::iterator I = Succ->begin();
3325 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3326 int Idx = PHI->getBasicBlockIndex(BB);
3327 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3329 Value *InValue = PHI->getIncomingValue(Idx);
3330 if (InValue != CaseValue) continue;
3339 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3340 /// instruction to a phi node dominated by the switch, if that would mean that
3341 /// some of the destination blocks of the switch can be folded away.
3342 /// Returns true if a change is made.
3343 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3344 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3345 ForwardingNodesMap ForwardingNodes;
3347 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3348 ConstantInt *CaseValue = I.getCaseValue();
3349 BasicBlock *CaseDest = I.getCaseSuccessor();
3352 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3356 ForwardingNodes[PHI].push_back(PhiIndex);
3359 bool Changed = false;
3361 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3362 E = ForwardingNodes.end(); I != E; ++I) {
3363 PHINode *Phi = I->first;
3364 SmallVectorImpl<int> &Indexes = I->second;
3366 if (Indexes.size() < 2) continue;
3368 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3369 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3376 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3377 /// initializing an array of constants like C.
3378 static bool ValidLookupTableConstant(Constant *C) {
3379 if (C->isThreadDependent())
3381 if (C->isDLLImportDependent())
3384 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3385 return CE->isGEPWithNoNotionalOverIndexing();
3387 return isa<ConstantFP>(C) ||
3388 isa<ConstantInt>(C) ||
3389 isa<ConstantPointerNull>(C) ||
3390 isa<GlobalValue>(C) ||
3394 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3395 /// its constant value in ConstantPool, returning 0 if it's not there.
3396 static Constant *LookupConstant(Value *V,
3397 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3398 if (Constant *C = dyn_cast<Constant>(V))
3400 return ConstantPool.lookup(V);
3403 /// ConstantFold - Try to fold instruction I into a constant. This works for
3404 /// simple instructions such as binary operations where both operands are
3405 /// constant or can be replaced by constants from the ConstantPool. Returns the
3406 /// resulting constant on success, 0 otherwise.
3408 ConstantFold(Instruction *I,
3409 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3410 const DataLayout *DL) {
3411 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3412 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3415 if (A->isAllOnesValue())
3416 return LookupConstant(Select->getTrueValue(), ConstantPool);
3417 if (A->isNullValue())
3418 return LookupConstant(Select->getFalseValue(), ConstantPool);
3422 SmallVector<Constant *, 4> COps;
3423 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3424 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3430 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3431 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3434 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3437 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3438 /// at the common destination basic block, *CommonDest, for one of the case
3439 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3440 /// case), of a switch instruction SI.
3442 GetCaseResults(SwitchInst *SI,
3443 ConstantInt *CaseVal,
3444 BasicBlock *CaseDest,
3445 BasicBlock **CommonDest,
3446 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3447 const DataLayout *DL) {
3448 // The block from which we enter the common destination.
3449 BasicBlock *Pred = SI->getParent();
3451 // If CaseDest is empty except for some side-effect free instructions through
3452 // which we can constant-propagate the CaseVal, continue to its successor.
3453 SmallDenseMap<Value*, Constant*> ConstantPool;
3454 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3455 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3457 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3458 // If the terminator is a simple branch, continue to the next block.
3459 if (T->getNumSuccessors() != 1)
3462 CaseDest = T->getSuccessor(0);
3463 } else if (isa<DbgInfoIntrinsic>(I)) {
3464 // Skip debug intrinsic.
3466 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3467 // Instruction is side-effect free and constant.
3468 ConstantPool.insert(std::make_pair(I, C));
3474 // If we did not have a CommonDest before, use the current one.
3476 *CommonDest = CaseDest;
3477 // If the destination isn't the common one, abort.
3478 if (CaseDest != *CommonDest)
3481 // Get the values for this case from phi nodes in the destination block.
3482 BasicBlock::iterator I = (*CommonDest)->begin();
3483 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3484 int Idx = PHI->getBasicBlockIndex(Pred);
3488 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3493 // Note: If the constant comes from constant-propagating the case value
3494 // through the CaseDest basic block, it will be safe to remove the
3495 // instructions in that block. They cannot be used (except in the phi nodes
3496 // we visit) outside CaseDest, because that block does not dominate its
3497 // successor. If it did, we would not be in this phi node.
3499 // Be conservative about which kinds of constants we support.
3500 if (!ValidLookupTableConstant(ConstVal))
3503 Res.push_back(std::make_pair(PHI, ConstVal));
3506 return Res.size() > 0;
3509 // MapCaseToResult - Helper function used to
3510 // add CaseVal to the list of cases that generate Result.
3511 static void MapCaseToResult(ConstantInt *CaseVal,
3512 SwitchCaseResultVectorTy &UniqueResults,
3514 for (auto &I : UniqueResults) {
3515 if (I.first == Result) {
3516 I.second.push_back(CaseVal);
3520 UniqueResults.push_back(std::make_pair(Result,
3521 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3524 // InitializeUniqueCases - Helper function that initializes a map containing
3525 // results for the PHI node of the common destination block for a switch
3526 // instruction. Returns false if multiple PHI nodes have been found or if
3527 // there is not a common destination block for the switch.
3528 static bool InitializeUniqueCases(
3529 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3530 BasicBlock *&CommonDest,
3531 SwitchCaseResultVectorTy &UniqueResults,
3532 Constant *&DefaultResult) {
3533 for (auto &I : SI->cases()) {
3534 ConstantInt *CaseVal = I.getCaseValue();
3536 // Resulting value at phi nodes for this case value.
3537 SwitchCaseResultsTy Results;
3538 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3542 // Only one value per case is permitted
3543 if (Results.size() > 1)
3545 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3547 // Check the PHI consistency.
3549 PHI = Results[0].first;
3550 else if (PHI != Results[0].first)
3553 // Find the default result value.
3554 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3555 BasicBlock *DefaultDest = SI->getDefaultDest();
3556 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3558 // If the default value is not found abort unless the default destination
3561 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3562 if ((!DefaultResult &&
3563 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3569 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3570 // transform a switch with only two cases (or two cases + default)
3571 // that produces a result into a value select.
3574 // case 10: %0 = icmp eq i32 %a, 10
3575 // return 10; %1 = select i1 %0, i32 10, i32 4
3576 // case 20: ----> %2 = icmp eq i32 %a, 20
3577 // return 2; %3 = select i1 %2, i32 2, i32 %1
3582 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3583 Constant *DefaultResult, Value *Condition,
3584 IRBuilder<> &Builder) {
3585 assert(ResultVector.size() == 2 &&
3586 "We should have exactly two unique results at this point");
3587 // If we are selecting between only two cases transform into a simple
3588 // select or a two-way select if default is possible.
3589 if (ResultVector[0].second.size() == 1 &&
3590 ResultVector[1].second.size() == 1) {
3591 ConstantInt *const FirstCase = ResultVector[0].second[0];
3592 ConstantInt *const SecondCase = ResultVector[1].second[0];
3594 bool DefaultCanTrigger = DefaultResult;
3595 Value *SelectValue = ResultVector[1].first;
3596 if (DefaultCanTrigger) {
3597 Value *const ValueCompare =
3598 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3599 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3600 DefaultResult, "switch.select");
3602 Value *const ValueCompare =
3603 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3604 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3611 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3612 // instruction that has been converted into a select, fixing up PHI nodes and
3614 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3616 IRBuilder<> &Builder) {
3617 BasicBlock *SelectBB = SI->getParent();
3618 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3619 PHI->removeIncomingValue(SelectBB);
3620 PHI->addIncoming(SelectValue, SelectBB);
3622 Builder.CreateBr(PHI->getParent());
3624 // Remove the switch.
3625 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3626 BasicBlock *Succ = SI->getSuccessor(i);
3628 if (Succ == PHI->getParent())
3630 Succ->removePredecessor(SelectBB);
3632 SI->eraseFromParent();
3635 /// SwitchToSelect - If the switch is only used to initialize one or more
3636 /// phi nodes in a common successor block with only two different
3637 /// constant values, replace the switch with select.
3638 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3639 const DataLayout *DL, AssumptionTracker *AT) {
3640 Value *const Cond = SI->getCondition();
3641 PHINode *PHI = nullptr;
3642 BasicBlock *CommonDest = nullptr;
3643 Constant *DefaultResult;
3644 SwitchCaseResultVectorTy UniqueResults;
3645 // Collect all the cases that will deliver the same value from the switch.
3646 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3649 // Selects choose between maximum two values.
3650 if (UniqueResults.size() != 2)
3652 assert(PHI != nullptr && "PHI for value select not found");
3654 Builder.SetInsertPoint(SI);
3655 Value *SelectValue = ConvertTwoCaseSwitch(
3657 DefaultResult, Cond, Builder);
3659 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3662 // The switch couldn't be converted into a select.
3667 /// SwitchLookupTable - This class represents a lookup table that can be used
3668 /// to replace a switch.
3669 class SwitchLookupTable {
3671 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3672 /// with the contents of Values, using DefaultValue to fill any holes in the
3674 SwitchLookupTable(Module &M,
3676 ConstantInt *Offset,
3677 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3678 Constant *DefaultValue,
3679 const DataLayout *DL);
3681 /// BuildLookup - Build instructions with Builder to retrieve the value at
3682 /// the position given by Index in the lookup table.
3683 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3685 /// WouldFitInRegister - Return true if a table with TableSize elements of
3686 /// type ElementType would fit in a target-legal register.
3687 static bool WouldFitInRegister(const DataLayout *DL,
3689 const Type *ElementType);
3692 // Depending on the contents of the table, it can be represented in
3695 // For tables where each element contains the same value, we just have to
3696 // store that single value and return it for each lookup.
3699 // For tables where there is a linear relationship between table index
3700 // and values. We calculate the result with a simple multiplication
3701 // and addition instead of a table lookup.
3704 // For small tables with integer elements, we can pack them into a bitmap
3705 // that fits into a target-legal register. Values are retrieved by
3706 // shift and mask operations.
3709 // The table is stored as an array of values. Values are retrieved by load
3710 // instructions from the table.
3714 // For SingleValueKind, this is the single value.
3715 Constant *SingleValue;
3717 // For BitMapKind, this is the bitmap.
3718 ConstantInt *BitMap;
3719 IntegerType *BitMapElementTy;
3721 // For LinearMapKind, these are the constants used to derive the value.
3722 ConstantInt *LinearOffset;
3723 ConstantInt *LinearMultiplier;
3725 // For ArrayKind, this is the array.
3726 GlobalVariable *Array;
3730 SwitchLookupTable::SwitchLookupTable(Module &M,
3732 ConstantInt *Offset,
3733 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3734 Constant *DefaultValue,
3735 const DataLayout *DL)
3736 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3737 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3738 assert(Values.size() && "Can't build lookup table without values!");
3739 assert(TableSize >= Values.size() && "Can't fit values in table!");
3741 // If all values in the table are equal, this is that value.
3742 SingleValue = Values.begin()->second;
3744 Type *ValueType = Values.begin()->second->getType();
3746 // Build up the table contents.
3747 SmallVector<Constant*, 64> TableContents(TableSize);
3748 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3749 ConstantInt *CaseVal = Values[I].first;
3750 Constant *CaseRes = Values[I].second;
3751 assert(CaseRes->getType() == ValueType);
3753 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3755 TableContents[Idx] = CaseRes;
3757 if (CaseRes != SingleValue)
3758 SingleValue = nullptr;
3761 // Fill in any holes in the table with the default result.
3762 if (Values.size() < TableSize) {
3763 assert(DefaultValue &&
3764 "Need a default value to fill the lookup table holes.");
3765 assert(DefaultValue->getType() == ValueType);
3766 for (uint64_t I = 0; I < TableSize; ++I) {
3767 if (!TableContents[I])
3768 TableContents[I] = DefaultValue;
3771 if (DefaultValue != SingleValue)
3772 SingleValue = nullptr;
3775 // If each element in the table contains the same value, we only need to store
3776 // that single value.
3778 Kind = SingleValueKind;
3782 // Check if we can derive the value with a linear transformation from the
3784 if (isa<IntegerType>(ValueType)) {
3785 bool LinearMappingPossible = true;
3788 assert(TableSize >= 2 && "Should be a SingleValue table.");
3789 // Check if there is the same distance between two consecutive values.
3790 for (uint64_t I = 0; I < TableSize; ++I) {
3791 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3793 // This is an undef. We could deal with it, but undefs in lookup tables
3794 // are very seldom. It's probably not worth the additional complexity.
3795 LinearMappingPossible = false;
3798 APInt Val = ConstVal->getValue();
3800 APInt Dist = Val - PrevVal;
3803 } else if (Dist != DistToPrev) {
3804 LinearMappingPossible = false;
3810 if (LinearMappingPossible) {
3811 LinearOffset = cast<ConstantInt>(TableContents[0]);
3812 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3813 Kind = LinearMapKind;
3819 // If the type is integer and the table fits in a register, build a bitmap.
3820 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3821 IntegerType *IT = cast<IntegerType>(ValueType);
3822 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3823 for (uint64_t I = TableSize; I > 0; --I) {
3824 TableInt <<= IT->getBitWidth();
3825 // Insert values into the bitmap. Undef values are set to zero.
3826 if (!isa<UndefValue>(TableContents[I - 1])) {
3827 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3828 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3831 BitMap = ConstantInt::get(M.getContext(), TableInt);
3832 BitMapElementTy = IT;
3838 // Store the table in an array.
3839 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3840 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3842 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3843 GlobalVariable::PrivateLinkage,
3846 Array->setUnnamedAddr(true);
3850 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3852 case SingleValueKind:
3854 case LinearMapKind: {
3855 // Derive the result value from the input value.
3856 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3857 false, "switch.idx.cast");
3858 if (!LinearMultiplier->isOne())
3859 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3860 if (!LinearOffset->isZero())
3861 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3865 // Type of the bitmap (e.g. i59).
3866 IntegerType *MapTy = BitMap->getType();
3868 // Cast Index to the same type as the bitmap.
3869 // Note: The Index is <= the number of elements in the table, so
3870 // truncating it to the width of the bitmask is safe.
3871 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3873 // Multiply the shift amount by the element width.
3874 ShiftAmt = Builder.CreateMul(ShiftAmt,
3875 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3879 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3880 "switch.downshift");
3882 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3886 // Make sure the table index will not overflow when treated as signed.
3887 IntegerType *IT = cast<IntegerType>(Index->getType());
3888 uint64_t TableSize = Array->getInitializer()->getType()
3889 ->getArrayNumElements();
3890 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3891 Index = Builder.CreateZExt(Index,
3892 IntegerType::get(IT->getContext(),
3893 IT->getBitWidth() + 1),
3894 "switch.tableidx.zext");
3896 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3897 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3899 return Builder.CreateLoad(GEP, "switch.load");
3902 llvm_unreachable("Unknown lookup table kind!");
3905 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3907 const Type *ElementType) {
3910 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3913 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3914 // are <= 15, we could try to narrow the type.
3916 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3917 if (TableSize >= UINT_MAX/IT->getBitWidth())
3919 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3922 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3923 /// for this switch, based on the number of cases, size of the table and the
3924 /// types of the results.
3925 static bool ShouldBuildLookupTable(SwitchInst *SI,
3927 const TargetTransformInfo &TTI,
3928 const DataLayout *DL,
3929 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3930 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3931 return false; // TableSize overflowed, or mul below might overflow.
3933 bool AllTablesFitInRegister = true;
3934 bool HasIllegalType = false;
3935 for (const auto &I : ResultTypes) {
3936 Type *Ty = I.second;
3938 // Saturate this flag to true.
3939 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3941 // Saturate this flag to false.
3942 AllTablesFitInRegister = AllTablesFitInRegister &&
3943 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3945 // If both flags saturate, we're done. NOTE: This *only* works with
3946 // saturating flags, and all flags have to saturate first due to the
3947 // non-deterministic behavior of iterating over a dense map.
3948 if (HasIllegalType && !AllTablesFitInRegister)
3952 // If each table would fit in a register, we should build it anyway.
3953 if (AllTablesFitInRegister)
3956 // Don't build a table that doesn't fit in-register if it has illegal types.
3960 // The table density should be at least 40%. This is the same criterion as for
3961 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3962 // FIXME: Find the best cut-off.
3963 return SI->getNumCases() * 10 >= TableSize * 4;
3966 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3967 /// phi nodes in a common successor block with different constant values,
3968 /// replace the switch with lookup tables.
3969 static bool SwitchToLookupTable(SwitchInst *SI,
3970 IRBuilder<> &Builder,
3971 const TargetTransformInfo &TTI,
3972 const DataLayout* DL) {
3973 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3975 // Only build lookup table when we have a target that supports it.
3976 if (!TTI.shouldBuildLookupTables())
3979 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3980 // split off a dense part and build a lookup table for that.
3982 // FIXME: This creates arrays of GEPs to constant strings, which means each
3983 // GEP needs a runtime relocation in PIC code. We should just build one big
3984 // string and lookup indices into that.
3986 // Ignore switches with less than three cases. Lookup tables will not make them
3987 // faster, so we don't analyze them.
3988 if (SI->getNumCases() < 3)
3991 // Figure out the corresponding result for each case value and phi node in the
3992 // common destination, as well as the the min and max case values.
3993 assert(SI->case_begin() != SI->case_end());
3994 SwitchInst::CaseIt CI = SI->case_begin();
3995 ConstantInt *MinCaseVal = CI.getCaseValue();
3996 ConstantInt *MaxCaseVal = CI.getCaseValue();
3998 BasicBlock *CommonDest = nullptr;
3999 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4000 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4001 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4002 SmallDenseMap<PHINode*, Type*> ResultTypes;
4003 SmallVector<PHINode*, 4> PHIs;
4005 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4006 ConstantInt *CaseVal = CI.getCaseValue();
4007 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4008 MinCaseVal = CaseVal;
4009 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4010 MaxCaseVal = CaseVal;
4012 // Resulting value at phi nodes for this case value.
4013 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4015 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4019 // Append the result from this case to the list for each phi.
4020 for (const auto &I : Results) {
4021 PHINode *PHI = I.first;
4022 Constant *Value = I.second;
4023 if (!ResultLists.count(PHI))
4024 PHIs.push_back(PHI);
4025 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4029 // Keep track of the result types.
4030 for (PHINode *PHI : PHIs) {
4031 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4034 uint64_t NumResults = ResultLists[PHIs[0]].size();
4035 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4036 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4037 bool TableHasHoles = (NumResults < TableSize);
4039 // If the table has holes, we need a constant result for the default case
4040 // or a bitmask that fits in a register.
4041 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4042 bool HasDefaultResults = false;
4043 if (TableHasHoles) {
4044 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4045 &CommonDest, DefaultResultsList, DL);
4048 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4050 // As an extra penalty for the validity test we require more cases.
4051 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4053 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4057 for (const auto &I : DefaultResultsList) {
4058 PHINode *PHI = I.first;
4059 Constant *Result = I.second;
4060 DefaultResults[PHI] = Result;
4063 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4066 // Create the BB that does the lookups.
4067 Module &Mod = *CommonDest->getParent()->getParent();
4068 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4070 CommonDest->getParent(),
4073 // Compute the table index value.
4074 Builder.SetInsertPoint(SI);
4075 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4078 // Compute the maximum table size representable by the integer type we are
4080 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4081 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4082 assert(MaxTableSize >= TableSize &&
4083 "It is impossible for a switch to have more entries than the max "
4084 "representable value of its input integer type's size.");
4086 // If we have a fully covered lookup table, unconditionally branch to the
4087 // lookup table BB. Otherwise, check if the condition value is within the case
4088 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4090 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4091 if (GeneratingCoveredLookupTable) {
4092 Builder.CreateBr(LookupBB);
4093 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4094 // do not delete PHINodes here.
4095 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4096 true/*DontDeleteUselessPHIs*/);
4098 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4099 MinCaseVal->getType(), TableSize));
4100 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4103 // Populate the BB that does the lookups.
4104 Builder.SetInsertPoint(LookupBB);
4107 // Before doing the lookup we do the hole check.
4108 // The LookupBB is therefore re-purposed to do the hole check
4109 // and we create a new LookupBB.
4110 BasicBlock *MaskBB = LookupBB;
4111 MaskBB->setName("switch.hole_check");
4112 LookupBB = BasicBlock::Create(Mod.getContext(),
4114 CommonDest->getParent(),
4117 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4118 // unnecessary illegal types.
4119 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4120 APInt MaskInt(TableSizePowOf2, 0);
4121 APInt One(TableSizePowOf2, 1);
4122 // Build bitmask; fill in a 1 bit for every case.
4123 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4124 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4125 uint64_t Idx = (ResultList[I].first->getValue() -
4126 MinCaseVal->getValue()).getLimitedValue();
4127 MaskInt |= One << Idx;
4129 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4131 // Get the TableIndex'th bit of the bitmask.
4132 // If this bit is 0 (meaning hole) jump to the default destination,
4133 // else continue with table lookup.
4134 IntegerType *MapTy = TableMask->getType();
4135 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4136 "switch.maskindex");
4137 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4139 Value *LoBit = Builder.CreateTrunc(Shifted,
4140 Type::getInt1Ty(Mod.getContext()),
4142 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4144 Builder.SetInsertPoint(LookupBB);
4145 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4148 bool ReturnedEarly = false;
4149 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4150 PHINode *PHI = PHIs[I];
4152 // If using a bitmask, use any value to fill the lookup table holes.
4153 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4154 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
4157 Value *Result = Table.BuildLookup(TableIndex, Builder);
4159 // If the result is used to return immediately from the function, we want to
4160 // do that right here.
4161 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4162 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4163 Builder.CreateRet(Result);
4164 ReturnedEarly = true;
4168 PHI->addIncoming(Result, LookupBB);
4172 Builder.CreateBr(CommonDest);
4174 // Remove the switch.
4175 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4176 BasicBlock *Succ = SI->getSuccessor(i);
4178 if (Succ == SI->getDefaultDest())
4180 Succ->removePredecessor(SI->getParent());
4182 SI->eraseFromParent();
4186 ++NumLookupTablesHoles;
4190 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4191 BasicBlock *BB = SI->getParent();
4193 if (isValueEqualityComparison(SI)) {
4194 // If we only have one predecessor, and if it is a branch on this value,
4195 // see if that predecessor totally determines the outcome of this switch.
4196 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4197 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4198 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4200 Value *Cond = SI->getCondition();
4201 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4202 if (SimplifySwitchOnSelect(SI, Select))
4203 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4205 // If the block only contains the switch, see if we can fold the block
4206 // away into any preds.
4207 BasicBlock::iterator BBI = BB->begin();
4208 // Ignore dbg intrinsics.
4209 while (isa<DbgInfoIntrinsic>(BBI))
4212 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4213 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4216 // Try to transform the switch into an icmp and a branch.
4217 if (TurnSwitchRangeIntoICmp(SI, Builder))
4218 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4220 // Remove unreachable cases.
4221 if (EliminateDeadSwitchCases(SI, DL, AT))
4222 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4224 if (SwitchToSelect(SI, Builder, DL, AT))
4225 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4227 if (ForwardSwitchConditionToPHI(SI))
4228 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4230 if (SwitchToLookupTable(SI, Builder, TTI, DL))
4231 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4236 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4237 BasicBlock *BB = IBI->getParent();
4238 bool Changed = false;
4240 // Eliminate redundant destinations.
4241 SmallPtrSet<Value *, 8> Succs;
4242 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4243 BasicBlock *Dest = IBI->getDestination(i);
4244 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4245 Dest->removePredecessor(BB);
4246 IBI->removeDestination(i);
4252 if (IBI->getNumDestinations() == 0) {
4253 // If the indirectbr has no successors, change it to unreachable.
4254 new UnreachableInst(IBI->getContext(), IBI);
4255 EraseTerminatorInstAndDCECond(IBI);
4259 if (IBI->getNumDestinations() == 1) {
4260 // If the indirectbr has one successor, change it to a direct branch.
4261 BranchInst::Create(IBI->getDestination(0), IBI);
4262 EraseTerminatorInstAndDCECond(IBI);
4266 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4267 if (SimplifyIndirectBrOnSelect(IBI, SI))
4268 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4273 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4274 BasicBlock *BB = BI->getParent();
4276 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4279 // If the Terminator is the only non-phi instruction, simplify the block.
4280 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4281 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4282 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4285 // If the only instruction in the block is a seteq/setne comparison
4286 // against a constant, try to simplify the block.
4287 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4288 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4289 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4291 if (I->isTerminator() &&
4292 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4293 BonusInstThreshold, DL, AT))
4297 // If this basic block is ONLY a compare and a branch, and if a predecessor
4298 // branches to us and our successor, fold the comparison into the
4299 // predecessor and use logical operations to update the incoming value
4300 // for PHI nodes in common successor.
4301 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4302 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4307 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4308 BasicBlock *BB = BI->getParent();
4310 // Conditional branch
4311 if (isValueEqualityComparison(BI)) {
4312 // If we only have one predecessor, and if it is a branch on this value,
4313 // see if that predecessor totally determines the outcome of this
4315 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4316 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4317 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4319 // This block must be empty, except for the setcond inst, if it exists.
4320 // Ignore dbg intrinsics.
4321 BasicBlock::iterator I = BB->begin();
4322 // Ignore dbg intrinsics.
4323 while (isa<DbgInfoIntrinsic>(I))
4326 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4327 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4328 } else if (&*I == cast<Instruction>(BI->getCondition())){
4330 // Ignore dbg intrinsics.
4331 while (isa<DbgInfoIntrinsic>(I))
4333 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4334 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4338 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4339 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4342 // If this basic block is ONLY a compare and a branch, and if a predecessor
4343 // branches to us and one of our successors, fold the comparison into the
4344 // predecessor and use logical operations to pick the right destination.
4345 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4346 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4348 // We have a conditional branch to two blocks that are only reachable
4349 // from BI. We know that the condbr dominates the two blocks, so see if
4350 // there is any identical code in the "then" and "else" blocks. If so, we
4351 // can hoist it up to the branching block.
4352 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4353 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4354 if (HoistThenElseCodeToIf(BI, DL))
4355 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4357 // If Successor #1 has multiple preds, we may be able to conditionally
4358 // execute Successor #0 if it branches to Successor #1.
4359 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4360 if (Succ0TI->getNumSuccessors() == 1 &&
4361 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4362 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4363 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4365 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4366 // If Successor #0 has multiple preds, we may be able to conditionally
4367 // execute Successor #1 if it branches to Successor #0.
4368 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4369 if (Succ1TI->getNumSuccessors() == 1 &&
4370 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4371 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4372 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4375 // If this is a branch on a phi node in the current block, thread control
4376 // through this block if any PHI node entries are constants.
4377 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4378 if (PN->getParent() == BI->getParent())
4379 if (FoldCondBranchOnPHI(BI, DL))
4380 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4382 // Scan predecessor blocks for conditional branches.
4383 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4384 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4385 if (PBI != BI && PBI->isConditional())
4386 if (SimplifyCondBranchToCondBranch(PBI, BI))
4387 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4392 /// Check if passing a value to an instruction will cause undefined behavior.
4393 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4394 Constant *C = dyn_cast<Constant>(V);
4401 if (C->isNullValue()) {
4402 // Only look at the first use, avoid hurting compile time with long uselists
4403 User *Use = *I->user_begin();
4405 // Now make sure that there are no instructions in between that can alter
4406 // control flow (eg. calls)
4407 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4408 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4411 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4412 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4413 if (GEP->getPointerOperand() == I)
4414 return passingValueIsAlwaysUndefined(V, GEP);
4416 // Look through bitcasts.
4417 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4418 return passingValueIsAlwaysUndefined(V, BC);
4420 // Load from null is undefined.
4421 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4422 if (!LI->isVolatile())
4423 return LI->getPointerAddressSpace() == 0;
4425 // Store to null is undefined.
4426 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4427 if (!SI->isVolatile())
4428 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4433 /// If BB has an incoming value that will always trigger undefined behavior
4434 /// (eg. null pointer dereference), remove the branch leading here.
4435 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4436 for (BasicBlock::iterator i = BB->begin();
4437 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4438 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4439 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4440 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4441 IRBuilder<> Builder(T);
4442 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4443 BB->removePredecessor(PHI->getIncomingBlock(i));
4444 // Turn uncoditional branches into unreachables and remove the dead
4445 // destination from conditional branches.
4446 if (BI->isUnconditional())
4447 Builder.CreateUnreachable();
4449 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4450 BI->getSuccessor(0));
4451 BI->eraseFromParent();
4454 // TODO: SwitchInst.
4460 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4461 bool Changed = false;
4463 assert(BB && BB->getParent() && "Block not embedded in function!");
4464 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4466 // Remove basic blocks that have no predecessors (except the entry block)...
4467 // or that just have themself as a predecessor. These are unreachable.
4468 if ((pred_begin(BB) == pred_end(BB) &&
4469 BB != &BB->getParent()->getEntryBlock()) ||
4470 BB->getSinglePredecessor() == BB) {
4471 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4472 DeleteDeadBlock(BB);
4476 // Check to see if we can constant propagate this terminator instruction
4478 Changed |= ConstantFoldTerminator(BB, true);
4480 // Check for and eliminate duplicate PHI nodes in this block.
4481 Changed |= EliminateDuplicatePHINodes(BB);
4483 // Check for and remove branches that will always cause undefined behavior.
4484 Changed |= removeUndefIntroducingPredecessor(BB);
4486 // Merge basic blocks into their predecessor if there is only one distinct
4487 // pred, and if there is only one distinct successor of the predecessor, and
4488 // if there are no PHI nodes.
4490 if (MergeBlockIntoPredecessor(BB))
4493 IRBuilder<> Builder(BB);
4495 // If there is a trivial two-entry PHI node in this basic block, and we can
4496 // eliminate it, do so now.
4497 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4498 if (PN->getNumIncomingValues() == 2)
4499 Changed |= FoldTwoEntryPHINode(PN, DL);
4501 Builder.SetInsertPoint(BB->getTerminator());
4502 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4503 if (BI->isUnconditional()) {
4504 if (SimplifyUncondBranch(BI, Builder)) return true;
4506 if (SimplifyCondBranch(BI, Builder)) return true;
4508 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4509 if (SimplifyReturn(RI, Builder)) return true;
4510 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4511 if (SimplifyResume(RI, Builder)) return true;
4512 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4513 if (SimplifySwitch(SI, Builder)) return true;
4514 } else if (UnreachableInst *UI =
4515 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4516 if (SimplifyUnreachable(UI)) return true;
4517 } else if (IndirectBrInst *IBI =
4518 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4519 if (SimplifyIndirectBr(IBI)) return true;
4525 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4526 /// example, it adjusts branches to branches to eliminate the extra hop, it
4527 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4528 /// of the CFG. It returns true if a modification was made.
4530 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4531 unsigned BonusInstThreshold,
4532 const DataLayout *DL, AssumptionTracker *AT) {
4533 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);