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"
51 using namespace PatternMatch;
53 #define DEBUG_TYPE "simplifycfg"
55 static cl::opt<unsigned>
56 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
57 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
60 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
61 cl::desc("Duplicate return instructions into unconditional branches"));
64 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
65 cl::desc("Sink common instructions down to the end block"));
67 static cl::opt<bool> HoistCondStores(
68 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
69 cl::desc("Hoist conditional stores if an unconditional store precedes"));
71 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
72 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
73 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
74 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
75 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
78 /// ValueEqualityComparisonCase - Represents a case of a switch.
79 struct ValueEqualityComparisonCase {
83 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
84 : Value(Value), Dest(Dest) {}
86 bool operator<(ValueEqualityComparisonCase RHS) const {
87 // Comparing pointers is ok as we only rely on the order for uniquing.
88 return Value < RHS.Value;
91 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
94 class SimplifyCFGOpt {
95 const TargetTransformInfo &TTI;
96 const DataLayout *const DL;
97 AssumptionTracker *AT;
98 Value *isValueEqualityComparison(TerminatorInst *TI);
99 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
100 std::vector<ValueEqualityComparisonCase> &Cases);
101 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
103 IRBuilder<> &Builder);
104 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
105 IRBuilder<> &Builder);
107 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
108 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
109 bool SimplifyUnreachable(UnreachableInst *UI);
110 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
111 bool SimplifyIndirectBr(IndirectBrInst *IBI);
112 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
113 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
116 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL,
117 AssumptionTracker *AT)
118 : TTI(TTI), DL(DL), AT(AT) {}
119 bool run(BasicBlock *BB);
123 /// SafeToMergeTerminators - Return true if it is safe to merge these two
124 /// terminator instructions together.
126 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
127 if (SI1 == SI2) return false; // Can't merge with self!
129 // It is not safe to merge these two switch instructions if they have a common
130 // successor, and if that successor has a PHI node, and if *that* PHI node has
131 // conflicting incoming values from the two switch blocks.
132 BasicBlock *SI1BB = SI1->getParent();
133 BasicBlock *SI2BB = SI2->getParent();
134 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
136 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
137 if (SI1Succs.count(*I))
138 for (BasicBlock::iterator BBI = (*I)->begin();
139 isa<PHINode>(BBI); ++BBI) {
140 PHINode *PN = cast<PHINode>(BBI);
141 if (PN->getIncomingValueForBlock(SI1BB) !=
142 PN->getIncomingValueForBlock(SI2BB))
149 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
150 /// to merge these two terminator instructions together, where SI1 is an
151 /// unconditional branch. PhiNodes will store all PHI nodes in common
154 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
157 SmallVectorImpl<PHINode*> &PhiNodes) {
158 if (SI1 == SI2) return false; // Can't merge with self!
159 assert(SI1->isUnconditional() && SI2->isConditional());
161 // We fold the unconditional branch if we can easily update all PHI nodes in
162 // common successors:
163 // 1> We have a constant incoming value for the conditional branch;
164 // 2> We have "Cond" as the incoming value for the unconditional branch;
165 // 3> SI2->getCondition() and Cond have same operands.
166 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
167 if (!Ci2) return false;
168 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
169 Cond->getOperand(1) == Ci2->getOperand(1)) &&
170 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
171 Cond->getOperand(1) == Ci2->getOperand(0)))
174 BasicBlock *SI1BB = SI1->getParent();
175 BasicBlock *SI2BB = SI2->getParent();
176 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
177 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
178 if (SI1Succs.count(*I))
179 for (BasicBlock::iterator BBI = (*I)->begin();
180 isa<PHINode>(BBI); ++BBI) {
181 PHINode *PN = cast<PHINode>(BBI);
182 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
183 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
185 PhiNodes.push_back(PN);
190 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
191 /// now be entries in it from the 'NewPred' block. The values that will be
192 /// flowing into the PHI nodes will be the same as those coming in from
193 /// ExistPred, an existing predecessor of Succ.
194 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
195 BasicBlock *ExistPred) {
196 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
199 for (BasicBlock::iterator I = Succ->begin();
200 (PN = dyn_cast<PHINode>(I)); ++I)
201 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
204 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
205 /// given instruction, which is assumed to be safe to speculate. 1 means
206 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
207 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
208 assert(isSafeToSpeculativelyExecute(I, DL) &&
209 "Instruction is not safe to speculatively execute!");
210 switch (Operator::getOpcode(I)) {
212 // In doubt, be conservative.
214 case Instruction::GetElementPtr:
215 // GEPs are cheap if all indices are constant.
216 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
219 case Instruction::ExtractValue:
220 case Instruction::Load:
221 case Instruction::Add:
222 case Instruction::Sub:
223 case Instruction::And:
224 case Instruction::Or:
225 case Instruction::Xor:
226 case Instruction::Shl:
227 case Instruction::LShr:
228 case Instruction::AShr:
229 case Instruction::ICmp:
230 case Instruction::Trunc:
231 case Instruction::ZExt:
232 case Instruction::SExt:
233 case Instruction::BitCast:
234 case Instruction::ExtractElement:
235 case Instruction::InsertElement:
236 return 1; // These are all cheap.
238 case Instruction::Call:
239 case Instruction::Select:
244 /// DominatesMergePoint - If we have a merge point of an "if condition" as
245 /// accepted above, return true if the specified value dominates the block. We
246 /// don't handle the true generality of domination here, just a special case
247 /// which works well enough for us.
249 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
250 /// see if V (which must be an instruction) and its recursive operands
251 /// that do not dominate BB have a combined cost lower than CostRemaining and
252 /// are non-trapping. If both are true, the instruction is inserted into the
253 /// set and true is returned.
255 /// The cost for most non-trapping instructions is defined as 1 except for
256 /// Select whose cost is 2.
258 /// After this function returns, CostRemaining is decreased by the cost of
259 /// V plus its non-dominating operands. If that cost is greater than
260 /// CostRemaining, false is returned and CostRemaining is undefined.
261 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
262 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
263 unsigned &CostRemaining,
264 const DataLayout *DL) {
265 Instruction *I = dyn_cast<Instruction>(V);
267 // Non-instructions all dominate instructions, but not all constantexprs
268 // can be executed unconditionally.
269 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
274 BasicBlock *PBB = I->getParent();
276 // We don't want to allow weird loops that might have the "if condition" in
277 // the bottom of this block.
278 if (PBB == BB) return false;
280 // If this instruction is defined in a block that contains an unconditional
281 // branch to BB, then it must be in the 'conditional' part of the "if
282 // statement". If not, it definitely dominates the region.
283 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
284 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
287 // If we aren't allowing aggressive promotion anymore, then don't consider
288 // instructions in the 'if region'.
289 if (!AggressiveInsts) return false;
291 // If we have seen this instruction before, don't count it again.
292 if (AggressiveInsts->count(I)) return true;
294 // Okay, it looks like the instruction IS in the "condition". Check to
295 // see if it's a cheap instruction to unconditionally compute, and if it
296 // only uses stuff defined outside of the condition. If so, hoist it out.
297 if (!isSafeToSpeculativelyExecute(I, DL))
300 unsigned Cost = ComputeSpeculationCost(I, DL);
302 if (Cost > CostRemaining)
305 CostRemaining -= Cost;
307 // Okay, we can only really hoist these out if their operands do
308 // not take us over the cost threshold.
309 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
310 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
312 // Okay, it's safe to do this! Remember this instruction.
313 AggressiveInsts->insert(I);
317 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
318 /// and PointerNullValue. Return NULL if value is not a constant int.
319 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
320 // Normal constant int.
321 ConstantInt *CI = dyn_cast<ConstantInt>(V);
322 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
325 // This is some kind of pointer constant. Turn it into a pointer-sized
326 // ConstantInt if possible.
327 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
329 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
330 if (isa<ConstantPointerNull>(V))
331 return ConstantInt::get(PtrTy, 0);
333 // IntToPtr const int.
334 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
335 if (CE->getOpcode() == Instruction::IntToPtr)
336 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
337 // The constant is very likely to have the right type already.
338 if (CI->getType() == PtrTy)
341 return cast<ConstantInt>
342 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
347 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
348 /// collection of icmp eq/ne instructions that compare a value against a
349 /// constant, return the value being compared, and stick the constant into the
352 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
353 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
354 Instruction *I = dyn_cast<Instruction>(V);
355 if (!I) return nullptr;
357 // If this is an icmp against a constant, handle this as one of the cases.
358 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
359 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
363 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
364 // (x & ~2^x) == y --> x == y || x == y|2^x
365 // This undoes a transformation done by instcombine to fuse 2 compares.
366 if (match(ICI->getOperand(0),
367 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
368 APInt Not = ~RHSC->getValue();
369 if (Not.isPowerOf2()) {
372 ConstantInt::get(C->getContext(), C->getValue() | Not));
380 return I->getOperand(0);
383 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
386 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
388 // Shift the range if the compare is fed by an add. This is the range
389 // compare idiom as emitted by instcombine.
391 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
393 Span = Span.subtract(RHSC->getValue());
395 // If this is an and/!= check then we want to optimize "x ugt 2" into
398 Span = Span.inverse();
400 // If there are a ton of values, we don't want to make a ginormous switch.
401 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
404 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
405 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
407 return hasAdd ? RHSVal : I->getOperand(0);
412 // Otherwise, we can only handle an | or &, depending on isEQ.
413 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
416 unsigned NumValsBeforeLHS = Vals.size();
417 unsigned UsedICmpsBeforeLHS = UsedICmps;
418 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
420 unsigned NumVals = Vals.size();
421 unsigned UsedICmpsBeforeRHS = UsedICmps;
422 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
426 Vals.resize(NumVals);
427 UsedICmps = UsedICmpsBeforeRHS;
430 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
431 // set it and return success.
432 if (Extra == nullptr || Extra == I->getOperand(1)) {
433 Extra = I->getOperand(1);
437 Vals.resize(NumValsBeforeLHS);
438 UsedICmps = UsedICmpsBeforeLHS;
442 // If the LHS can't be folded in, but Extra is available and RHS can, try to
444 if (Extra == nullptr || Extra == I->getOperand(0)) {
445 Value *OldExtra = Extra;
446 Extra = I->getOperand(0);
447 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
450 assert(Vals.size() == NumValsBeforeLHS);
457 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
458 Instruction *Cond = nullptr;
459 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
460 Cond = dyn_cast<Instruction>(SI->getCondition());
461 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
462 if (BI->isConditional())
463 Cond = dyn_cast<Instruction>(BI->getCondition());
464 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
465 Cond = dyn_cast<Instruction>(IBI->getAddress());
468 TI->eraseFromParent();
469 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
472 /// isValueEqualityComparison - Return true if the specified terminator checks
473 /// to see if a value is equal to constant integer value.
474 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
476 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
477 // Do not permit merging of large switch instructions into their
478 // predecessors unless there is only one predecessor.
479 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
480 pred_end(SI->getParent())) <= 128)
481 CV = SI->getCondition();
482 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
483 if (BI->isConditional() && BI->getCondition()->hasOneUse())
484 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
485 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
486 CV = ICI->getOperand(0);
488 // Unwrap any lossless ptrtoint cast.
490 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
491 Value *Ptr = PTII->getPointerOperand();
492 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
499 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
500 /// decode all of the 'cases' that it represents and return the 'default' block.
501 BasicBlock *SimplifyCFGOpt::
502 GetValueEqualityComparisonCases(TerminatorInst *TI,
503 std::vector<ValueEqualityComparisonCase>
505 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
506 Cases.reserve(SI->getNumCases());
507 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
508 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
509 i.getCaseSuccessor()));
510 return SI->getDefaultDest();
513 BranchInst *BI = cast<BranchInst>(TI);
514 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
515 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
516 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
519 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
523 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
524 /// in the list that match the specified block.
525 static void EliminateBlockCases(BasicBlock *BB,
526 std::vector<ValueEqualityComparisonCase> &Cases) {
527 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
530 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
533 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
534 std::vector<ValueEqualityComparisonCase > &C2) {
535 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
537 // Make V1 be smaller than V2.
538 if (V1->size() > V2->size())
541 if (V1->size() == 0) return false;
542 if (V1->size() == 1) {
544 ConstantInt *TheVal = (*V1)[0].Value;
545 for (unsigned i = 0, e = V2->size(); i != e; ++i)
546 if (TheVal == (*V2)[i].Value)
550 // Otherwise, just sort both lists and compare element by element.
551 array_pod_sort(V1->begin(), V1->end());
552 array_pod_sort(V2->begin(), V2->end());
553 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
554 while (i1 != e1 && i2 != e2) {
555 if ((*V1)[i1].Value == (*V2)[i2].Value)
557 if ((*V1)[i1].Value < (*V2)[i2].Value)
565 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
566 /// terminator instruction and its block is known to only have a single
567 /// predecessor block, check to see if that predecessor is also a value
568 /// comparison with the same value, and if that comparison determines the
569 /// outcome of this comparison. If so, simplify TI. This does a very limited
570 /// form of jump threading.
571 bool SimplifyCFGOpt::
572 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
574 IRBuilder<> &Builder) {
575 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
576 if (!PredVal) return false; // Not a value comparison in predecessor.
578 Value *ThisVal = isValueEqualityComparison(TI);
579 assert(ThisVal && "This isn't a value comparison!!");
580 if (ThisVal != PredVal) return false; // Different predicates.
582 // TODO: Preserve branch weight metadata, similarly to how
583 // FoldValueComparisonIntoPredecessors preserves it.
585 // Find out information about when control will move from Pred to TI's block.
586 std::vector<ValueEqualityComparisonCase> PredCases;
587 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
589 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
591 // Find information about how control leaves this block.
592 std::vector<ValueEqualityComparisonCase> ThisCases;
593 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
594 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
596 // If TI's block is the default block from Pred's comparison, potentially
597 // simplify TI based on this knowledge.
598 if (PredDef == TI->getParent()) {
599 // If we are here, we know that the value is none of those cases listed in
600 // PredCases. If there are any cases in ThisCases that are in PredCases, we
602 if (!ValuesOverlap(PredCases, ThisCases))
605 if (isa<BranchInst>(TI)) {
606 // Okay, one of the successors of this condbr is dead. Convert it to a
608 assert(ThisCases.size() == 1 && "Branch can only have one case!");
609 // Insert the new branch.
610 Instruction *NI = Builder.CreateBr(ThisDef);
613 // Remove PHI node entries for the dead edge.
614 ThisCases[0].Dest->removePredecessor(TI->getParent());
616 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
617 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
619 EraseTerminatorInstAndDCECond(TI);
623 SwitchInst *SI = cast<SwitchInst>(TI);
624 // Okay, TI has cases that are statically dead, prune them away.
625 SmallPtrSet<Constant*, 16> DeadCases;
626 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
627 DeadCases.insert(PredCases[i].Value);
629 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
630 << "Through successor TI: " << *TI);
632 // Collect branch weights into a vector.
633 SmallVector<uint32_t, 8> Weights;
634 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
635 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
637 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
639 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
641 Weights.push_back(CI->getValue().getZExtValue());
643 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
645 if (DeadCases.count(i.getCaseValue())) {
647 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
650 i.getCaseSuccessor()->removePredecessor(TI->getParent());
654 if (HasWeight && Weights.size() >= 2)
655 SI->setMetadata(LLVMContext::MD_prof,
656 MDBuilder(SI->getParent()->getContext()).
657 createBranchWeights(Weights));
659 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
663 // Otherwise, TI's block must correspond to some matched value. Find out
664 // which value (or set of values) this is.
665 ConstantInt *TIV = nullptr;
666 BasicBlock *TIBB = TI->getParent();
667 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
668 if (PredCases[i].Dest == TIBB) {
670 return false; // Cannot handle multiple values coming to this block.
671 TIV = PredCases[i].Value;
673 assert(TIV && "No edge from pred to succ?");
675 // Okay, we found the one constant that our value can be if we get into TI's
676 // BB. Find out which successor will unconditionally be branched to.
677 BasicBlock *TheRealDest = nullptr;
678 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
679 if (ThisCases[i].Value == TIV) {
680 TheRealDest = ThisCases[i].Dest;
684 // If not handled by any explicit cases, it is handled by the default case.
685 if (!TheRealDest) TheRealDest = ThisDef;
687 // Remove PHI node entries for dead edges.
688 BasicBlock *CheckEdge = TheRealDest;
689 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
690 if (*SI != CheckEdge)
691 (*SI)->removePredecessor(TIBB);
695 // Insert the new branch.
696 Instruction *NI = Builder.CreateBr(TheRealDest);
699 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
700 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
702 EraseTerminatorInstAndDCECond(TI);
707 /// ConstantIntOrdering - This class implements a stable ordering of constant
708 /// integers that does not depend on their address. This is important for
709 /// applications that sort ConstantInt's to ensure uniqueness.
710 struct ConstantIntOrdering {
711 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
712 return LHS->getValue().ult(RHS->getValue());
717 static int ConstantIntSortPredicate(ConstantInt *const *P1,
718 ConstantInt *const *P2) {
719 const ConstantInt *LHS = *P1;
720 const ConstantInt *RHS = *P2;
721 if (LHS->getValue().ult(RHS->getValue()))
723 if (LHS->getValue() == RHS->getValue())
728 static inline bool HasBranchWeights(const Instruction* I) {
729 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
730 if (ProfMD && ProfMD->getOperand(0))
731 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
732 return MDS->getString().equals("branch_weights");
737 /// Get Weights of a given TerminatorInst, the default weight is at the front
738 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
740 static void GetBranchWeights(TerminatorInst *TI,
741 SmallVectorImpl<uint64_t> &Weights) {
742 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
744 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
745 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
746 Weights.push_back(CI->getValue().getZExtValue());
749 // If TI is a conditional eq, the default case is the false case,
750 // and the corresponding branch-weight data is at index 2. We swap the
751 // default weight to be the first entry.
752 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
753 assert(Weights.size() == 2);
754 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
755 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
756 std::swap(Weights.front(), Weights.back());
760 /// Keep halving the weights until all can fit in uint32_t.
761 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
762 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
763 if (Max > UINT_MAX) {
764 unsigned Offset = 32 - countLeadingZeros(Max);
765 for (uint64_t &I : Weights)
770 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
771 /// equality comparison instruction (either a switch or a branch on "X == c").
772 /// See if any of the predecessors of the terminator block are value comparisons
773 /// on the same value. If so, and if safe to do so, fold them together.
774 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
775 IRBuilder<> &Builder) {
776 BasicBlock *BB = TI->getParent();
777 Value *CV = isValueEqualityComparison(TI); // CondVal
778 assert(CV && "Not a comparison?");
779 bool Changed = false;
781 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
782 while (!Preds.empty()) {
783 BasicBlock *Pred = Preds.pop_back_val();
785 // See if the predecessor is a comparison with the same value.
786 TerminatorInst *PTI = Pred->getTerminator();
787 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
789 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
790 // Figure out which 'cases' to copy from SI to PSI.
791 std::vector<ValueEqualityComparisonCase> BBCases;
792 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
794 std::vector<ValueEqualityComparisonCase> PredCases;
795 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
797 // Based on whether the default edge from PTI goes to BB or not, fill in
798 // PredCases and PredDefault with the new switch cases we would like to
800 SmallVector<BasicBlock*, 8> NewSuccessors;
802 // Update the branch weight metadata along the way
803 SmallVector<uint64_t, 8> Weights;
804 bool PredHasWeights = HasBranchWeights(PTI);
805 bool SuccHasWeights = HasBranchWeights(TI);
807 if (PredHasWeights) {
808 GetBranchWeights(PTI, Weights);
809 // branch-weight metadata is inconsistent here.
810 if (Weights.size() != 1 + PredCases.size())
811 PredHasWeights = SuccHasWeights = false;
812 } else if (SuccHasWeights)
813 // If there are no predecessor weights but there are successor weights,
814 // populate Weights with 1, which will later be scaled to the sum of
815 // successor's weights
816 Weights.assign(1 + PredCases.size(), 1);
818 SmallVector<uint64_t, 8> SuccWeights;
819 if (SuccHasWeights) {
820 GetBranchWeights(TI, SuccWeights);
821 // branch-weight metadata is inconsistent here.
822 if (SuccWeights.size() != 1 + BBCases.size())
823 PredHasWeights = SuccHasWeights = false;
824 } else if (PredHasWeights)
825 SuccWeights.assign(1 + BBCases.size(), 1);
827 if (PredDefault == BB) {
828 // If this is the default destination from PTI, only the edges in TI
829 // that don't occur in PTI, or that branch to BB will be activated.
830 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
831 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
832 if (PredCases[i].Dest != BB)
833 PTIHandled.insert(PredCases[i].Value);
835 // The default destination is BB, we don't need explicit targets.
836 std::swap(PredCases[i], PredCases.back());
838 if (PredHasWeights || SuccHasWeights) {
839 // Increase weight for the default case.
840 Weights[0] += Weights[i+1];
841 std::swap(Weights[i+1], Weights.back());
845 PredCases.pop_back();
849 // Reconstruct the new switch statement we will be building.
850 if (PredDefault != BBDefault) {
851 PredDefault->removePredecessor(Pred);
852 PredDefault = BBDefault;
853 NewSuccessors.push_back(BBDefault);
856 unsigned CasesFromPred = Weights.size();
857 uint64_t ValidTotalSuccWeight = 0;
858 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
859 if (!PTIHandled.count(BBCases[i].Value) &&
860 BBCases[i].Dest != BBDefault) {
861 PredCases.push_back(BBCases[i]);
862 NewSuccessors.push_back(BBCases[i].Dest);
863 if (SuccHasWeights || PredHasWeights) {
864 // The default weight is at index 0, so weight for the ith case
865 // should be at index i+1. Scale the cases from successor by
866 // PredDefaultWeight (Weights[0]).
867 Weights.push_back(Weights[0] * SuccWeights[i+1]);
868 ValidTotalSuccWeight += SuccWeights[i+1];
872 if (SuccHasWeights || PredHasWeights) {
873 ValidTotalSuccWeight += SuccWeights[0];
874 // Scale the cases from predecessor by ValidTotalSuccWeight.
875 for (unsigned i = 1; i < CasesFromPred; ++i)
876 Weights[i] *= ValidTotalSuccWeight;
877 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
878 Weights[0] *= SuccWeights[0];
881 // If this is not the default destination from PSI, only the edges
882 // in SI that occur in PSI with a destination of BB will be
884 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
885 std::map<ConstantInt*, uint64_t> WeightsForHandled;
886 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
887 if (PredCases[i].Dest == BB) {
888 PTIHandled.insert(PredCases[i].Value);
890 if (PredHasWeights || SuccHasWeights) {
891 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
892 std::swap(Weights[i+1], Weights.back());
896 std::swap(PredCases[i], PredCases.back());
897 PredCases.pop_back();
901 // Okay, now we know which constants were sent to BB from the
902 // predecessor. Figure out where they will all go now.
903 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
904 if (PTIHandled.count(BBCases[i].Value)) {
905 // If this is one we are capable of getting...
906 if (PredHasWeights || SuccHasWeights)
907 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
908 PredCases.push_back(BBCases[i]);
909 NewSuccessors.push_back(BBCases[i].Dest);
910 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
913 // If there are any constants vectored to BB that TI doesn't handle,
914 // they must go to the default destination of TI.
915 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
917 E = PTIHandled.end(); I != E; ++I) {
918 if (PredHasWeights || SuccHasWeights)
919 Weights.push_back(WeightsForHandled[*I]);
920 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
921 NewSuccessors.push_back(BBDefault);
925 // Okay, at this point, we know which new successor Pred will get. Make
926 // sure we update the number of entries in the PHI nodes for these
928 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
929 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
931 Builder.SetInsertPoint(PTI);
932 // Convert pointer to int before we switch.
933 if (CV->getType()->isPointerTy()) {
934 assert(DL && "Cannot switch on pointer without DataLayout");
935 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
939 // Now that the successors are updated, create the new Switch instruction.
940 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
942 NewSI->setDebugLoc(PTI->getDebugLoc());
943 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
944 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
946 if (PredHasWeights || SuccHasWeights) {
947 // Halve the weights if any of them cannot fit in an uint32_t
950 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
952 NewSI->setMetadata(LLVMContext::MD_prof,
953 MDBuilder(BB->getContext()).
954 createBranchWeights(MDWeights));
957 EraseTerminatorInstAndDCECond(PTI);
959 // Okay, last check. If BB is still a successor of PSI, then we must
960 // have an infinite loop case. If so, add an infinitely looping block
961 // to handle the case to preserve the behavior of the code.
962 BasicBlock *InfLoopBlock = nullptr;
963 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
964 if (NewSI->getSuccessor(i) == BB) {
966 // Insert it at the end of the function, because it's either code,
967 // or it won't matter if it's hot. :)
968 InfLoopBlock = BasicBlock::Create(BB->getContext(),
969 "infloop", BB->getParent());
970 BranchInst::Create(InfLoopBlock, InfLoopBlock);
972 NewSI->setSuccessor(i, InfLoopBlock);
981 // isSafeToHoistInvoke - If we would need to insert a select that uses the
982 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
983 // would need to do this), we can't hoist the invoke, as there is nowhere
984 // to put the select in this case.
985 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
986 Instruction *I1, Instruction *I2) {
987 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
989 for (BasicBlock::iterator BBI = SI->begin();
990 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
991 Value *BB1V = PN->getIncomingValueForBlock(BB1);
992 Value *BB2V = PN->getIncomingValueForBlock(BB2);
993 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1001 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1002 /// BB2, hoist any common code in the two blocks up into the branch block. The
1003 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1004 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1005 // This does very trivial matching, with limited scanning, to find identical
1006 // instructions in the two blocks. In particular, we don't want to get into
1007 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1008 // such, we currently just scan for obviously identical instructions in an
1010 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1011 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1013 BasicBlock::iterator BB1_Itr = BB1->begin();
1014 BasicBlock::iterator BB2_Itr = BB2->begin();
1016 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1017 // Skip debug info if it is not identical.
1018 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1019 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1020 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1021 while (isa<DbgInfoIntrinsic>(I1))
1023 while (isa<DbgInfoIntrinsic>(I2))
1026 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1027 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1030 BasicBlock *BIParent = BI->getParent();
1032 bool Changed = false;
1034 // If we are hoisting the terminator instruction, don't move one (making a
1035 // broken BB), instead clone it, and remove BI.
1036 if (isa<TerminatorInst>(I1))
1037 goto HoistTerminator;
1039 // For a normal instruction, we just move one to right before the branch,
1040 // then replace all uses of the other with the first. Finally, we remove
1041 // the now redundant second instruction.
1042 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1043 if (!I2->use_empty())
1044 I2->replaceAllUsesWith(I1);
1045 I1->intersectOptionalDataWith(I2);
1046 unsigned KnownIDs[] = {
1047 LLVMContext::MD_tbaa,
1048 LLVMContext::MD_range,
1049 LLVMContext::MD_fpmath,
1050 LLVMContext::MD_invariant_load
1052 combineMetadata(I1, I2, KnownIDs);
1053 I2->eraseFromParent();
1058 // Skip debug info if it is not identical.
1059 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1060 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1061 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1062 while (isa<DbgInfoIntrinsic>(I1))
1064 while (isa<DbgInfoIntrinsic>(I2))
1067 } while (I1->isIdenticalToWhenDefined(I2));
1072 // It may not be possible to hoist an invoke.
1073 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1076 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1078 for (BasicBlock::iterator BBI = SI->begin();
1079 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1080 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1081 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1085 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1087 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1092 // Okay, it is safe to hoist the terminator.
1093 Instruction *NT = I1->clone();
1094 BIParent->getInstList().insert(BI, NT);
1095 if (!NT->getType()->isVoidTy()) {
1096 I1->replaceAllUsesWith(NT);
1097 I2->replaceAllUsesWith(NT);
1101 IRBuilder<true, NoFolder> Builder(NT);
1102 // Hoisting one of the terminators from our successor is a great thing.
1103 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1104 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1105 // nodes, so we insert select instruction to compute the final result.
1106 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1107 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1109 for (BasicBlock::iterator BBI = SI->begin();
1110 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1111 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1112 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1113 if (BB1V == BB2V) continue;
1115 // These values do not agree. Insert a select instruction before NT
1116 // that determines the right value.
1117 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1119 SI = cast<SelectInst>
1120 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1121 BB1V->getName()+"."+BB2V->getName()));
1123 // Make the PHI node use the select for all incoming values for BB1/BB2
1124 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1125 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1126 PN->setIncomingValue(i, SI);
1130 // Update any PHI nodes in our new successors.
1131 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1132 AddPredecessorToBlock(*SI, BIParent, BB1);
1134 EraseTerminatorInstAndDCECond(BI);
1138 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1139 /// check whether BBEnd has only two predecessors and the other predecessor
1140 /// ends with an unconditional branch. If it is true, sink any common code
1141 /// in the two predecessors to BBEnd.
1142 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1143 assert(BI1->isUnconditional());
1144 BasicBlock *BB1 = BI1->getParent();
1145 BasicBlock *BBEnd = BI1->getSuccessor(0);
1147 // Check that BBEnd has two predecessors and the other predecessor ends with
1148 // an unconditional branch.
1149 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1150 BasicBlock *Pred0 = *PI++;
1151 if (PI == PE) // Only one predecessor.
1153 BasicBlock *Pred1 = *PI++;
1154 if (PI != PE) // More than two predecessors.
1156 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1157 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1158 if (!BI2 || !BI2->isUnconditional())
1161 // Gather the PHI nodes in BBEnd.
1162 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1163 Instruction *FirstNonPhiInBBEnd = nullptr;
1164 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1166 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1167 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1168 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1169 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1171 FirstNonPhiInBBEnd = &*I;
1175 if (!FirstNonPhiInBBEnd)
1179 // This does very trivial matching, with limited scanning, to find identical
1180 // instructions in the two blocks. We scan backward for obviously identical
1181 // instructions in an identical order.
1182 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1183 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1184 RE2 = BB2->getInstList().rend();
1186 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1189 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1192 // Skip the unconditional branches.
1196 bool Changed = false;
1197 while (RI1 != RE1 && RI2 != RE2) {
1199 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1202 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1206 Instruction *I1 = &*RI1, *I2 = &*RI2;
1207 // I1 and I2 should have a single use in the same PHI node, and they
1208 // perform the same operation.
1209 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1210 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1211 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1212 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1213 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1214 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1215 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1216 !I1->hasOneUse() || !I2->hasOneUse() ||
1217 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1218 MapValueFromBB1ToBB2[I1].first != I2)
1221 // Check whether we should swap the operands of ICmpInst.
1222 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1223 bool SwapOpnds = false;
1224 if (ICmp1 && ICmp2 &&
1225 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1226 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1227 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1228 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1229 ICmp2->swapOperands();
1232 if (!I1->isSameOperationAs(I2)) {
1234 ICmp2->swapOperands();
1238 // The operands should be either the same or they need to be generated
1239 // with a PHI node after sinking. We only handle the case where there is
1240 // a single pair of different operands.
1241 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1242 unsigned Op1Idx = 0;
1243 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1244 if (I1->getOperand(I) == I2->getOperand(I))
1246 // Early exit if we have more-than one pair of different operands or
1247 // the different operand is already in MapValueFromBB1ToBB2.
1248 // Early exit if we need a PHI node to replace a constant.
1250 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1251 MapValueFromBB1ToBB2.end() ||
1252 isa<Constant>(I1->getOperand(I)) ||
1253 isa<Constant>(I2->getOperand(I))) {
1254 // If we can't sink the instructions, undo the swapping.
1256 ICmp2->swapOperands();
1259 DifferentOp1 = I1->getOperand(I);
1261 DifferentOp2 = I2->getOperand(I);
1264 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1265 // remove (I1, I2) from MapValueFromBB1ToBB2.
1267 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1268 DifferentOp1->getName() + ".sink",
1270 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1271 // I1 should use NewPN instead of DifferentOp1.
1272 I1->setOperand(Op1Idx, NewPN);
1273 NewPN->addIncoming(DifferentOp1, BB1);
1274 NewPN->addIncoming(DifferentOp2, BB2);
1275 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1277 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1278 MapValueFromBB1ToBB2.erase(I1);
1280 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1281 DEBUG(dbgs() << " " << *I2 << "\n";);
1282 // We need to update RE1 and RE2 if we are going to sink the first
1283 // instruction in the basic block down.
1284 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1285 // Sink the instruction.
1286 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1287 if (!OldPN->use_empty())
1288 OldPN->replaceAllUsesWith(I1);
1289 OldPN->eraseFromParent();
1291 if (!I2->use_empty())
1292 I2->replaceAllUsesWith(I1);
1293 I1->intersectOptionalDataWith(I2);
1294 I2->eraseFromParent();
1297 RE1 = BB1->getInstList().rend();
1299 RE2 = BB2->getInstList().rend();
1300 FirstNonPhiInBBEnd = I1;
1307 /// \brief Determine if we can hoist sink a sole store instruction out of a
1308 /// conditional block.
1310 /// We are looking for code like the following:
1312 /// store i32 %add, i32* %arrayidx2
1313 /// ... // No other stores or function calls (we could be calling a memory
1314 /// ... // function).
1315 /// %cmp = icmp ult %x, %y
1316 /// br i1 %cmp, label %EndBB, label %ThenBB
1318 /// store i32 %add5, i32* %arrayidx2
1322 /// We are going to transform this into:
1324 /// store i32 %add, i32* %arrayidx2
1326 /// %cmp = icmp ult %x, %y
1327 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1328 /// store i32 %add.add5, i32* %arrayidx2
1331 /// \return The pointer to the value of the previous store if the store can be
1332 /// hoisted into the predecessor block. 0 otherwise.
1333 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1334 BasicBlock *StoreBB, BasicBlock *EndBB) {
1335 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1339 // Volatile or atomic.
1340 if (!StoreToHoist->isSimple())
1343 Value *StorePtr = StoreToHoist->getPointerOperand();
1345 // Look for a store to the same pointer in BrBB.
1346 unsigned MaxNumInstToLookAt = 10;
1347 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1348 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1349 Instruction *CurI = &*RI;
1351 // Could be calling an instruction that effects memory like free().
1352 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1355 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1356 // Found the previous store make sure it stores to the same location.
1357 if (SI && SI->getPointerOperand() == StorePtr)
1358 // Found the previous store, return its value operand.
1359 return SI->getValueOperand();
1361 return nullptr; // Unknown store.
1367 /// \brief Speculate a conditional basic block flattening the CFG.
1369 /// Note that this is a very risky transform currently. Speculating
1370 /// instructions like this is most often not desirable. Instead, there is an MI
1371 /// pass which can do it with full awareness of the resource constraints.
1372 /// However, some cases are "obvious" and we should do directly. An example of
1373 /// this is speculating a single, reasonably cheap instruction.
1375 /// There is only one distinct advantage to flattening the CFG at the IR level:
1376 /// it makes very common but simplistic optimizations such as are common in
1377 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1378 /// modeling their effects with easier to reason about SSA value graphs.
1381 /// An illustration of this transform is turning this IR:
1384 /// %cmp = icmp ult %x, %y
1385 /// br i1 %cmp, label %EndBB, label %ThenBB
1387 /// %sub = sub %x, %y
1390 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1397 /// %cmp = icmp ult %x, %y
1398 /// %sub = sub %x, %y
1399 /// %cond = select i1 %cmp, 0, %sub
1403 /// \returns true if the conditional block is removed.
1404 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1405 const DataLayout *DL) {
1406 // Be conservative for now. FP select instruction can often be expensive.
1407 Value *BrCond = BI->getCondition();
1408 if (isa<FCmpInst>(BrCond))
1411 BasicBlock *BB = BI->getParent();
1412 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1414 // If ThenBB is actually on the false edge of the conditional branch, remember
1415 // to swap the select operands later.
1416 bool Invert = false;
1417 if (ThenBB != BI->getSuccessor(0)) {
1418 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1421 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1423 // Keep a count of how many times instructions are used within CondBB when
1424 // they are candidates for sinking into CondBB. Specifically:
1425 // - They are defined in BB, and
1426 // - They have no side effects, and
1427 // - All of their uses are in CondBB.
1428 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1430 unsigned SpeculationCost = 0;
1431 Value *SpeculatedStoreValue = nullptr;
1432 StoreInst *SpeculatedStore = nullptr;
1433 for (BasicBlock::iterator BBI = ThenBB->begin(),
1434 BBE = std::prev(ThenBB->end());
1435 BBI != BBE; ++BBI) {
1436 Instruction *I = BBI;
1438 if (isa<DbgInfoIntrinsic>(I))
1441 // Only speculatively execution a single instruction (not counting the
1442 // terminator) for now.
1444 if (SpeculationCost > 1)
1447 // Don't hoist the instruction if it's unsafe or expensive.
1448 if (!isSafeToSpeculativelyExecute(I, DL) &&
1449 !(HoistCondStores &&
1450 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1453 if (!SpeculatedStoreValue &&
1454 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
1457 // Store the store speculation candidate.
1458 if (SpeculatedStoreValue)
1459 SpeculatedStore = cast<StoreInst>(I);
1461 // Do not hoist the instruction if any of its operands are defined but not
1462 // used in BB. The transformation will prevent the operand from
1463 // being sunk into the use block.
1464 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1466 Instruction *OpI = dyn_cast<Instruction>(*i);
1467 if (!OpI || OpI->getParent() != BB ||
1468 OpI->mayHaveSideEffects())
1469 continue; // Not a candidate for sinking.
1471 ++SinkCandidateUseCounts[OpI];
1475 // Consider any sink candidates which are only used in CondBB as costs for
1476 // speculation. Note, while we iterate over a DenseMap here, we are summing
1477 // and so iteration order isn't significant.
1478 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1479 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1481 if (I->first->getNumUses() == I->second) {
1483 if (SpeculationCost > 1)
1487 // Check that the PHI nodes can be converted to selects.
1488 bool HaveRewritablePHIs = false;
1489 for (BasicBlock::iterator I = EndBB->begin();
1490 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1491 Value *OrigV = PN->getIncomingValueForBlock(BB);
1492 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1494 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1495 // Skip PHIs which are trivial.
1499 HaveRewritablePHIs = true;
1500 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1501 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1502 if (!OrigCE && !ThenCE)
1503 continue; // Known safe and cheap.
1505 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1506 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1508 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1509 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
1510 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1513 // Account for the cost of an unfolded ConstantExpr which could end up
1514 // getting expanded into Instructions.
1515 // FIXME: This doesn't account for how many operations are combined in the
1516 // constant expression.
1518 if (SpeculationCost > 1)
1522 // If there are no PHIs to process, bail early. This helps ensure idempotence
1524 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1527 // If we get here, we can hoist the instruction and if-convert.
1528 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1530 // Insert a select of the value of the speculated store.
1531 if (SpeculatedStoreValue) {
1532 IRBuilder<true, NoFolder> Builder(BI);
1533 Value *TrueV = SpeculatedStore->getValueOperand();
1534 Value *FalseV = SpeculatedStoreValue;
1536 std::swap(TrueV, FalseV);
1537 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1538 "." + FalseV->getName());
1539 SpeculatedStore->setOperand(0, S);
1542 // Hoist the instructions.
1543 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1544 std::prev(ThenBB->end()));
1546 // Insert selects and rewrite the PHI operands.
1547 IRBuilder<true, NoFolder> Builder(BI);
1548 for (BasicBlock::iterator I = EndBB->begin();
1549 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1550 unsigned OrigI = PN->getBasicBlockIndex(BB);
1551 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1552 Value *OrigV = PN->getIncomingValue(OrigI);
1553 Value *ThenV = PN->getIncomingValue(ThenI);
1555 // Skip PHIs which are trivial.
1559 // Create a select whose true value is the speculatively executed value and
1560 // false value is the preexisting value. Swap them if the branch
1561 // destinations were inverted.
1562 Value *TrueV = ThenV, *FalseV = OrigV;
1564 std::swap(TrueV, FalseV);
1565 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1566 TrueV->getName() + "." + FalseV->getName());
1567 PN->setIncomingValue(OrigI, V);
1568 PN->setIncomingValue(ThenI, V);
1575 /// \returns True if this block contains a CallInst with the NoDuplicate
1577 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1578 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1579 const CallInst *CI = dyn_cast<CallInst>(I);
1582 if (CI->cannotDuplicate())
1588 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1589 /// across this block.
1590 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1591 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1594 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1595 if (isa<DbgInfoIntrinsic>(BBI))
1597 if (Size > 10) return false; // Don't clone large BB's.
1600 // We can only support instructions that do not define values that are
1601 // live outside of the current basic block.
1602 for (User *U : BBI->users()) {
1603 Instruction *UI = cast<Instruction>(U);
1604 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1607 // Looks ok, continue checking.
1613 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1614 /// that is defined in the same block as the branch and if any PHI entries are
1615 /// constants, thread edges corresponding to that entry to be branches to their
1616 /// ultimate destination.
1617 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1618 BasicBlock *BB = BI->getParent();
1619 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1620 // NOTE: we currently cannot transform this case if the PHI node is used
1621 // outside of the block.
1622 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1625 // Degenerate case of a single entry PHI.
1626 if (PN->getNumIncomingValues() == 1) {
1627 FoldSingleEntryPHINodes(PN->getParent());
1631 // Now we know that this block has multiple preds and two succs.
1632 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1634 if (HasNoDuplicateCall(BB)) return false;
1636 // Okay, this is a simple enough basic block. See if any phi values are
1638 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1639 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1640 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1642 // Okay, we now know that all edges from PredBB should be revectored to
1643 // branch to RealDest.
1644 BasicBlock *PredBB = PN->getIncomingBlock(i);
1645 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1647 if (RealDest == BB) continue; // Skip self loops.
1648 // Skip if the predecessor's terminator is an indirect branch.
1649 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1651 // The dest block might have PHI nodes, other predecessors and other
1652 // difficult cases. Instead of being smart about this, just insert a new
1653 // block that jumps to the destination block, effectively splitting
1654 // the edge we are about to create.
1655 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1656 RealDest->getName()+".critedge",
1657 RealDest->getParent(), RealDest);
1658 BranchInst::Create(RealDest, EdgeBB);
1660 // Update PHI nodes.
1661 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1663 // BB may have instructions that are being threaded over. Clone these
1664 // instructions into EdgeBB. We know that there will be no uses of the
1665 // cloned instructions outside of EdgeBB.
1666 BasicBlock::iterator InsertPt = EdgeBB->begin();
1667 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1668 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1669 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1670 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1673 // Clone the instruction.
1674 Instruction *N = BBI->clone();
1675 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1677 // Update operands due to translation.
1678 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1680 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1681 if (PI != TranslateMap.end())
1685 // Check for trivial simplification.
1686 if (Value *V = SimplifyInstruction(N, DL)) {
1687 TranslateMap[BBI] = V;
1688 delete N; // Instruction folded away, don't need actual inst
1690 // Insert the new instruction into its new home.
1691 EdgeBB->getInstList().insert(InsertPt, N);
1692 if (!BBI->use_empty())
1693 TranslateMap[BBI] = N;
1697 // Loop over all of the edges from PredBB to BB, changing them to branch
1698 // to EdgeBB instead.
1699 TerminatorInst *PredBBTI = PredBB->getTerminator();
1700 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1701 if (PredBBTI->getSuccessor(i) == BB) {
1702 BB->removePredecessor(PredBB);
1703 PredBBTI->setSuccessor(i, EdgeBB);
1706 // Recurse, simplifying any other constants.
1707 return FoldCondBranchOnPHI(BI, DL) | true;
1713 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1714 /// PHI node, see if we can eliminate it.
1715 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1716 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1717 // statement", which has a very simple dominance structure. Basically, we
1718 // are trying to find the condition that is being branched on, which
1719 // subsequently causes this merge to happen. We really want control
1720 // dependence information for this check, but simplifycfg can't keep it up
1721 // to date, and this catches most of the cases we care about anyway.
1722 BasicBlock *BB = PN->getParent();
1723 BasicBlock *IfTrue, *IfFalse;
1724 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1726 // Don't bother if the branch will be constant folded trivially.
1727 isa<ConstantInt>(IfCond))
1730 // Okay, we found that we can merge this two-entry phi node into a select.
1731 // Doing so would require us to fold *all* two entry phi nodes in this block.
1732 // At some point this becomes non-profitable (particularly if the target
1733 // doesn't support cmov's). Only do this transformation if there are two or
1734 // fewer PHI nodes in this block.
1735 unsigned NumPhis = 0;
1736 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1740 // Loop over the PHI's seeing if we can promote them all to select
1741 // instructions. While we are at it, keep track of the instructions
1742 // that need to be moved to the dominating block.
1743 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1744 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1745 MaxCostVal1 = PHINodeFoldingThreshold;
1747 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1748 PHINode *PN = cast<PHINode>(II++);
1749 if (Value *V = SimplifyInstruction(PN, DL)) {
1750 PN->replaceAllUsesWith(V);
1751 PN->eraseFromParent();
1755 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1757 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1762 // If we folded the first phi, PN dangles at this point. Refresh it. If
1763 // we ran out of PHIs then we simplified them all.
1764 PN = dyn_cast<PHINode>(BB->begin());
1765 if (!PN) return true;
1767 // Don't fold i1 branches on PHIs which contain binary operators. These can
1768 // often be turned into switches and other things.
1769 if (PN->getType()->isIntegerTy(1) &&
1770 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1771 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1772 isa<BinaryOperator>(IfCond)))
1775 // If we all PHI nodes are promotable, check to make sure that all
1776 // instructions in the predecessor blocks can be promoted as well. If
1777 // not, we won't be able to get rid of the control flow, so it's not
1778 // worth promoting to select instructions.
1779 BasicBlock *DomBlock = nullptr;
1780 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1781 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1782 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1785 DomBlock = *pred_begin(IfBlock1);
1786 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1787 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1788 // This is not an aggressive instruction that we can promote.
1789 // Because of this, we won't be able to get rid of the control
1790 // flow, so the xform is not worth it.
1795 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1798 DomBlock = *pred_begin(IfBlock2);
1799 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1800 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1801 // This is not an aggressive instruction that we can promote.
1802 // Because of this, we won't be able to get rid of the control
1803 // flow, so the xform is not worth it.
1808 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1809 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1811 // If we can still promote the PHI nodes after this gauntlet of tests,
1812 // do all of the PHI's now.
1813 Instruction *InsertPt = DomBlock->getTerminator();
1814 IRBuilder<true, NoFolder> Builder(InsertPt);
1816 // Move all 'aggressive' instructions, which are defined in the
1817 // conditional parts of the if's up to the dominating block.
1819 DomBlock->getInstList().splice(InsertPt,
1820 IfBlock1->getInstList(), IfBlock1->begin(),
1821 IfBlock1->getTerminator());
1823 DomBlock->getInstList().splice(InsertPt,
1824 IfBlock2->getInstList(), IfBlock2->begin(),
1825 IfBlock2->getTerminator());
1827 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1828 // Change the PHI node into a select instruction.
1829 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1830 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1833 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1834 PN->replaceAllUsesWith(NV);
1836 PN->eraseFromParent();
1839 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1840 // has been flattened. Change DomBlock to jump directly to our new block to
1841 // avoid other simplifycfg's kicking in on the diamond.
1842 TerminatorInst *OldTI = DomBlock->getTerminator();
1843 Builder.SetInsertPoint(OldTI);
1844 Builder.CreateBr(BB);
1845 OldTI->eraseFromParent();
1849 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1850 /// to two returning blocks, try to merge them together into one return,
1851 /// introducing a select if the return values disagree.
1852 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1853 IRBuilder<> &Builder) {
1854 assert(BI->isConditional() && "Must be a conditional branch");
1855 BasicBlock *TrueSucc = BI->getSuccessor(0);
1856 BasicBlock *FalseSucc = BI->getSuccessor(1);
1857 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1858 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1860 // Check to ensure both blocks are empty (just a return) or optionally empty
1861 // with PHI nodes. If there are other instructions, merging would cause extra
1862 // computation on one path or the other.
1863 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1865 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1868 Builder.SetInsertPoint(BI);
1869 // Okay, we found a branch that is going to two return nodes. If
1870 // there is no return value for this function, just change the
1871 // branch into a return.
1872 if (FalseRet->getNumOperands() == 0) {
1873 TrueSucc->removePredecessor(BI->getParent());
1874 FalseSucc->removePredecessor(BI->getParent());
1875 Builder.CreateRetVoid();
1876 EraseTerminatorInstAndDCECond(BI);
1880 // Otherwise, figure out what the true and false return values are
1881 // so we can insert a new select instruction.
1882 Value *TrueValue = TrueRet->getReturnValue();
1883 Value *FalseValue = FalseRet->getReturnValue();
1885 // Unwrap any PHI nodes in the return blocks.
1886 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1887 if (TVPN->getParent() == TrueSucc)
1888 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1889 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1890 if (FVPN->getParent() == FalseSucc)
1891 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1893 // In order for this transformation to be safe, we must be able to
1894 // unconditionally execute both operands to the return. This is
1895 // normally the case, but we could have a potentially-trapping
1896 // constant expression that prevents this transformation from being
1898 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1901 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1905 // Okay, we collected all the mapped values and checked them for sanity, and
1906 // defined to really do this transformation. First, update the CFG.
1907 TrueSucc->removePredecessor(BI->getParent());
1908 FalseSucc->removePredecessor(BI->getParent());
1910 // Insert select instructions where needed.
1911 Value *BrCond = BI->getCondition();
1913 // Insert a select if the results differ.
1914 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1915 } else if (isa<UndefValue>(TrueValue)) {
1916 TrueValue = FalseValue;
1918 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1919 FalseValue, "retval");
1923 Value *RI = !TrueValue ?
1924 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1928 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1929 << "\n " << *BI << "NewRet = " << *RI
1930 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1932 EraseTerminatorInstAndDCECond(BI);
1937 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1938 /// probabilities of the branch taking each edge. Fills in the two APInt
1939 /// parameters and return true, or returns false if no or invalid metadata was
1941 static bool ExtractBranchMetadata(BranchInst *BI,
1942 uint64_t &ProbTrue, uint64_t &ProbFalse) {
1943 assert(BI->isConditional() &&
1944 "Looking for probabilities on unconditional branch?");
1945 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1946 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1947 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1948 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1949 if (!CITrue || !CIFalse) return false;
1950 ProbTrue = CITrue->getValue().getZExtValue();
1951 ProbFalse = CIFalse->getValue().getZExtValue();
1955 /// checkCSEInPredecessor - Return true if the given instruction is available
1956 /// in its predecessor block. If yes, the instruction will be removed.
1958 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1959 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1961 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1962 Instruction *PBI = &*I;
1963 // Check whether Inst and PBI generate the same value.
1964 if (Inst->isIdenticalTo(PBI)) {
1965 Inst->replaceAllUsesWith(PBI);
1966 Inst->eraseFromParent();
1973 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1974 /// predecessor branches to us and one of our successors, fold the block into
1975 /// the predecessor and use logical operations to pick the right destination.
1976 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL) {
1977 BasicBlock *BB = BI->getParent();
1979 Instruction *Cond = nullptr;
1980 if (BI->isConditional())
1981 Cond = dyn_cast<Instruction>(BI->getCondition());
1983 // For unconditional branch, check for a simple CFG pattern, where
1984 // BB has a single predecessor and BB's successor is also its predecessor's
1985 // successor. If such pattern exisits, check for CSE between BB and its
1987 if (BasicBlock *PB = BB->getSinglePredecessor())
1988 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1989 if (PBI->isConditional() &&
1990 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1991 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1992 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1994 Instruction *Curr = I++;
1995 if (isa<CmpInst>(Curr)) {
1999 // Quit if we can't remove this instruction.
2000 if (!checkCSEInPredecessor(Curr, PB))
2009 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2010 Cond->getParent() != BB || !Cond->hasOneUse())
2013 // Only allow this if the condition is a simple instruction that can be
2014 // executed unconditionally. It must be in the same block as the branch, and
2015 // must be at the front of the block.
2016 BasicBlock::iterator FrontIt = BB->front();
2018 // Ignore dbg intrinsics.
2019 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2021 // Allow a single instruction to be hoisted in addition to the compare
2022 // that feeds the branch. We later ensure that any values that _it_ uses
2023 // were also live in the predecessor, so that we don't unnecessarily create
2024 // register pressure or inhibit out-of-order execution.
2025 Instruction *BonusInst = nullptr;
2026 if (&*FrontIt != Cond &&
2027 FrontIt->hasOneUse() && FrontIt->user_back() == Cond &&
2028 isSafeToSpeculativelyExecute(FrontIt, DL)) {
2029 BonusInst = &*FrontIt;
2032 // Ignore dbg intrinsics.
2033 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2036 // Only a single bonus inst is allowed.
2037 if (&*FrontIt != Cond)
2040 // Make sure the instruction after the condition is the cond branch.
2041 BasicBlock::iterator CondIt = Cond; ++CondIt;
2043 // Ignore dbg intrinsics.
2044 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2049 // Cond is known to be a compare or binary operator. Check to make sure that
2050 // neither operand is a potentially-trapping constant expression.
2051 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2054 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2058 // Finally, don't infinitely unroll conditional loops.
2059 BasicBlock *TrueDest = BI->getSuccessor(0);
2060 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2061 if (TrueDest == BB || FalseDest == BB)
2064 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2065 BasicBlock *PredBlock = *PI;
2066 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2068 // Check that we have two conditional branches. If there is a PHI node in
2069 // the common successor, verify that the same value flows in from both
2071 SmallVector<PHINode*, 4> PHIs;
2072 if (!PBI || PBI->isUnconditional() ||
2073 (BI->isConditional() &&
2074 !SafeToMergeTerminators(BI, PBI)) ||
2075 (!BI->isConditional() &&
2076 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2079 // Determine if the two branches share a common destination.
2080 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2081 bool InvertPredCond = false;
2083 if (BI->isConditional()) {
2084 if (PBI->getSuccessor(0) == TrueDest)
2085 Opc = Instruction::Or;
2086 else if (PBI->getSuccessor(1) == FalseDest)
2087 Opc = Instruction::And;
2088 else if (PBI->getSuccessor(0) == FalseDest)
2089 Opc = Instruction::And, InvertPredCond = true;
2090 else if (PBI->getSuccessor(1) == TrueDest)
2091 Opc = Instruction::Or, InvertPredCond = true;
2095 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2099 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2100 IRBuilder<> Builder(PBI);
2102 // If we need to invert the condition in the pred block to match, do so now.
2103 if (InvertPredCond) {
2104 Value *NewCond = PBI->getCondition();
2106 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2107 CmpInst *CI = cast<CmpInst>(NewCond);
2108 CI->setPredicate(CI->getInversePredicate());
2110 NewCond = Builder.CreateNot(NewCond,
2111 PBI->getCondition()->getName()+".not");
2114 PBI->setCondition(NewCond);
2115 PBI->swapSuccessors();
2118 // If we have a bonus inst, clone it into the predecessor block.
2119 Instruction *NewBonus = nullptr;
2121 NewBonus = BonusInst->clone();
2123 // If we moved a load, we cannot any longer claim any knowledge about
2124 // its potential value. The previous information might have been valid
2125 // only given the branch precondition.
2126 // For an analogous reason, we must also drop all the metadata whose
2127 // semantics we don't understand.
2128 NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
2130 PredBlock->getInstList().insert(PBI, NewBonus);
2131 NewBonus->takeName(BonusInst);
2132 BonusInst->setName(BonusInst->getName()+".old");
2135 // Clone Cond into the predecessor basic block, and or/and the
2136 // two conditions together.
2137 Instruction *New = Cond->clone();
2138 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
2139 PredBlock->getInstList().insert(PBI, New);
2140 New->takeName(Cond);
2141 Cond->setName(New->getName()+".old");
2143 if (BI->isConditional()) {
2144 Instruction *NewCond =
2145 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2147 PBI->setCondition(NewCond);
2149 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2150 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2152 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2154 SmallVector<uint64_t, 8> NewWeights;
2156 if (PBI->getSuccessor(0) == BB) {
2157 if (PredHasWeights && SuccHasWeights) {
2158 // PBI: br i1 %x, BB, FalseDest
2159 // BI: br i1 %y, TrueDest, FalseDest
2160 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2161 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2162 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2163 // TrueWeight for PBI * FalseWeight for BI.
2164 // We assume that total weights of a BranchInst can fit into 32 bits.
2165 // Therefore, we will not have overflow using 64-bit arithmetic.
2166 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2167 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2169 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2170 PBI->setSuccessor(0, TrueDest);
2172 if (PBI->getSuccessor(1) == BB) {
2173 if (PredHasWeights && SuccHasWeights) {
2174 // PBI: br i1 %x, TrueDest, BB
2175 // BI: br i1 %y, TrueDest, FalseDest
2176 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2177 // FalseWeight for PBI * TrueWeight for BI.
2178 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2179 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2180 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2181 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2183 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2184 PBI->setSuccessor(1, FalseDest);
2186 if (NewWeights.size() == 2) {
2187 // Halve the weights if any of them cannot fit in an uint32_t
2188 FitWeights(NewWeights);
2190 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2191 PBI->setMetadata(LLVMContext::MD_prof,
2192 MDBuilder(BI->getContext()).
2193 createBranchWeights(MDWeights));
2195 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2197 // Update PHI nodes in the common successors.
2198 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2199 ConstantInt *PBI_C = cast<ConstantInt>(
2200 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2201 assert(PBI_C->getType()->isIntegerTy(1));
2202 Instruction *MergedCond = nullptr;
2203 if (PBI->getSuccessor(0) == TrueDest) {
2204 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2205 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2206 // is false: !PBI_Cond and BI_Value
2207 Instruction *NotCond =
2208 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2211 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2216 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2217 PBI->getCondition(), MergedCond,
2220 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2221 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2222 // is false: PBI_Cond and BI_Value
2224 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2225 PBI->getCondition(), New,
2227 if (PBI_C->isOne()) {
2228 Instruction *NotCond =
2229 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2232 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2233 NotCond, MergedCond,
2238 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2241 // Change PBI from Conditional to Unconditional.
2242 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2243 EraseTerminatorInstAndDCECond(PBI);
2247 // TODO: If BB is reachable from all paths through PredBlock, then we
2248 // could replace PBI's branch probabilities with BI's.
2250 // Copy any debug value intrinsics into the end of PredBlock.
2251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2252 if (isa<DbgInfoIntrinsic>(*I))
2253 I->clone()->insertBefore(PBI);
2260 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2261 /// predecessor of another block, this function tries to simplify it. We know
2262 /// that PBI and BI are both conditional branches, and BI is in one of the
2263 /// successor blocks of PBI - PBI branches to BI.
2264 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2265 assert(PBI->isConditional() && BI->isConditional());
2266 BasicBlock *BB = BI->getParent();
2268 // If this block ends with a branch instruction, and if there is a
2269 // predecessor that ends on a branch of the same condition, make
2270 // this conditional branch redundant.
2271 if (PBI->getCondition() == BI->getCondition() &&
2272 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2273 // Okay, the outcome of this conditional branch is statically
2274 // knowable. If this block had a single pred, handle specially.
2275 if (BB->getSinglePredecessor()) {
2276 // Turn this into a branch on constant.
2277 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2278 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2280 return true; // Nuke the branch on constant.
2283 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2284 // in the constant and simplify the block result. Subsequent passes of
2285 // simplifycfg will thread the block.
2286 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2287 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2288 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2289 std::distance(PB, PE),
2290 BI->getCondition()->getName() + ".pr",
2292 // Okay, we're going to insert the PHI node. Since PBI is not the only
2293 // predecessor, compute the PHI'd conditional value for all of the preds.
2294 // Any predecessor where the condition is not computable we keep symbolic.
2295 for (pred_iterator PI = PB; PI != PE; ++PI) {
2296 BasicBlock *P = *PI;
2297 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2298 PBI != BI && PBI->isConditional() &&
2299 PBI->getCondition() == BI->getCondition() &&
2300 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2301 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2302 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2305 NewPN->addIncoming(BI->getCondition(), P);
2309 BI->setCondition(NewPN);
2314 // If this is a conditional branch in an empty block, and if any
2315 // predecessors are a conditional branch to one of our destinations,
2316 // fold the conditions into logical ops and one cond br.
2317 BasicBlock::iterator BBI = BB->begin();
2318 // Ignore dbg intrinsics.
2319 while (isa<DbgInfoIntrinsic>(BBI))
2325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2330 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2332 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2333 PBIOp = 0, BIOp = 1;
2334 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2335 PBIOp = 1, BIOp = 0;
2336 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2341 // Check to make sure that the other destination of this branch
2342 // isn't BB itself. If so, this is an infinite loop that will
2343 // keep getting unwound.
2344 if (PBI->getSuccessor(PBIOp) == BB)
2347 // Do not perform this transformation if it would require
2348 // insertion of a large number of select instructions. For targets
2349 // without predication/cmovs, this is a big pessimization.
2351 // Also do not perform this transformation if any phi node in the common
2352 // destination block can trap when reached by BB or PBB (PR17073). In that
2353 // case, it would be unsafe to hoist the operation into a select instruction.
2355 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2356 unsigned NumPhis = 0;
2357 for (BasicBlock::iterator II = CommonDest->begin();
2358 isa<PHINode>(II); ++II, ++NumPhis) {
2359 if (NumPhis > 2) // Disable this xform.
2362 PHINode *PN = cast<PHINode>(II);
2363 Value *BIV = PN->getIncomingValueForBlock(BB);
2364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2368 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2369 Value *PBIV = PN->getIncomingValue(PBBIdx);
2370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2375 // Finally, if everything is ok, fold the branches to logical ops.
2376 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2378 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2379 << "AND: " << *BI->getParent());
2382 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2383 // branch in it, where one edge (OtherDest) goes back to itself but the other
2384 // exits. We don't *know* that the program avoids the infinite loop
2385 // (even though that seems likely). If we do this xform naively, we'll end up
2386 // recursively unpeeling the loop. Since we know that (after the xform is
2387 // done) that the block *is* infinite if reached, we just make it an obviously
2388 // infinite loop with no cond branch.
2389 if (OtherDest == BB) {
2390 // Insert it at the end of the function, because it's either code,
2391 // or it won't matter if it's hot. :)
2392 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2393 "infloop", BB->getParent());
2394 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2395 OtherDest = InfLoopBlock;
2398 DEBUG(dbgs() << *PBI->getParent()->getParent());
2400 // BI may have other predecessors. Because of this, we leave
2401 // it alone, but modify PBI.
2403 // Make sure we get to CommonDest on True&True directions.
2404 Value *PBICond = PBI->getCondition();
2405 IRBuilder<true, NoFolder> Builder(PBI);
2407 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2409 Value *BICond = BI->getCondition();
2411 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2413 // Merge the conditions.
2414 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2416 // Modify PBI to branch on the new condition to the new dests.
2417 PBI->setCondition(Cond);
2418 PBI->setSuccessor(0, CommonDest);
2419 PBI->setSuccessor(1, OtherDest);
2421 // Update branch weight for PBI.
2422 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2423 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2425 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2427 if (PredHasWeights && SuccHasWeights) {
2428 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2429 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2430 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2431 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2432 // The weight to CommonDest should be PredCommon * SuccTotal +
2433 // PredOther * SuccCommon.
2434 // The weight to OtherDest should be PredOther * SuccOther.
2435 SmallVector<uint64_t, 2> NewWeights;
2436 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2437 PredOther * SuccCommon);
2438 NewWeights.push_back(PredOther * SuccOther);
2439 // Halve the weights if any of them cannot fit in an uint32_t
2440 FitWeights(NewWeights);
2442 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2443 PBI->setMetadata(LLVMContext::MD_prof,
2444 MDBuilder(BI->getContext()).
2445 createBranchWeights(MDWeights));
2448 // OtherDest may have phi nodes. If so, add an entry from PBI's
2449 // block that are identical to the entries for BI's block.
2450 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2452 // We know that the CommonDest already had an edge from PBI to
2453 // it. If it has PHIs though, the PHIs may have different
2454 // entries for BB and PBI's BB. If so, insert a select to make
2457 for (BasicBlock::iterator II = CommonDest->begin();
2458 (PN = dyn_cast<PHINode>(II)); ++II) {
2459 Value *BIV = PN->getIncomingValueForBlock(BB);
2460 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2461 Value *PBIV = PN->getIncomingValue(PBBIdx);
2463 // Insert a select in PBI to pick the right value.
2464 Value *NV = cast<SelectInst>
2465 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2466 PN->setIncomingValue(PBBIdx, NV);
2470 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2471 DEBUG(dbgs() << *PBI->getParent()->getParent());
2473 // This basic block is probably dead. We know it has at least
2474 // one fewer predecessor.
2478 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2479 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2480 // Takes care of updating the successors and removing the old terminator.
2481 // Also makes sure not to introduce new successors by assuming that edges to
2482 // non-successor TrueBBs and FalseBBs aren't reachable.
2483 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2484 BasicBlock *TrueBB, BasicBlock *FalseBB,
2485 uint32_t TrueWeight,
2486 uint32_t FalseWeight){
2487 // Remove any superfluous successor edges from the CFG.
2488 // First, figure out which successors to preserve.
2489 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2491 BasicBlock *KeepEdge1 = TrueBB;
2492 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2494 // Then remove the rest.
2495 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2496 BasicBlock *Succ = OldTerm->getSuccessor(I);
2497 // Make sure only to keep exactly one copy of each edge.
2498 if (Succ == KeepEdge1)
2499 KeepEdge1 = nullptr;
2500 else if (Succ == KeepEdge2)
2501 KeepEdge2 = nullptr;
2503 Succ->removePredecessor(OldTerm->getParent());
2506 IRBuilder<> Builder(OldTerm);
2507 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2509 // Insert an appropriate new terminator.
2510 if (!KeepEdge1 && !KeepEdge2) {
2511 if (TrueBB == FalseBB)
2512 // We were only looking for one successor, and it was present.
2513 // Create an unconditional branch to it.
2514 Builder.CreateBr(TrueBB);
2516 // We found both of the successors we were looking for.
2517 // Create a conditional branch sharing the condition of the select.
2518 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2519 if (TrueWeight != FalseWeight)
2520 NewBI->setMetadata(LLVMContext::MD_prof,
2521 MDBuilder(OldTerm->getContext()).
2522 createBranchWeights(TrueWeight, FalseWeight));
2524 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2525 // Neither of the selected blocks were successors, so this
2526 // terminator must be unreachable.
2527 new UnreachableInst(OldTerm->getContext(), OldTerm);
2529 // One of the selected values was a successor, but the other wasn't.
2530 // Insert an unconditional branch to the one that was found;
2531 // the edge to the one that wasn't must be unreachable.
2533 // Only TrueBB was found.
2534 Builder.CreateBr(TrueBB);
2536 // Only FalseBB was found.
2537 Builder.CreateBr(FalseBB);
2540 EraseTerminatorInstAndDCECond(OldTerm);
2544 // SimplifySwitchOnSelect - Replaces
2545 // (switch (select cond, X, Y)) on constant X, Y
2546 // with a branch - conditional if X and Y lead to distinct BBs,
2547 // unconditional otherwise.
2548 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2549 // Check for constant integer values in the select.
2550 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2551 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2552 if (!TrueVal || !FalseVal)
2555 // Find the relevant condition and destinations.
2556 Value *Condition = Select->getCondition();
2557 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2558 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2560 // Get weight for TrueBB and FalseBB.
2561 uint32_t TrueWeight = 0, FalseWeight = 0;
2562 SmallVector<uint64_t, 8> Weights;
2563 bool HasWeights = HasBranchWeights(SI);
2565 GetBranchWeights(SI, Weights);
2566 if (Weights.size() == 1 + SI->getNumCases()) {
2567 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2568 getSuccessorIndex()];
2569 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2570 getSuccessorIndex()];
2574 // Perform the actual simplification.
2575 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2576 TrueWeight, FalseWeight);
2579 // SimplifyIndirectBrOnSelect - Replaces
2580 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2581 // blockaddress(@fn, BlockB)))
2583 // (br cond, BlockA, BlockB).
2584 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2585 // Check that both operands of the select are block addresses.
2586 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2587 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2591 // Extract the actual blocks.
2592 BasicBlock *TrueBB = TBA->getBasicBlock();
2593 BasicBlock *FalseBB = FBA->getBasicBlock();
2595 // Perform the actual simplification.
2596 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2600 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2601 /// instruction (a seteq/setne with a constant) as the only instruction in a
2602 /// block that ends with an uncond branch. We are looking for a very specific
2603 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2604 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2605 /// default value goes to an uncond block with a seteq in it, we get something
2608 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2610 /// %tmp = icmp eq i8 %A, 92
2613 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2615 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2616 /// the PHI, merging the third icmp into the switch.
2617 static bool TryToSimplifyUncondBranchWithICmpInIt(
2618 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2619 const DataLayout *DL, AssumptionTracker *AT) {
2620 BasicBlock *BB = ICI->getParent();
2622 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2624 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2626 Value *V = ICI->getOperand(0);
2627 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2629 // The pattern we're looking for is where our only predecessor is a switch on
2630 // 'V' and this block is the default case for the switch. In this case we can
2631 // fold the compared value into the switch to simplify things.
2632 BasicBlock *Pred = BB->getSinglePredecessor();
2633 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2635 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2636 if (SI->getCondition() != V)
2639 // If BB is reachable on a non-default case, then we simply know the value of
2640 // V in this block. Substitute it and constant fold the icmp instruction
2642 if (SI->getDefaultDest() != BB) {
2643 ConstantInt *VVal = SI->findCaseDest(BB);
2644 assert(VVal && "Should have a unique destination value");
2645 ICI->setOperand(0, VVal);
2647 if (Value *V = SimplifyInstruction(ICI, DL)) {
2648 ICI->replaceAllUsesWith(V);
2649 ICI->eraseFromParent();
2651 // BB is now empty, so it is likely to simplify away.
2652 return SimplifyCFG(BB, TTI, DL, AT) | true;
2655 // Ok, the block is reachable from the default dest. If the constant we're
2656 // comparing exists in one of the other edges, then we can constant fold ICI
2658 if (SI->findCaseValue(Cst) != SI->case_default()) {
2660 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2661 V = ConstantInt::getFalse(BB->getContext());
2663 V = ConstantInt::getTrue(BB->getContext());
2665 ICI->replaceAllUsesWith(V);
2666 ICI->eraseFromParent();
2667 // BB is now empty, so it is likely to simplify away.
2668 return SimplifyCFG(BB, TTI, DL, AT) | true;
2671 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2673 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2674 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2675 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2676 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2679 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2681 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2682 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2684 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2685 std::swap(DefaultCst, NewCst);
2687 // Replace ICI (which is used by the PHI for the default value) with true or
2688 // false depending on if it is EQ or NE.
2689 ICI->replaceAllUsesWith(DefaultCst);
2690 ICI->eraseFromParent();
2692 // Okay, the switch goes to this block on a default value. Add an edge from
2693 // the switch to the merge point on the compared value.
2694 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2695 BB->getParent(), BB);
2696 SmallVector<uint64_t, 8> Weights;
2697 bool HasWeights = HasBranchWeights(SI);
2699 GetBranchWeights(SI, Weights);
2700 if (Weights.size() == 1 + SI->getNumCases()) {
2701 // Split weight for default case to case for "Cst".
2702 Weights[0] = (Weights[0]+1) >> 1;
2703 Weights.push_back(Weights[0]);
2705 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2706 SI->setMetadata(LLVMContext::MD_prof,
2707 MDBuilder(SI->getContext()).
2708 createBranchWeights(MDWeights));
2711 SI->addCase(Cst, NewBB);
2713 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2714 Builder.SetInsertPoint(NewBB);
2715 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2716 Builder.CreateBr(SuccBlock);
2717 PHIUse->addIncoming(NewCst, NewBB);
2721 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2722 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2723 /// fold it into a switch instruction if so.
2724 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2725 IRBuilder<> &Builder) {
2726 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2727 if (!Cond) return false;
2730 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2731 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2732 // 'setne's and'ed together, collect them.
2733 Value *CompVal = nullptr;
2734 std::vector<ConstantInt*> Values;
2735 bool TrueWhenEqual = true;
2736 Value *ExtraCase = nullptr;
2737 unsigned UsedICmps = 0;
2739 if (Cond->getOpcode() == Instruction::Or) {
2740 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
2742 } else if (Cond->getOpcode() == Instruction::And) {
2743 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
2745 TrueWhenEqual = false;
2748 // If we didn't have a multiply compared value, fail.
2749 if (!CompVal) return false;
2751 // Avoid turning single icmps into a switch.
2755 // There might be duplicate constants in the list, which the switch
2756 // instruction can't handle, remove them now.
2757 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2758 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2760 // If Extra was used, we require at least two switch values to do the
2761 // transformation. A switch with one value is just an cond branch.
2762 if (ExtraCase && Values.size() < 2) return false;
2764 // TODO: Preserve branch weight metadata, similarly to how
2765 // FoldValueComparisonIntoPredecessors preserves it.
2767 // Figure out which block is which destination.
2768 BasicBlock *DefaultBB = BI->getSuccessor(1);
2769 BasicBlock *EdgeBB = BI->getSuccessor(0);
2770 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2772 BasicBlock *BB = BI->getParent();
2774 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2775 << " cases into SWITCH. BB is:\n" << *BB);
2777 // If there are any extra values that couldn't be folded into the switch
2778 // then we evaluate them with an explicit branch first. Split the block
2779 // right before the condbr to handle it.
2781 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2782 // Remove the uncond branch added to the old block.
2783 TerminatorInst *OldTI = BB->getTerminator();
2784 Builder.SetInsertPoint(OldTI);
2787 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2789 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2791 OldTI->eraseFromParent();
2793 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2794 // for the edge we just added.
2795 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2797 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2798 << "\nEXTRABB = " << *BB);
2802 Builder.SetInsertPoint(BI);
2803 // Convert pointer to int before we switch.
2804 if (CompVal->getType()->isPointerTy()) {
2805 assert(DL && "Cannot switch on pointer without DataLayout");
2806 CompVal = Builder.CreatePtrToInt(CompVal,
2807 DL->getIntPtrType(CompVal->getType()),
2811 // Create the new switch instruction now.
2812 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2814 // Add all of the 'cases' to the switch instruction.
2815 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2816 New->addCase(Values[i], EdgeBB);
2818 // We added edges from PI to the EdgeBB. As such, if there were any
2819 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2820 // the number of edges added.
2821 for (BasicBlock::iterator BBI = EdgeBB->begin();
2822 isa<PHINode>(BBI); ++BBI) {
2823 PHINode *PN = cast<PHINode>(BBI);
2824 Value *InVal = PN->getIncomingValueForBlock(BB);
2825 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2826 PN->addIncoming(InVal, BB);
2829 // Erase the old branch instruction.
2830 EraseTerminatorInstAndDCECond(BI);
2832 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2836 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2837 // If this is a trivial landing pad that just continues unwinding the caught
2838 // exception then zap the landing pad, turning its invokes into calls.
2839 BasicBlock *BB = RI->getParent();
2840 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2841 if (RI->getValue() != LPInst)
2842 // Not a landing pad, or the resume is not unwinding the exception that
2843 // caused control to branch here.
2846 // Check that there are no other instructions except for debug intrinsics.
2847 BasicBlock::iterator I = LPInst, E = RI;
2849 if (!isa<DbgInfoIntrinsic>(I))
2852 // Turn all invokes that unwind here into calls and delete the basic block.
2853 bool InvokeRequiresTableEntry = false;
2854 bool Changed = false;
2855 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2856 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2858 if (II->hasFnAttr(Attribute::UWTable)) {
2859 // Don't remove an `invoke' instruction if the ABI requires an entry into
2861 InvokeRequiresTableEntry = true;
2865 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2867 // Insert a call instruction before the invoke.
2868 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2870 Call->setCallingConv(II->getCallingConv());
2871 Call->setAttributes(II->getAttributes());
2872 Call->setDebugLoc(II->getDebugLoc());
2874 // Anything that used the value produced by the invoke instruction now uses
2875 // the value produced by the call instruction. Note that we do this even
2876 // for void functions and calls with no uses so that the callgraph edge is
2878 II->replaceAllUsesWith(Call);
2879 BB->removePredecessor(II->getParent());
2881 // Insert a branch to the normal destination right before the invoke.
2882 BranchInst::Create(II->getNormalDest(), II);
2884 // Finally, delete the invoke instruction!
2885 II->eraseFromParent();
2889 if (!InvokeRequiresTableEntry)
2890 // The landingpad is now unreachable. Zap it.
2891 BB->eraseFromParent();
2896 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2897 BasicBlock *BB = RI->getParent();
2898 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2900 // Find predecessors that end with branches.
2901 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2902 SmallVector<BranchInst*, 8> CondBranchPreds;
2903 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2904 BasicBlock *P = *PI;
2905 TerminatorInst *PTI = P->getTerminator();
2906 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2907 if (BI->isUnconditional())
2908 UncondBranchPreds.push_back(P);
2910 CondBranchPreds.push_back(BI);
2914 // If we found some, do the transformation!
2915 if (!UncondBranchPreds.empty() && DupRet) {
2916 while (!UncondBranchPreds.empty()) {
2917 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2918 DEBUG(dbgs() << "FOLDING: " << *BB
2919 << "INTO UNCOND BRANCH PRED: " << *Pred);
2920 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2923 // If we eliminated all predecessors of the block, delete the block now.
2924 if (pred_begin(BB) == pred_end(BB))
2925 // We know there are no successors, so just nuke the block.
2926 BB->eraseFromParent();
2931 // Check out all of the conditional branches going to this return
2932 // instruction. If any of them just select between returns, change the
2933 // branch itself into a select/return pair.
2934 while (!CondBranchPreds.empty()) {
2935 BranchInst *BI = CondBranchPreds.pop_back_val();
2937 // Check to see if the non-BB successor is also a return block.
2938 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2939 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2940 SimplifyCondBranchToTwoReturns(BI, Builder))
2946 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2947 BasicBlock *BB = UI->getParent();
2949 bool Changed = false;
2951 // If there are any instructions immediately before the unreachable that can
2952 // be removed, do so.
2953 while (UI != BB->begin()) {
2954 BasicBlock::iterator BBI = UI;
2956 // Do not delete instructions that can have side effects which might cause
2957 // the unreachable to not be reachable; specifically, calls and volatile
2958 // operations may have this effect.
2959 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2961 if (BBI->mayHaveSideEffects()) {
2962 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2963 if (SI->isVolatile())
2965 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2966 if (LI->isVolatile())
2968 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2969 if (RMWI->isVolatile())
2971 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2972 if (CXI->isVolatile())
2974 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2975 !isa<LandingPadInst>(BBI)) {
2978 // Note that deleting LandingPad's here is in fact okay, although it
2979 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2980 // all the predecessors of this block will be the unwind edges of Invokes,
2981 // and we can therefore guarantee this block will be erased.
2984 // Delete this instruction (any uses are guaranteed to be dead)
2985 if (!BBI->use_empty())
2986 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2987 BBI->eraseFromParent();
2991 // If the unreachable instruction is the first in the block, take a gander
2992 // at all of the predecessors of this instruction, and simplify them.
2993 if (&BB->front() != UI) return Changed;
2995 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2996 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2997 TerminatorInst *TI = Preds[i]->getTerminator();
2998 IRBuilder<> Builder(TI);
2999 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3000 if (BI->isUnconditional()) {
3001 if (BI->getSuccessor(0) == BB) {
3002 new UnreachableInst(TI->getContext(), TI);
3003 TI->eraseFromParent();
3007 if (BI->getSuccessor(0) == BB) {
3008 Builder.CreateBr(BI->getSuccessor(1));
3009 EraseTerminatorInstAndDCECond(BI);
3010 } else if (BI->getSuccessor(1) == BB) {
3011 Builder.CreateBr(BI->getSuccessor(0));
3012 EraseTerminatorInstAndDCECond(BI);
3016 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3017 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3019 if (i.getCaseSuccessor() == BB) {
3020 BB->removePredecessor(SI->getParent());
3025 // If the default value is unreachable, figure out the most popular
3026 // destination and make it the default.
3027 if (SI->getDefaultDest() == BB) {
3028 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3029 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3031 std::pair<unsigned, unsigned> &entry =
3032 Popularity[i.getCaseSuccessor()];
3033 if (entry.first == 0) {
3035 entry.second = i.getCaseIndex();
3041 // Find the most popular block.
3042 unsigned MaxPop = 0;
3043 unsigned MaxIndex = 0;
3044 BasicBlock *MaxBlock = nullptr;
3045 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3046 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3047 if (I->second.first > MaxPop ||
3048 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3049 MaxPop = I->second.first;
3050 MaxIndex = I->second.second;
3051 MaxBlock = I->first;
3055 // Make this the new default, allowing us to delete any explicit
3057 SI->setDefaultDest(MaxBlock);
3060 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3062 if (isa<PHINode>(MaxBlock->begin()))
3063 for (unsigned i = 0; i != MaxPop-1; ++i)
3064 MaxBlock->removePredecessor(SI->getParent());
3066 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3068 if (i.getCaseSuccessor() == MaxBlock) {
3074 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3075 if (II->getUnwindDest() == BB) {
3076 // Convert the invoke to a call instruction. This would be a good
3077 // place to note that the call does not throw though.
3078 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3079 II->removeFromParent(); // Take out of symbol table
3081 // Insert the call now...
3082 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3083 Builder.SetInsertPoint(BI);
3084 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3085 Args, II->getName());
3086 CI->setCallingConv(II->getCallingConv());
3087 CI->setAttributes(II->getAttributes());
3088 // If the invoke produced a value, the call does now instead.
3089 II->replaceAllUsesWith(CI);
3096 // If this block is now dead, remove it.
3097 if (pred_begin(BB) == pred_end(BB) &&
3098 BB != &BB->getParent()->getEntryBlock()) {
3099 // We know there are no successors, so just nuke the block.
3100 BB->eraseFromParent();
3107 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3108 /// integer range comparison into a sub, an icmp and a branch.
3109 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3110 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3112 // Make sure all cases point to the same destination and gather the values.
3113 SmallVector<ConstantInt *, 16> Cases;
3114 SwitchInst::CaseIt I = SI->case_begin();
3115 Cases.push_back(I.getCaseValue());
3116 SwitchInst::CaseIt PrevI = I++;
3117 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3118 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3120 Cases.push_back(I.getCaseValue());
3122 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3124 // Sort the case values, then check if they form a range we can transform.
3125 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3126 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3127 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3131 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3132 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3134 Value *Sub = SI->getCondition();
3135 if (!Offset->isNullValue())
3136 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3138 // If NumCases overflowed, then all possible values jump to the successor.
3139 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3140 Cmp = ConstantInt::getTrue(SI->getContext());
3142 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3143 BranchInst *NewBI = Builder.CreateCondBr(
3144 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3146 // Update weight for the newly-created conditional branch.
3147 SmallVector<uint64_t, 8> Weights;
3148 bool HasWeights = HasBranchWeights(SI);
3150 GetBranchWeights(SI, Weights);
3151 if (Weights.size() == 1 + SI->getNumCases()) {
3152 // Combine all weights for the cases to be the true weight of NewBI.
3153 // We assume that the sum of all weights for a Terminator can fit into 32
3155 uint32_t NewTrueWeight = 0;
3156 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3157 NewTrueWeight += (uint32_t)Weights[I];
3158 NewBI->setMetadata(LLVMContext::MD_prof,
3159 MDBuilder(SI->getContext()).
3160 createBranchWeights(NewTrueWeight,
3161 (uint32_t)Weights[0]));
3165 // Prune obsolete incoming values off the successor's PHI nodes.
3166 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3167 isa<PHINode>(BBI); ++BBI) {
3168 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3169 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3171 SI->eraseFromParent();
3176 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3177 /// and use it to remove dead cases.
3178 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3179 AssumptionTracker *AT) {
3180 Value *Cond = SI->getCondition();
3181 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3182 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3183 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3185 // Gather dead cases.
3186 SmallVector<ConstantInt*, 8> DeadCases;
3187 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3188 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3189 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3190 DeadCases.push_back(I.getCaseValue());
3191 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3192 << I.getCaseValue() << "' is dead.\n");
3196 SmallVector<uint64_t, 8> Weights;
3197 bool HasWeight = HasBranchWeights(SI);
3199 GetBranchWeights(SI, Weights);
3200 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3203 // Remove dead cases from the switch.
3204 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3205 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3206 assert(Case != SI->case_default() &&
3207 "Case was not found. Probably mistake in DeadCases forming.");
3209 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3213 // Prune unused values from PHI nodes.
3214 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3215 SI->removeCase(Case);
3217 if (HasWeight && Weights.size() >= 2) {
3218 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3219 SI->setMetadata(LLVMContext::MD_prof,
3220 MDBuilder(SI->getParent()->getContext()).
3221 createBranchWeights(MDWeights));
3224 return !DeadCases.empty();
3227 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3228 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3229 /// by an unconditional branch), look at the phi node for BB in the successor
3230 /// block and see if the incoming value is equal to CaseValue. If so, return
3231 /// the phi node, and set PhiIndex to BB's index in the phi node.
3232 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3235 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3236 return nullptr; // BB must be empty to be a candidate for simplification.
3237 if (!BB->getSinglePredecessor())
3238 return nullptr; // BB must be dominated by the switch.
3240 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3241 if (!Branch || !Branch->isUnconditional())
3242 return nullptr; // Terminator must be unconditional branch.
3244 BasicBlock *Succ = Branch->getSuccessor(0);
3246 BasicBlock::iterator I = Succ->begin();
3247 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3248 int Idx = PHI->getBasicBlockIndex(BB);
3249 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3251 Value *InValue = PHI->getIncomingValue(Idx);
3252 if (InValue != CaseValue) continue;
3261 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3262 /// instruction to a phi node dominated by the switch, if that would mean that
3263 /// some of the destination blocks of the switch can be folded away.
3264 /// Returns true if a change is made.
3265 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3266 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3267 ForwardingNodesMap ForwardingNodes;
3269 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3270 ConstantInt *CaseValue = I.getCaseValue();
3271 BasicBlock *CaseDest = I.getCaseSuccessor();
3274 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3278 ForwardingNodes[PHI].push_back(PhiIndex);
3281 bool Changed = false;
3283 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3284 E = ForwardingNodes.end(); I != E; ++I) {
3285 PHINode *Phi = I->first;
3286 SmallVectorImpl<int> &Indexes = I->second;
3288 if (Indexes.size() < 2) continue;
3290 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3291 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3298 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3299 /// initializing an array of constants like C.
3300 static bool ValidLookupTableConstant(Constant *C) {
3301 if (C->isThreadDependent())
3303 if (C->isDLLImportDependent())
3306 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3307 return CE->isGEPWithNoNotionalOverIndexing();
3309 return isa<ConstantFP>(C) ||
3310 isa<ConstantInt>(C) ||
3311 isa<ConstantPointerNull>(C) ||
3312 isa<GlobalValue>(C) ||
3316 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3317 /// its constant value in ConstantPool, returning 0 if it's not there.
3318 static Constant *LookupConstant(Value *V,
3319 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3320 if (Constant *C = dyn_cast<Constant>(V))
3322 return ConstantPool.lookup(V);
3325 /// ConstantFold - Try to fold instruction I into a constant. This works for
3326 /// simple instructions such as binary operations where both operands are
3327 /// constant or can be replaced by constants from the ConstantPool. Returns the
3328 /// resulting constant on success, 0 otherwise.
3330 ConstantFold(Instruction *I,
3331 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3332 const DataLayout *DL) {
3333 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3334 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3337 if (A->isAllOnesValue())
3338 return LookupConstant(Select->getTrueValue(), ConstantPool);
3339 if (A->isNullValue())
3340 return LookupConstant(Select->getFalseValue(), ConstantPool);
3344 SmallVector<Constant *, 4> COps;
3345 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3346 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3352 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3353 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3356 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3359 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3360 /// at the common destination basic block, *CommonDest, for one of the case
3361 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3362 /// case), of a switch instruction SI.
3364 GetCaseResults(SwitchInst *SI,
3365 ConstantInt *CaseVal,
3366 BasicBlock *CaseDest,
3367 BasicBlock **CommonDest,
3368 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3369 const DataLayout *DL) {
3370 // The block from which we enter the common destination.
3371 BasicBlock *Pred = SI->getParent();
3373 // If CaseDest is empty except for some side-effect free instructions through
3374 // which we can constant-propagate the CaseVal, continue to its successor.
3375 SmallDenseMap<Value*, Constant*> ConstantPool;
3376 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3377 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3379 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3380 // If the terminator is a simple branch, continue to the next block.
3381 if (T->getNumSuccessors() != 1)
3384 CaseDest = T->getSuccessor(0);
3385 } else if (isa<DbgInfoIntrinsic>(I)) {
3386 // Skip debug intrinsic.
3388 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3389 // Instruction is side-effect free and constant.
3390 ConstantPool.insert(std::make_pair(I, C));
3396 // If we did not have a CommonDest before, use the current one.
3398 *CommonDest = CaseDest;
3399 // If the destination isn't the common one, abort.
3400 if (CaseDest != *CommonDest)
3403 // Get the values for this case from phi nodes in the destination block.
3404 BasicBlock::iterator I = (*CommonDest)->begin();
3405 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3406 int Idx = PHI->getBasicBlockIndex(Pred);
3410 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3415 // Note: If the constant comes from constant-propagating the case value
3416 // through the CaseDest basic block, it will be safe to remove the
3417 // instructions in that block. They cannot be used (except in the phi nodes
3418 // we visit) outside CaseDest, because that block does not dominate its
3419 // successor. If it did, we would not be in this phi node.
3421 // Be conservative about which kinds of constants we support.
3422 if (!ValidLookupTableConstant(ConstVal))
3425 Res.push_back(std::make_pair(PHI, ConstVal));
3428 return Res.size() > 0;
3432 /// SwitchLookupTable - This class represents a lookup table that can be used
3433 /// to replace a switch.
3434 class SwitchLookupTable {
3436 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3437 /// with the contents of Values, using DefaultValue to fill any holes in the
3439 SwitchLookupTable(Module &M,
3441 ConstantInt *Offset,
3442 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3443 Constant *DefaultValue,
3444 const DataLayout *DL);
3446 /// BuildLookup - Build instructions with Builder to retrieve the value at
3447 /// the position given by Index in the lookup table.
3448 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3450 /// WouldFitInRegister - Return true if a table with TableSize elements of
3451 /// type ElementType would fit in a target-legal register.
3452 static bool WouldFitInRegister(const DataLayout *DL,
3454 const Type *ElementType);
3457 // Depending on the contents of the table, it can be represented in
3460 // For tables where each element contains the same value, we just have to
3461 // store that single value and return it for each lookup.
3464 // For small tables with integer elements, we can pack them into a bitmap
3465 // that fits into a target-legal register. Values are retrieved by
3466 // shift and mask operations.
3469 // The table is stored as an array of values. Values are retrieved by load
3470 // instructions from the table.
3474 // For SingleValueKind, this is the single value.
3475 Constant *SingleValue;
3477 // For BitMapKind, this is the bitmap.
3478 ConstantInt *BitMap;
3479 IntegerType *BitMapElementTy;
3481 // For ArrayKind, this is the array.
3482 GlobalVariable *Array;
3486 SwitchLookupTable::SwitchLookupTable(Module &M,
3488 ConstantInt *Offset,
3489 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3490 Constant *DefaultValue,
3491 const DataLayout *DL)
3492 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3494 assert(Values.size() && "Can't build lookup table without values!");
3495 assert(TableSize >= Values.size() && "Can't fit values in table!");
3497 // If all values in the table are equal, this is that value.
3498 SingleValue = Values.begin()->second;
3500 Type *ValueType = Values.begin()->second->getType();
3502 // Build up the table contents.
3503 SmallVector<Constant*, 64> TableContents(TableSize);
3504 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3505 ConstantInt *CaseVal = Values[I].first;
3506 Constant *CaseRes = Values[I].second;
3507 assert(CaseRes->getType() == ValueType);
3509 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3511 TableContents[Idx] = CaseRes;
3513 if (CaseRes != SingleValue)
3514 SingleValue = nullptr;
3517 // Fill in any holes in the table with the default result.
3518 if (Values.size() < TableSize) {
3519 assert(DefaultValue &&
3520 "Need a default value to fill the lookup table holes.");
3521 assert(DefaultValue->getType() == ValueType);
3522 for (uint64_t I = 0; I < TableSize; ++I) {
3523 if (!TableContents[I])
3524 TableContents[I] = DefaultValue;
3527 if (DefaultValue != SingleValue)
3528 SingleValue = nullptr;
3531 // If each element in the table contains the same value, we only need to store
3532 // that single value.
3534 Kind = SingleValueKind;
3538 // If the type is integer and the table fits in a register, build a bitmap.
3539 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3540 IntegerType *IT = cast<IntegerType>(ValueType);
3541 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3542 for (uint64_t I = TableSize; I > 0; --I) {
3543 TableInt <<= IT->getBitWidth();
3544 // Insert values into the bitmap. Undef values are set to zero.
3545 if (!isa<UndefValue>(TableContents[I - 1])) {
3546 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3547 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3550 BitMap = ConstantInt::get(M.getContext(), TableInt);
3551 BitMapElementTy = IT;
3557 // Store the table in an array.
3558 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3559 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3561 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3562 GlobalVariable::PrivateLinkage,
3565 Array->setUnnamedAddr(true);
3569 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3571 case SingleValueKind:
3574 // Type of the bitmap (e.g. i59).
3575 IntegerType *MapTy = BitMap->getType();
3577 // Cast Index to the same type as the bitmap.
3578 // Note: The Index is <= the number of elements in the table, so
3579 // truncating it to the width of the bitmask is safe.
3580 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3582 // Multiply the shift amount by the element width.
3583 ShiftAmt = Builder.CreateMul(ShiftAmt,
3584 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3588 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3589 "switch.downshift");
3591 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3595 // Make sure the table index will not overflow when treated as signed.
3596 IntegerType *IT = cast<IntegerType>(Index->getType());
3597 uint64_t TableSize = Array->getInitializer()->getType()
3598 ->getArrayNumElements();
3599 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3600 Index = Builder.CreateZExt(Index,
3601 IntegerType::get(IT->getContext(),
3602 IT->getBitWidth() + 1),
3603 "switch.tableidx.zext");
3605 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3606 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3608 return Builder.CreateLoad(GEP, "switch.load");
3611 llvm_unreachable("Unknown lookup table kind!");
3614 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3616 const Type *ElementType) {
3619 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3622 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3623 // are <= 15, we could try to narrow the type.
3625 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3626 if (TableSize >= UINT_MAX/IT->getBitWidth())
3628 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3631 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3632 /// for this switch, based on the number of cases, size of the table and the
3633 /// types of the results.
3634 static bool ShouldBuildLookupTable(SwitchInst *SI,
3636 const TargetTransformInfo &TTI,
3637 const DataLayout *DL,
3638 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3639 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3640 return false; // TableSize overflowed, or mul below might overflow.
3642 bool AllTablesFitInRegister = true;
3643 bool HasIllegalType = false;
3644 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3645 E = ResultTypes.end(); I != E; ++I) {
3646 Type *Ty = I->second;
3648 // Saturate this flag to true.
3649 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3651 // Saturate this flag to false.
3652 AllTablesFitInRegister = AllTablesFitInRegister &&
3653 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3655 // If both flags saturate, we're done. NOTE: This *only* works with
3656 // saturating flags, and all flags have to saturate first due to the
3657 // non-deterministic behavior of iterating over a dense map.
3658 if (HasIllegalType && !AllTablesFitInRegister)
3662 // If each table would fit in a register, we should build it anyway.
3663 if (AllTablesFitInRegister)
3666 // Don't build a table that doesn't fit in-register if it has illegal types.
3670 // The table density should be at least 40%. This is the same criterion as for
3671 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3672 // FIXME: Find the best cut-off.
3673 return SI->getNumCases() * 10 >= TableSize * 4;
3676 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3677 /// phi nodes in a common successor block with different constant values,
3678 /// replace the switch with lookup tables.
3679 static bool SwitchToLookupTable(SwitchInst *SI,
3680 IRBuilder<> &Builder,
3681 const TargetTransformInfo &TTI,
3682 const DataLayout* DL) {
3683 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3685 // Only build lookup table when we have a target that supports it.
3686 if (!TTI.shouldBuildLookupTables())
3689 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3690 // split off a dense part and build a lookup table for that.
3692 // FIXME: This creates arrays of GEPs to constant strings, which means each
3693 // GEP needs a runtime relocation in PIC code. We should just build one big
3694 // string and lookup indices into that.
3696 // Ignore switches with less than three cases. Lookup tables will not make them
3697 // faster, so we don't analyze them.
3698 if (SI->getNumCases() < 3)
3701 // Figure out the corresponding result for each case value and phi node in the
3702 // common destination, as well as the the min and max case values.
3703 assert(SI->case_begin() != SI->case_end());
3704 SwitchInst::CaseIt CI = SI->case_begin();
3705 ConstantInt *MinCaseVal = CI.getCaseValue();
3706 ConstantInt *MaxCaseVal = CI.getCaseValue();
3708 BasicBlock *CommonDest = nullptr;
3709 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3710 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3711 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3712 SmallDenseMap<PHINode*, Type*> ResultTypes;
3713 SmallVector<PHINode*, 4> PHIs;
3715 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3716 ConstantInt *CaseVal = CI.getCaseValue();
3717 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3718 MinCaseVal = CaseVal;
3719 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3720 MaxCaseVal = CaseVal;
3722 // Resulting value at phi nodes for this case value.
3723 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3725 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3729 // Append the result from this case to the list for each phi.
3730 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3731 if (!ResultLists.count(I->first))
3732 PHIs.push_back(I->first);
3733 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3737 // Keep track of the result types.
3738 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3739 PHINode *PHI = PHIs[I];
3740 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3743 uint64_t NumResults = ResultLists[PHIs[0]].size();
3744 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3745 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3746 bool TableHasHoles = (NumResults < TableSize);
3748 // If the table has holes, we need a constant result for the default case
3749 // or a bitmask that fits in a register.
3750 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3751 bool HasDefaultResults = false;
3752 if (TableHasHoles) {
3753 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3754 &CommonDest, DefaultResultsList, DL);
3756 bool NeedMask = (TableHasHoles && !HasDefaultResults);
3758 // As an extra penalty for the validity test we require more cases.
3759 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
3761 if (!(DL && DL->fitsInLegalInteger(TableSize)))
3765 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3766 PHINode *PHI = DefaultResultsList[I].first;
3767 Constant *Result = DefaultResultsList[I].second;
3768 DefaultResults[PHI] = Result;
3771 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
3774 // Create the BB that does the lookups.
3775 Module &Mod = *CommonDest->getParent()->getParent();
3776 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3778 CommonDest->getParent(),
3781 // Compute the table index value.
3782 Builder.SetInsertPoint(SI);
3783 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3786 // Compute the maximum table size representable by the integer type we are
3788 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
3789 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
3790 assert(MaxTableSize >= TableSize &&
3791 "It is impossible for a switch to have more entries than the max "
3792 "representable value of its input integer type's size.");
3794 // If we have a fully covered lookup table, unconditionally branch to the
3795 // lookup table BB. Otherwise, check if the condition value is within the case
3796 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3798 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3799 if (GeneratingCoveredLookupTable) {
3800 Builder.CreateBr(LookupBB);
3801 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
3802 // do not delete PHINodes here.
3803 SI->getDefaultDest()->removePredecessor(SI->getParent(),
3804 true/*DontDeleteUselessPHIs*/);
3806 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3807 MinCaseVal->getType(), TableSize));
3808 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3811 // Populate the BB that does the lookups.
3812 Builder.SetInsertPoint(LookupBB);
3815 // Before doing the lookup we do the hole check.
3816 // The LookupBB is therefore re-purposed to do the hole check
3817 // and we create a new LookupBB.
3818 BasicBlock *MaskBB = LookupBB;
3819 MaskBB->setName("switch.hole_check");
3820 LookupBB = BasicBlock::Create(Mod.getContext(),
3822 CommonDest->getParent(),
3825 // Build bitmask; fill in a 1 bit for every case.
3826 APInt MaskInt(TableSize, 0);
3827 APInt One(TableSize, 1);
3828 const ResultListTy &ResultList = ResultLists[PHIs[0]];
3829 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3830 uint64_t Idx = (ResultList[I].first->getValue() -
3831 MinCaseVal->getValue()).getLimitedValue();
3832 MaskInt |= One << Idx;
3834 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3836 // Get the TableIndex'th bit of the bitmask.
3837 // If this bit is 0 (meaning hole) jump to the default destination,
3838 // else continue with table lookup.
3839 IntegerType *MapTy = TableMask->getType();
3840 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3841 "switch.maskindex");
3842 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3844 Value *LoBit = Builder.CreateTrunc(Shifted,
3845 Type::getInt1Ty(Mod.getContext()),
3847 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3849 Builder.SetInsertPoint(LookupBB);
3850 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3853 bool ReturnedEarly = false;
3854 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3855 PHINode *PHI = PHIs[I];
3857 // If using a bitmask, use any value to fill the lookup table holes.
3858 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
3859 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3862 Value *Result = Table.BuildLookup(TableIndex, Builder);
3864 // If the result is used to return immediately from the function, we want to
3865 // do that right here.
3866 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3867 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
3868 Builder.CreateRet(Result);
3869 ReturnedEarly = true;
3873 PHI->addIncoming(Result, LookupBB);
3877 Builder.CreateBr(CommonDest);
3879 // Remove the switch.
3880 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3881 BasicBlock *Succ = SI->getSuccessor(i);
3883 if (Succ == SI->getDefaultDest())
3885 Succ->removePredecessor(SI->getParent());
3887 SI->eraseFromParent();
3891 ++NumLookupTablesHoles;
3895 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3896 BasicBlock *BB = SI->getParent();
3898 if (isValueEqualityComparison(SI)) {
3899 // If we only have one predecessor, and if it is a branch on this value,
3900 // see if that predecessor totally determines the outcome of this switch.
3901 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3902 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3903 return SimplifyCFG(BB, TTI, DL, AT) | true;
3905 Value *Cond = SI->getCondition();
3906 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3907 if (SimplifySwitchOnSelect(SI, Select))
3908 return SimplifyCFG(BB, TTI, DL, AT) | true;
3910 // If the block only contains the switch, see if we can fold the block
3911 // away into any preds.
3912 BasicBlock::iterator BBI = BB->begin();
3913 // Ignore dbg intrinsics.
3914 while (isa<DbgInfoIntrinsic>(BBI))
3917 if (FoldValueComparisonIntoPredecessors(SI, Builder))
3918 return SimplifyCFG(BB, TTI, DL, AT) | true;
3921 // Try to transform the switch into an icmp and a branch.
3922 if (TurnSwitchRangeIntoICmp(SI, Builder))
3923 return SimplifyCFG(BB, TTI, DL, AT) | true;
3925 // Remove unreachable cases.
3926 if (EliminateDeadSwitchCases(SI, DL, AT))
3927 return SimplifyCFG(BB, TTI, DL, AT) | true;
3929 if (ForwardSwitchConditionToPHI(SI))
3930 return SimplifyCFG(BB, TTI, DL, AT) | true;
3932 if (SwitchToLookupTable(SI, Builder, TTI, DL))
3933 return SimplifyCFG(BB, TTI, DL, AT) | true;
3938 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3939 BasicBlock *BB = IBI->getParent();
3940 bool Changed = false;
3942 // Eliminate redundant destinations.
3943 SmallPtrSet<Value *, 8> Succs;
3944 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3945 BasicBlock *Dest = IBI->getDestination(i);
3946 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3947 Dest->removePredecessor(BB);
3948 IBI->removeDestination(i);
3954 if (IBI->getNumDestinations() == 0) {
3955 // If the indirectbr has no successors, change it to unreachable.
3956 new UnreachableInst(IBI->getContext(), IBI);
3957 EraseTerminatorInstAndDCECond(IBI);
3961 if (IBI->getNumDestinations() == 1) {
3962 // If the indirectbr has one successor, change it to a direct branch.
3963 BranchInst::Create(IBI->getDestination(0), IBI);
3964 EraseTerminatorInstAndDCECond(IBI);
3968 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3969 if (SimplifyIndirectBrOnSelect(IBI, SI))
3970 return SimplifyCFG(BB, TTI, DL, AT) | true;
3975 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
3976 BasicBlock *BB = BI->getParent();
3978 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3981 // If the Terminator is the only non-phi instruction, simplify the block.
3982 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
3983 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3984 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3987 // If the only instruction in the block is a seteq/setne comparison
3988 // against a constant, try to simplify the block.
3989 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3990 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3991 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3993 if (I->isTerminator() &&
3994 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL, AT))
3998 // If this basic block is ONLY a compare and a branch, and if a predecessor
3999 // branches to us and our successor, fold the comparison into the
4000 // predecessor and use logical operations to update the incoming value
4001 // for PHI nodes in common successor.
4002 if (FoldBranchToCommonDest(BI, DL))
4003 return SimplifyCFG(BB, TTI, DL, AT) | true;
4008 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4009 BasicBlock *BB = BI->getParent();
4011 // Conditional branch
4012 if (isValueEqualityComparison(BI)) {
4013 // If we only have one predecessor, and if it is a branch on this value,
4014 // see if that predecessor totally determines the outcome of this
4016 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4017 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4018 return SimplifyCFG(BB, TTI, DL, AT) | true;
4020 // This block must be empty, except for the setcond inst, if it exists.
4021 // Ignore dbg intrinsics.
4022 BasicBlock::iterator I = BB->begin();
4023 // Ignore dbg intrinsics.
4024 while (isa<DbgInfoIntrinsic>(I))
4027 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4028 return SimplifyCFG(BB, TTI, DL, AT) | true;
4029 } else if (&*I == cast<Instruction>(BI->getCondition())){
4031 // Ignore dbg intrinsics.
4032 while (isa<DbgInfoIntrinsic>(I))
4034 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4035 return SimplifyCFG(BB, TTI, DL, AT) | true;
4039 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4040 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4043 // If this basic block is ONLY a compare and a branch, and if a predecessor
4044 // branches to us and one of our successors, fold the comparison into the
4045 // predecessor and use logical operations to pick the right destination.
4046 if (FoldBranchToCommonDest(BI, DL))
4047 return SimplifyCFG(BB, TTI, DL, AT) | true;
4049 // We have a conditional branch to two blocks that are only reachable
4050 // from BI. We know that the condbr dominates the two blocks, so see if
4051 // there is any identical code in the "then" and "else" blocks. If so, we
4052 // can hoist it up to the branching block.
4053 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4054 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4055 if (HoistThenElseCodeToIf(BI, DL))
4056 return SimplifyCFG(BB, TTI, DL, AT) | true;
4058 // If Successor #1 has multiple preds, we may be able to conditionally
4059 // execute Successor #0 if it branches to Successor #1.
4060 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4061 if (Succ0TI->getNumSuccessors() == 1 &&
4062 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4063 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4064 return SimplifyCFG(BB, TTI, DL, AT) | true;
4066 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4067 // If Successor #0 has multiple preds, we may be able to conditionally
4068 // execute Successor #1 if it branches to Successor #0.
4069 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4070 if (Succ1TI->getNumSuccessors() == 1 &&
4071 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4072 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4073 return SimplifyCFG(BB, TTI, DL, AT) | true;
4076 // If this is a branch on a phi node in the current block, thread control
4077 // through this block if any PHI node entries are constants.
4078 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4079 if (PN->getParent() == BI->getParent())
4080 if (FoldCondBranchOnPHI(BI, DL))
4081 return SimplifyCFG(BB, TTI, DL, AT) | true;
4083 // Scan predecessor blocks for conditional branches.
4084 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4085 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4086 if (PBI != BI && PBI->isConditional())
4087 if (SimplifyCondBranchToCondBranch(PBI, BI))
4088 return SimplifyCFG(BB, TTI, DL, AT) | true;
4093 /// Check if passing a value to an instruction will cause undefined behavior.
4094 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4095 Constant *C = dyn_cast<Constant>(V);
4102 if (C->isNullValue()) {
4103 // Only look at the first use, avoid hurting compile time with long uselists
4104 User *Use = *I->user_begin();
4106 // Now make sure that there are no instructions in between that can alter
4107 // control flow (eg. calls)
4108 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4109 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4112 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4113 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4114 if (GEP->getPointerOperand() == I)
4115 return passingValueIsAlwaysUndefined(V, GEP);
4117 // Look through bitcasts.
4118 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4119 return passingValueIsAlwaysUndefined(V, BC);
4121 // Load from null is undefined.
4122 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4123 if (!LI->isVolatile())
4124 return LI->getPointerAddressSpace() == 0;
4126 // Store to null is undefined.
4127 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4128 if (!SI->isVolatile())
4129 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4134 /// If BB has an incoming value that will always trigger undefined behavior
4135 /// (eg. null pointer dereference), remove the branch leading here.
4136 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4137 for (BasicBlock::iterator i = BB->begin();
4138 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4139 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4140 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4141 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4142 IRBuilder<> Builder(T);
4143 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4144 BB->removePredecessor(PHI->getIncomingBlock(i));
4145 // Turn uncoditional branches into unreachables and remove the dead
4146 // destination from conditional branches.
4147 if (BI->isUnconditional())
4148 Builder.CreateUnreachable();
4150 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4151 BI->getSuccessor(0));
4152 BI->eraseFromParent();
4155 // TODO: SwitchInst.
4161 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4162 bool Changed = false;
4164 assert(BB && BB->getParent() && "Block not embedded in function!");
4165 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4167 // Remove basic blocks that have no predecessors (except the entry block)...
4168 // or that just have themself as a predecessor. These are unreachable.
4169 if ((pred_begin(BB) == pred_end(BB) &&
4170 BB != &BB->getParent()->getEntryBlock()) ||
4171 BB->getSinglePredecessor() == BB) {
4172 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4173 DeleteDeadBlock(BB);
4177 // Check to see if we can constant propagate this terminator instruction
4179 Changed |= ConstantFoldTerminator(BB, true);
4181 // Check for and eliminate duplicate PHI nodes in this block.
4182 Changed |= EliminateDuplicatePHINodes(BB);
4184 // Check for and remove branches that will always cause undefined behavior.
4185 Changed |= removeUndefIntroducingPredecessor(BB);
4187 // Merge basic blocks into their predecessor if there is only one distinct
4188 // pred, and if there is only one distinct successor of the predecessor, and
4189 // if there are no PHI nodes.
4191 if (MergeBlockIntoPredecessor(BB))
4194 IRBuilder<> Builder(BB);
4196 // If there is a trivial two-entry PHI node in this basic block, and we can
4197 // eliminate it, do so now.
4198 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4199 if (PN->getNumIncomingValues() == 2)
4200 Changed |= FoldTwoEntryPHINode(PN, DL);
4202 Builder.SetInsertPoint(BB->getTerminator());
4203 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4204 if (BI->isUnconditional()) {
4205 if (SimplifyUncondBranch(BI, Builder)) return true;
4207 if (SimplifyCondBranch(BI, Builder)) return true;
4209 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4210 if (SimplifyReturn(RI, Builder)) return true;
4211 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4212 if (SimplifyResume(RI, Builder)) return true;
4213 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4214 if (SimplifySwitch(SI, Builder)) return true;
4215 } else if (UnreachableInst *UI =
4216 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4217 if (SimplifyUnreachable(UI)) return true;
4218 } else if (IndirectBrInst *IBI =
4219 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4220 if (SimplifyIndirectBr(IBI)) return true;
4226 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4227 /// example, it adjusts branches to branches to eliminate the extra hop, it
4228 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4229 /// of the CFG. It returns true if a modification was made.
4231 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4232 const DataLayout *DL, AssumptionTracker *AT) {
4233 return SimplifyCFGOpt(TTI, DL, AT).run(BB);