1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
52 using namespace PatternMatch;
54 #define DEBUG_TYPE "simplifycfg"
56 static cl::opt<unsigned>
57 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
61 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
65 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
68 static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
72 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
73 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
74 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
75 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
76 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
79 /// ValueEqualityComparisonCase - Represents a case of a switch.
80 struct ValueEqualityComparisonCase {
84 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
85 : Value(Value), Dest(Dest) {}
87 bool operator<(ValueEqualityComparisonCase RHS) const {
88 // Comparing pointers is ok as we only rely on the order for uniquing.
89 return Value < RHS.Value;
92 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
95 class SimplifyCFGOpt {
96 const TargetTransformInfo &TTI;
97 unsigned BonusInstThreshold;
98 const DataLayout *const DL;
99 AssumptionTracker *AT;
100 Value *isValueEqualityComparison(TerminatorInst *TI);
101 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
102 std::vector<ValueEqualityComparisonCase> &Cases);
103 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
105 IRBuilder<> &Builder);
106 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
107 IRBuilder<> &Builder);
109 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
110 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
111 bool SimplifyUnreachable(UnreachableInst *UI);
112 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
113 bool SimplifyIndirectBr(IndirectBrInst *IBI);
114 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
115 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
118 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
119 const DataLayout *DL, AssumptionTracker *AT)
120 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
121 bool run(BasicBlock *BB);
125 /// SafeToMergeTerminators - Return true if it is safe to merge these two
126 /// terminator instructions together.
128 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
129 if (SI1 == SI2) return false; // Can't merge with self!
131 // It is not safe to merge these two switch instructions if they have a common
132 // successor, and if that successor has a PHI node, and if *that* PHI node has
133 // conflicting incoming values from the two switch blocks.
134 BasicBlock *SI1BB = SI1->getParent();
135 BasicBlock *SI2BB = SI2->getParent();
136 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
138 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
139 if (SI1Succs.count(*I))
140 for (BasicBlock::iterator BBI = (*I)->begin();
141 isa<PHINode>(BBI); ++BBI) {
142 PHINode *PN = cast<PHINode>(BBI);
143 if (PN->getIncomingValueForBlock(SI1BB) !=
144 PN->getIncomingValueForBlock(SI2BB))
151 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
152 /// to merge these two terminator instructions together, where SI1 is an
153 /// unconditional branch. PhiNodes will store all PHI nodes in common
156 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
159 SmallVectorImpl<PHINode*> &PhiNodes) {
160 if (SI1 == SI2) return false; // Can't merge with self!
161 assert(SI1->isUnconditional() && SI2->isConditional());
163 // We fold the unconditional branch if we can easily update all PHI nodes in
164 // common successors:
165 // 1> We have a constant incoming value for the conditional branch;
166 // 2> We have "Cond" as the incoming value for the unconditional branch;
167 // 3> SI2->getCondition() and Cond have same operands.
168 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
169 if (!Ci2) return false;
170 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
171 Cond->getOperand(1) == Ci2->getOperand(1)) &&
172 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
173 Cond->getOperand(1) == Ci2->getOperand(0)))
176 BasicBlock *SI1BB = SI1->getParent();
177 BasicBlock *SI2BB = SI2->getParent();
178 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
179 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
180 if (SI1Succs.count(*I))
181 for (BasicBlock::iterator BBI = (*I)->begin();
182 isa<PHINode>(BBI); ++BBI) {
183 PHINode *PN = cast<PHINode>(BBI);
184 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
185 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
187 PhiNodes.push_back(PN);
192 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
193 /// now be entries in it from the 'NewPred' block. The values that will be
194 /// flowing into the PHI nodes will be the same as those coming in from
195 /// ExistPred, an existing predecessor of Succ.
196 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
197 BasicBlock *ExistPred) {
198 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
201 for (BasicBlock::iterator I = Succ->begin();
202 (PN = dyn_cast<PHINode>(I)); ++I)
203 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
206 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
207 /// given instruction, which is assumed to be safe to speculate. 1 means
208 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
209 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
210 assert(isSafeToSpeculativelyExecute(I, DL) &&
211 "Instruction is not safe to speculatively execute!");
212 switch (Operator::getOpcode(I)) {
214 // In doubt, be conservative.
216 case Instruction::GetElementPtr:
217 // GEPs are cheap if all indices are constant.
218 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
221 case Instruction::ExtractValue:
222 case Instruction::Load:
223 case Instruction::Add:
224 case Instruction::Sub:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor:
228 case Instruction::Shl:
229 case Instruction::LShr:
230 case Instruction::AShr:
231 case Instruction::ICmp:
232 case Instruction::Trunc:
233 case Instruction::ZExt:
234 case Instruction::SExt:
235 case Instruction::BitCast:
236 case Instruction::ExtractElement:
237 case Instruction::InsertElement:
238 return 1; // These are all cheap.
240 case Instruction::Call:
241 case Instruction::Select:
246 /// DominatesMergePoint - If we have a merge point of an "if condition" as
247 /// accepted above, return true if the specified value dominates the block. We
248 /// don't handle the true generality of domination here, just a special case
249 /// which works well enough for us.
251 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
252 /// see if V (which must be an instruction) and its recursive operands
253 /// that do not dominate BB have a combined cost lower than CostRemaining and
254 /// are non-trapping. If both are true, the instruction is inserted into the
255 /// set and true is returned.
257 /// The cost for most non-trapping instructions is defined as 1 except for
258 /// Select whose cost is 2.
260 /// After this function returns, CostRemaining is decreased by the cost of
261 /// V plus its non-dominating operands. If that cost is greater than
262 /// CostRemaining, false is returned and CostRemaining is undefined.
263 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
264 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
265 unsigned &CostRemaining,
266 const DataLayout *DL) {
267 Instruction *I = dyn_cast<Instruction>(V);
269 // Non-instructions all dominate instructions, but not all constantexprs
270 // can be executed unconditionally.
271 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
276 BasicBlock *PBB = I->getParent();
278 // We don't want to allow weird loops that might have the "if condition" in
279 // the bottom of this block.
280 if (PBB == BB) return false;
282 // If this instruction is defined in a block that contains an unconditional
283 // branch to BB, then it must be in the 'conditional' part of the "if
284 // statement". If not, it definitely dominates the region.
285 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
286 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
289 // If we aren't allowing aggressive promotion anymore, then don't consider
290 // instructions in the 'if region'.
291 if (!AggressiveInsts) return false;
293 // If we have seen this instruction before, don't count it again.
294 if (AggressiveInsts->count(I)) return true;
296 // Okay, it looks like the instruction IS in the "condition". Check to
297 // see if it's a cheap instruction to unconditionally compute, and if it
298 // only uses stuff defined outside of the condition. If so, hoist it out.
299 if (!isSafeToSpeculativelyExecute(I, DL))
302 unsigned Cost = ComputeSpeculationCost(I, DL);
304 if (Cost > CostRemaining)
307 CostRemaining -= Cost;
309 // Okay, we can only really hoist these out if their operands do
310 // not take us over the cost threshold.
311 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
312 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
314 // Okay, it's safe to do this! Remember this instruction.
315 AggressiveInsts->insert(I);
319 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
320 /// and PointerNullValue. Return NULL if value is not a constant int.
321 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
322 // Normal constant int.
323 ConstantInt *CI = dyn_cast<ConstantInt>(V);
324 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
327 // This is some kind of pointer constant. Turn it into a pointer-sized
328 // ConstantInt if possible.
329 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
331 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
332 if (isa<ConstantPointerNull>(V))
333 return ConstantInt::get(PtrTy, 0);
335 // IntToPtr const int.
336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
337 if (CE->getOpcode() == Instruction::IntToPtr)
338 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
339 // The constant is very likely to have the right type already.
340 if (CI->getType() == PtrTy)
343 return cast<ConstantInt>
344 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
349 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
350 /// collection of icmp eq/ne instructions that compare a value against a
351 /// constant, return the value being compared, and stick the constant into the
354 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
355 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
356 Instruction *I = dyn_cast<Instruction>(V);
357 if (!I) return nullptr;
359 // If this is an icmp against a constant, handle this as one of the cases.
360 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
361 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
365 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
366 // (x & ~2^x) == y --> x == y || x == y|2^x
367 // This undoes a transformation done by instcombine to fuse 2 compares.
368 if (match(ICI->getOperand(0),
369 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
370 APInt Not = ~RHSC->getValue();
371 if (Not.isPowerOf2()) {
374 ConstantInt::get(C->getContext(), C->getValue() | Not));
382 return I->getOperand(0);
385 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
388 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
390 // Shift the range if the compare is fed by an add. This is the range
391 // compare idiom as emitted by instcombine.
393 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
395 Span = Span.subtract(RHSC->getValue());
397 // If this is an and/!= check then we want to optimize "x ugt 2" into
400 Span = Span.inverse();
402 // If there are a ton of values, we don't want to make a ginormous switch.
403 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
406 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
407 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
409 return hasAdd ? RHSVal : I->getOperand(0);
414 // Otherwise, we can only handle an | or &, depending on isEQ.
415 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
418 unsigned NumValsBeforeLHS = Vals.size();
419 unsigned UsedICmpsBeforeLHS = UsedICmps;
420 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
422 unsigned NumVals = Vals.size();
423 unsigned UsedICmpsBeforeRHS = UsedICmps;
424 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
428 Vals.resize(NumVals);
429 UsedICmps = UsedICmpsBeforeRHS;
432 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
433 // set it and return success.
434 if (Extra == nullptr || Extra == I->getOperand(1)) {
435 Extra = I->getOperand(1);
439 Vals.resize(NumValsBeforeLHS);
440 UsedICmps = UsedICmpsBeforeLHS;
444 // If the LHS can't be folded in, but Extra is available and RHS can, try to
446 if (Extra == nullptr || Extra == I->getOperand(0)) {
447 Value *OldExtra = Extra;
448 Extra = I->getOperand(0);
449 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
452 assert(Vals.size() == NumValsBeforeLHS);
459 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
460 Instruction *Cond = nullptr;
461 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
462 Cond = dyn_cast<Instruction>(SI->getCondition());
463 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
464 if (BI->isConditional())
465 Cond = dyn_cast<Instruction>(BI->getCondition());
466 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
467 Cond = dyn_cast<Instruction>(IBI->getAddress());
470 TI->eraseFromParent();
471 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
474 /// isValueEqualityComparison - Return true if the specified terminator checks
475 /// to see if a value is equal to constant integer value.
476 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
478 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
479 // Do not permit merging of large switch instructions into their
480 // predecessors unless there is only one predecessor.
481 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
482 pred_end(SI->getParent())) <= 128)
483 CV = SI->getCondition();
484 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
485 if (BI->isConditional() && BI->getCondition()->hasOneUse())
486 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
487 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
488 CV = ICI->getOperand(0);
490 // Unwrap any lossless ptrtoint cast.
492 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
493 Value *Ptr = PTII->getPointerOperand();
494 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
501 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
502 /// decode all of the 'cases' that it represents and return the 'default' block.
503 BasicBlock *SimplifyCFGOpt::
504 GetValueEqualityComparisonCases(TerminatorInst *TI,
505 std::vector<ValueEqualityComparisonCase>
507 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
508 Cases.reserve(SI->getNumCases());
509 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
510 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
511 i.getCaseSuccessor()));
512 return SI->getDefaultDest();
515 BranchInst *BI = cast<BranchInst>(TI);
516 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
517 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
518 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
521 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
525 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
526 /// in the list that match the specified block.
527 static void EliminateBlockCases(BasicBlock *BB,
528 std::vector<ValueEqualityComparisonCase> &Cases) {
529 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
532 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
535 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
536 std::vector<ValueEqualityComparisonCase > &C2) {
537 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
539 // Make V1 be smaller than V2.
540 if (V1->size() > V2->size())
543 if (V1->size() == 0) return false;
544 if (V1->size() == 1) {
546 ConstantInt *TheVal = (*V1)[0].Value;
547 for (unsigned i = 0, e = V2->size(); i != e; ++i)
548 if (TheVal == (*V2)[i].Value)
552 // Otherwise, just sort both lists and compare element by element.
553 array_pod_sort(V1->begin(), V1->end());
554 array_pod_sort(V2->begin(), V2->end());
555 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
556 while (i1 != e1 && i2 != e2) {
557 if ((*V1)[i1].Value == (*V2)[i2].Value)
559 if ((*V1)[i1].Value < (*V2)[i2].Value)
567 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
568 /// terminator instruction and its block is known to only have a single
569 /// predecessor block, check to see if that predecessor is also a value
570 /// comparison with the same value, and if that comparison determines the
571 /// outcome of this comparison. If so, simplify TI. This does a very limited
572 /// form of jump threading.
573 bool SimplifyCFGOpt::
574 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
576 IRBuilder<> &Builder) {
577 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
578 if (!PredVal) return false; // Not a value comparison in predecessor.
580 Value *ThisVal = isValueEqualityComparison(TI);
581 assert(ThisVal && "This isn't a value comparison!!");
582 if (ThisVal != PredVal) return false; // Different predicates.
584 // TODO: Preserve branch weight metadata, similarly to how
585 // FoldValueComparisonIntoPredecessors preserves it.
587 // Find out information about when control will move from Pred to TI's block.
588 std::vector<ValueEqualityComparisonCase> PredCases;
589 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
591 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
593 // Find information about how control leaves this block.
594 std::vector<ValueEqualityComparisonCase> ThisCases;
595 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
596 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
598 // If TI's block is the default block from Pred's comparison, potentially
599 // simplify TI based on this knowledge.
600 if (PredDef == TI->getParent()) {
601 // If we are here, we know that the value is none of those cases listed in
602 // PredCases. If there are any cases in ThisCases that are in PredCases, we
604 if (!ValuesOverlap(PredCases, ThisCases))
607 if (isa<BranchInst>(TI)) {
608 // Okay, one of the successors of this condbr is dead. Convert it to a
610 assert(ThisCases.size() == 1 && "Branch can only have one case!");
611 // Insert the new branch.
612 Instruction *NI = Builder.CreateBr(ThisDef);
615 // Remove PHI node entries for the dead edge.
616 ThisCases[0].Dest->removePredecessor(TI->getParent());
618 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
619 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
621 EraseTerminatorInstAndDCECond(TI);
625 SwitchInst *SI = cast<SwitchInst>(TI);
626 // Okay, TI has cases that are statically dead, prune them away.
627 SmallPtrSet<Constant*, 16> DeadCases;
628 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
629 DeadCases.insert(PredCases[i].Value);
631 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
632 << "Through successor TI: " << *TI);
634 // Collect branch weights into a vector.
635 SmallVector<uint32_t, 8> Weights;
636 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
637 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
639 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
641 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
643 Weights.push_back(CI->getValue().getZExtValue());
645 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
647 if (DeadCases.count(i.getCaseValue())) {
649 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
652 i.getCaseSuccessor()->removePredecessor(TI->getParent());
656 if (HasWeight && Weights.size() >= 2)
657 SI->setMetadata(LLVMContext::MD_prof,
658 MDBuilder(SI->getParent()->getContext()).
659 createBranchWeights(Weights));
661 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
665 // Otherwise, TI's block must correspond to some matched value. Find out
666 // which value (or set of values) this is.
667 ConstantInt *TIV = nullptr;
668 BasicBlock *TIBB = TI->getParent();
669 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
670 if (PredCases[i].Dest == TIBB) {
672 return false; // Cannot handle multiple values coming to this block.
673 TIV = PredCases[i].Value;
675 assert(TIV && "No edge from pred to succ?");
677 // Okay, we found the one constant that our value can be if we get into TI's
678 // BB. Find out which successor will unconditionally be branched to.
679 BasicBlock *TheRealDest = nullptr;
680 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
681 if (ThisCases[i].Value == TIV) {
682 TheRealDest = ThisCases[i].Dest;
686 // If not handled by any explicit cases, it is handled by the default case.
687 if (!TheRealDest) TheRealDest = ThisDef;
689 // Remove PHI node entries for dead edges.
690 BasicBlock *CheckEdge = TheRealDest;
691 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
692 if (*SI != CheckEdge)
693 (*SI)->removePredecessor(TIBB);
697 // Insert the new branch.
698 Instruction *NI = Builder.CreateBr(TheRealDest);
701 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
702 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
704 EraseTerminatorInstAndDCECond(TI);
709 /// ConstantIntOrdering - This class implements a stable ordering of constant
710 /// integers that does not depend on their address. This is important for
711 /// applications that sort ConstantInt's to ensure uniqueness.
712 struct ConstantIntOrdering {
713 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
714 return LHS->getValue().ult(RHS->getValue());
719 static int ConstantIntSortPredicate(ConstantInt *const *P1,
720 ConstantInt *const *P2) {
721 const ConstantInt *LHS = *P1;
722 const ConstantInt *RHS = *P2;
723 if (LHS->getValue().ult(RHS->getValue()))
725 if (LHS->getValue() == RHS->getValue())
730 static inline bool HasBranchWeights(const Instruction* I) {
731 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
732 if (ProfMD && ProfMD->getOperand(0))
733 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
734 return MDS->getString().equals("branch_weights");
739 /// Get Weights of a given TerminatorInst, the default weight is at the front
740 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
742 static void GetBranchWeights(TerminatorInst *TI,
743 SmallVectorImpl<uint64_t> &Weights) {
744 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
746 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
747 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
748 Weights.push_back(CI->getValue().getZExtValue());
751 // If TI is a conditional eq, the default case is the false case,
752 // and the corresponding branch-weight data is at index 2. We swap the
753 // default weight to be the first entry.
754 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
755 assert(Weights.size() == 2);
756 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
757 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
758 std::swap(Weights.front(), Weights.back());
762 /// Keep halving the weights until all can fit in uint32_t.
763 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
764 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
765 if (Max > UINT_MAX) {
766 unsigned Offset = 32 - countLeadingZeros(Max);
767 for (uint64_t &I : Weights)
772 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
773 /// equality comparison instruction (either a switch or a branch on "X == c").
774 /// See if any of the predecessors of the terminator block are value comparisons
775 /// on the same value. If so, and if safe to do so, fold them together.
776 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
777 IRBuilder<> &Builder) {
778 BasicBlock *BB = TI->getParent();
779 Value *CV = isValueEqualityComparison(TI); // CondVal
780 assert(CV && "Not a comparison?");
781 bool Changed = false;
783 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
784 while (!Preds.empty()) {
785 BasicBlock *Pred = Preds.pop_back_val();
787 // See if the predecessor is a comparison with the same value.
788 TerminatorInst *PTI = Pred->getTerminator();
789 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
791 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
792 // Figure out which 'cases' to copy from SI to PSI.
793 std::vector<ValueEqualityComparisonCase> BBCases;
794 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
796 std::vector<ValueEqualityComparisonCase> PredCases;
797 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
799 // Based on whether the default edge from PTI goes to BB or not, fill in
800 // PredCases and PredDefault with the new switch cases we would like to
802 SmallVector<BasicBlock*, 8> NewSuccessors;
804 // Update the branch weight metadata along the way
805 SmallVector<uint64_t, 8> Weights;
806 bool PredHasWeights = HasBranchWeights(PTI);
807 bool SuccHasWeights = HasBranchWeights(TI);
809 if (PredHasWeights) {
810 GetBranchWeights(PTI, Weights);
811 // branch-weight metadata is inconsistent here.
812 if (Weights.size() != 1 + PredCases.size())
813 PredHasWeights = SuccHasWeights = false;
814 } else if (SuccHasWeights)
815 // If there are no predecessor weights but there are successor weights,
816 // populate Weights with 1, which will later be scaled to the sum of
817 // successor's weights
818 Weights.assign(1 + PredCases.size(), 1);
820 SmallVector<uint64_t, 8> SuccWeights;
821 if (SuccHasWeights) {
822 GetBranchWeights(TI, SuccWeights);
823 // branch-weight metadata is inconsistent here.
824 if (SuccWeights.size() != 1 + BBCases.size())
825 PredHasWeights = SuccHasWeights = false;
826 } else if (PredHasWeights)
827 SuccWeights.assign(1 + BBCases.size(), 1);
829 if (PredDefault == BB) {
830 // If this is the default destination from PTI, only the edges in TI
831 // that don't occur in PTI, or that branch to BB will be activated.
832 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
833 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
834 if (PredCases[i].Dest != BB)
835 PTIHandled.insert(PredCases[i].Value);
837 // The default destination is BB, we don't need explicit targets.
838 std::swap(PredCases[i], PredCases.back());
840 if (PredHasWeights || SuccHasWeights) {
841 // Increase weight for the default case.
842 Weights[0] += Weights[i+1];
843 std::swap(Weights[i+1], Weights.back());
847 PredCases.pop_back();
851 // Reconstruct the new switch statement we will be building.
852 if (PredDefault != BBDefault) {
853 PredDefault->removePredecessor(Pred);
854 PredDefault = BBDefault;
855 NewSuccessors.push_back(BBDefault);
858 unsigned CasesFromPred = Weights.size();
859 uint64_t ValidTotalSuccWeight = 0;
860 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
861 if (!PTIHandled.count(BBCases[i].Value) &&
862 BBCases[i].Dest != BBDefault) {
863 PredCases.push_back(BBCases[i]);
864 NewSuccessors.push_back(BBCases[i].Dest);
865 if (SuccHasWeights || PredHasWeights) {
866 // The default weight is at index 0, so weight for the ith case
867 // should be at index i+1. Scale the cases from successor by
868 // PredDefaultWeight (Weights[0]).
869 Weights.push_back(Weights[0] * SuccWeights[i+1]);
870 ValidTotalSuccWeight += SuccWeights[i+1];
874 if (SuccHasWeights || PredHasWeights) {
875 ValidTotalSuccWeight += SuccWeights[0];
876 // Scale the cases from predecessor by ValidTotalSuccWeight.
877 for (unsigned i = 1; i < CasesFromPred; ++i)
878 Weights[i] *= ValidTotalSuccWeight;
879 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
880 Weights[0] *= SuccWeights[0];
883 // If this is not the default destination from PSI, only the edges
884 // in SI that occur in PSI with a destination of BB will be
886 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
887 std::map<ConstantInt*, uint64_t> WeightsForHandled;
888 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
889 if (PredCases[i].Dest == BB) {
890 PTIHandled.insert(PredCases[i].Value);
892 if (PredHasWeights || SuccHasWeights) {
893 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
894 std::swap(Weights[i+1], Weights.back());
898 std::swap(PredCases[i], PredCases.back());
899 PredCases.pop_back();
903 // Okay, now we know which constants were sent to BB from the
904 // predecessor. Figure out where they will all go now.
905 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
906 if (PTIHandled.count(BBCases[i].Value)) {
907 // If this is one we are capable of getting...
908 if (PredHasWeights || SuccHasWeights)
909 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
910 PredCases.push_back(BBCases[i]);
911 NewSuccessors.push_back(BBCases[i].Dest);
912 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
915 // If there are any constants vectored to BB that TI doesn't handle,
916 // they must go to the default destination of TI.
917 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
919 E = PTIHandled.end(); I != E; ++I) {
920 if (PredHasWeights || SuccHasWeights)
921 Weights.push_back(WeightsForHandled[*I]);
922 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
923 NewSuccessors.push_back(BBDefault);
927 // Okay, at this point, we know which new successor Pred will get. Make
928 // sure we update the number of entries in the PHI nodes for these
930 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
931 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
933 Builder.SetInsertPoint(PTI);
934 // Convert pointer to int before we switch.
935 if (CV->getType()->isPointerTy()) {
936 assert(DL && "Cannot switch on pointer without DataLayout");
937 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
941 // Now that the successors are updated, create the new Switch instruction.
942 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
944 NewSI->setDebugLoc(PTI->getDebugLoc());
945 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
948 if (PredHasWeights || SuccHasWeights) {
949 // Halve the weights if any of them cannot fit in an uint32_t
952 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
954 NewSI->setMetadata(LLVMContext::MD_prof,
955 MDBuilder(BB->getContext()).
956 createBranchWeights(MDWeights));
959 EraseTerminatorInstAndDCECond(PTI);
961 // Okay, last check. If BB is still a successor of PSI, then we must
962 // have an infinite loop case. If so, add an infinitely looping block
963 // to handle the case to preserve the behavior of the code.
964 BasicBlock *InfLoopBlock = nullptr;
965 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
966 if (NewSI->getSuccessor(i) == BB) {
968 // Insert it at the end of the function, because it's either code,
969 // or it won't matter if it's hot. :)
970 InfLoopBlock = BasicBlock::Create(BB->getContext(),
971 "infloop", BB->getParent());
972 BranchInst::Create(InfLoopBlock, InfLoopBlock);
974 NewSI->setSuccessor(i, InfLoopBlock);
983 // isSafeToHoistInvoke - If we would need to insert a select that uses the
984 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
985 // would need to do this), we can't hoist the invoke, as there is nowhere
986 // to put the select in this case.
987 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
988 Instruction *I1, Instruction *I2) {
989 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
991 for (BasicBlock::iterator BBI = SI->begin();
992 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
993 Value *BB1V = PN->getIncomingValueForBlock(BB1);
994 Value *BB2V = PN->getIncomingValueForBlock(BB2);
995 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1003 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1004 /// BB2, hoist any common code in the two blocks up into the branch block. The
1005 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1006 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1007 // This does very trivial matching, with limited scanning, to find identical
1008 // instructions in the two blocks. In particular, we don't want to get into
1009 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1010 // such, we currently just scan for obviously identical instructions in an
1012 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1013 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1015 BasicBlock::iterator BB1_Itr = BB1->begin();
1016 BasicBlock::iterator BB2_Itr = BB2->begin();
1018 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1019 // Skip debug info if it is not identical.
1020 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1021 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1022 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1023 while (isa<DbgInfoIntrinsic>(I1))
1025 while (isa<DbgInfoIntrinsic>(I2))
1028 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1029 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1032 BasicBlock *BIParent = BI->getParent();
1034 bool Changed = false;
1036 // If we are hoisting the terminator instruction, don't move one (making a
1037 // broken BB), instead clone it, and remove BI.
1038 if (isa<TerminatorInst>(I1))
1039 goto HoistTerminator;
1041 // For a normal instruction, we just move one to right before the branch,
1042 // then replace all uses of the other with the first. Finally, we remove
1043 // the now redundant second instruction.
1044 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1045 if (!I2->use_empty())
1046 I2->replaceAllUsesWith(I1);
1047 I1->intersectOptionalDataWith(I2);
1048 unsigned KnownIDs[] = {
1049 LLVMContext::MD_tbaa,
1050 LLVMContext::MD_range,
1051 LLVMContext::MD_fpmath,
1052 LLVMContext::MD_invariant_load
1054 combineMetadata(I1, I2, KnownIDs);
1055 I2->eraseFromParent();
1060 // Skip debug info if it is not identical.
1061 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1062 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1063 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1064 while (isa<DbgInfoIntrinsic>(I1))
1066 while (isa<DbgInfoIntrinsic>(I2))
1069 } while (I1->isIdenticalToWhenDefined(I2));
1074 // It may not be possible to hoist an invoke.
1075 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1078 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1080 for (BasicBlock::iterator BBI = SI->begin();
1081 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1082 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1083 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1087 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1089 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1094 // Okay, it is safe to hoist the terminator.
1095 Instruction *NT = I1->clone();
1096 BIParent->getInstList().insert(BI, NT);
1097 if (!NT->getType()->isVoidTy()) {
1098 I1->replaceAllUsesWith(NT);
1099 I2->replaceAllUsesWith(NT);
1103 IRBuilder<true, NoFolder> Builder(NT);
1104 // Hoisting one of the terminators from our successor is a great thing.
1105 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1106 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1107 // nodes, so we insert select instruction to compute the final result.
1108 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1109 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1111 for (BasicBlock::iterator BBI = SI->begin();
1112 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1113 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1114 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1115 if (BB1V == BB2V) continue;
1117 // These values do not agree. Insert a select instruction before NT
1118 // that determines the right value.
1119 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1121 SI = cast<SelectInst>
1122 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1123 BB1V->getName()+"."+BB2V->getName()));
1125 // Make the PHI node use the select for all incoming values for BB1/BB2
1126 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1127 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1128 PN->setIncomingValue(i, SI);
1132 // Update any PHI nodes in our new successors.
1133 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1134 AddPredecessorToBlock(*SI, BIParent, BB1);
1136 EraseTerminatorInstAndDCECond(BI);
1140 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1141 /// check whether BBEnd has only two predecessors and the other predecessor
1142 /// ends with an unconditional branch. If it is true, sink any common code
1143 /// in the two predecessors to BBEnd.
1144 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1145 assert(BI1->isUnconditional());
1146 BasicBlock *BB1 = BI1->getParent();
1147 BasicBlock *BBEnd = BI1->getSuccessor(0);
1149 // Check that BBEnd has two predecessors and the other predecessor ends with
1150 // an unconditional branch.
1151 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1152 BasicBlock *Pred0 = *PI++;
1153 if (PI == PE) // Only one predecessor.
1155 BasicBlock *Pred1 = *PI++;
1156 if (PI != PE) // More than two predecessors.
1158 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1159 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1160 if (!BI2 || !BI2->isUnconditional())
1163 // Gather the PHI nodes in BBEnd.
1164 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1165 Instruction *FirstNonPhiInBBEnd = nullptr;
1166 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1168 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1169 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1170 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1171 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1173 FirstNonPhiInBBEnd = &*I;
1177 if (!FirstNonPhiInBBEnd)
1181 // This does very trivial matching, with limited scanning, to find identical
1182 // instructions in the two blocks. We scan backward for obviously identical
1183 // instructions in an identical order.
1184 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1185 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1186 RE2 = BB2->getInstList().rend();
1188 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1191 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1194 // Skip the unconditional branches.
1198 bool Changed = false;
1199 while (RI1 != RE1 && RI2 != RE2) {
1201 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1204 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1208 Instruction *I1 = &*RI1, *I2 = &*RI2;
1209 // I1 and I2 should have a single use in the same PHI node, and they
1210 // perform the same operation.
1211 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1212 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1213 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1214 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1215 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1216 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1217 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1218 !I1->hasOneUse() || !I2->hasOneUse() ||
1219 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1220 MapValueFromBB1ToBB2[I1].first != I2)
1223 // Check whether we should swap the operands of ICmpInst.
1224 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1225 bool SwapOpnds = false;
1226 if (ICmp1 && ICmp2 &&
1227 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1228 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1229 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1230 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1231 ICmp2->swapOperands();
1234 if (!I1->isSameOperationAs(I2)) {
1236 ICmp2->swapOperands();
1240 // The operands should be either the same or they need to be generated
1241 // with a PHI node after sinking. We only handle the case where there is
1242 // a single pair of different operands.
1243 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1244 unsigned Op1Idx = 0;
1245 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1246 if (I1->getOperand(I) == I2->getOperand(I))
1248 // Early exit if we have more-than one pair of different operands or
1249 // the different operand is already in MapValueFromBB1ToBB2.
1250 // Early exit if we need a PHI node to replace a constant.
1252 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1253 MapValueFromBB1ToBB2.end() ||
1254 isa<Constant>(I1->getOperand(I)) ||
1255 isa<Constant>(I2->getOperand(I))) {
1256 // If we can't sink the instructions, undo the swapping.
1258 ICmp2->swapOperands();
1261 DifferentOp1 = I1->getOperand(I);
1263 DifferentOp2 = I2->getOperand(I);
1266 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1267 // remove (I1, I2) from MapValueFromBB1ToBB2.
1269 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1270 DifferentOp1->getName() + ".sink",
1272 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1273 // I1 should use NewPN instead of DifferentOp1.
1274 I1->setOperand(Op1Idx, NewPN);
1275 NewPN->addIncoming(DifferentOp1, BB1);
1276 NewPN->addIncoming(DifferentOp2, BB2);
1277 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1279 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1280 MapValueFromBB1ToBB2.erase(I1);
1282 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1283 DEBUG(dbgs() << " " << *I2 << "\n";);
1284 // We need to update RE1 and RE2 if we are going to sink the first
1285 // instruction in the basic block down.
1286 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1287 // Sink the instruction.
1288 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1289 if (!OldPN->use_empty())
1290 OldPN->replaceAllUsesWith(I1);
1291 OldPN->eraseFromParent();
1293 if (!I2->use_empty())
1294 I2->replaceAllUsesWith(I1);
1295 I1->intersectOptionalDataWith(I2);
1296 I2->eraseFromParent();
1299 RE1 = BB1->getInstList().rend();
1301 RE2 = BB2->getInstList().rend();
1302 FirstNonPhiInBBEnd = I1;
1309 /// \brief Determine if we can hoist sink a sole store instruction out of a
1310 /// conditional block.
1312 /// We are looking for code like the following:
1314 /// store i32 %add, i32* %arrayidx2
1315 /// ... // No other stores or function calls (we could be calling a memory
1316 /// ... // function).
1317 /// %cmp = icmp ult %x, %y
1318 /// br i1 %cmp, label %EndBB, label %ThenBB
1320 /// store i32 %add5, i32* %arrayidx2
1324 /// We are going to transform this into:
1326 /// store i32 %add, i32* %arrayidx2
1328 /// %cmp = icmp ult %x, %y
1329 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1330 /// store i32 %add.add5, i32* %arrayidx2
1333 /// \return The pointer to the value of the previous store if the store can be
1334 /// hoisted into the predecessor block. 0 otherwise.
1335 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1336 BasicBlock *StoreBB, BasicBlock *EndBB) {
1337 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1341 // Volatile or atomic.
1342 if (!StoreToHoist->isSimple())
1345 Value *StorePtr = StoreToHoist->getPointerOperand();
1347 // Look for a store to the same pointer in BrBB.
1348 unsigned MaxNumInstToLookAt = 10;
1349 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1350 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1351 Instruction *CurI = &*RI;
1353 // Could be calling an instruction that effects memory like free().
1354 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1357 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1358 // Found the previous store make sure it stores to the same location.
1359 if (SI && SI->getPointerOperand() == StorePtr)
1360 // Found the previous store, return its value operand.
1361 return SI->getValueOperand();
1363 return nullptr; // Unknown store.
1369 /// \brief Speculate a conditional basic block flattening the CFG.
1371 /// Note that this is a very risky transform currently. Speculating
1372 /// instructions like this is most often not desirable. Instead, there is an MI
1373 /// pass which can do it with full awareness of the resource constraints.
1374 /// However, some cases are "obvious" and we should do directly. An example of
1375 /// this is speculating a single, reasonably cheap instruction.
1377 /// There is only one distinct advantage to flattening the CFG at the IR level:
1378 /// it makes very common but simplistic optimizations such as are common in
1379 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1380 /// modeling their effects with easier to reason about SSA value graphs.
1383 /// An illustration of this transform is turning this IR:
1386 /// %cmp = icmp ult %x, %y
1387 /// br i1 %cmp, label %EndBB, label %ThenBB
1389 /// %sub = sub %x, %y
1392 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1399 /// %cmp = icmp ult %x, %y
1400 /// %sub = sub %x, %y
1401 /// %cond = select i1 %cmp, 0, %sub
1405 /// \returns true if the conditional block is removed.
1406 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1407 const DataLayout *DL) {
1408 // Be conservative for now. FP select instruction can often be expensive.
1409 Value *BrCond = BI->getCondition();
1410 if (isa<FCmpInst>(BrCond))
1413 BasicBlock *BB = BI->getParent();
1414 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1416 // If ThenBB is actually on the false edge of the conditional branch, remember
1417 // to swap the select operands later.
1418 bool Invert = false;
1419 if (ThenBB != BI->getSuccessor(0)) {
1420 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1423 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1425 // Keep a count of how many times instructions are used within CondBB when
1426 // they are candidates for sinking into CondBB. Specifically:
1427 // - They are defined in BB, and
1428 // - They have no side effects, and
1429 // - All of their uses are in CondBB.
1430 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1432 unsigned SpeculationCost = 0;
1433 Value *SpeculatedStoreValue = nullptr;
1434 StoreInst *SpeculatedStore = nullptr;
1435 for (BasicBlock::iterator BBI = ThenBB->begin(),
1436 BBE = std::prev(ThenBB->end());
1437 BBI != BBE; ++BBI) {
1438 Instruction *I = BBI;
1440 if (isa<DbgInfoIntrinsic>(I))
1443 // Only speculatively execution a single instruction (not counting the
1444 // terminator) for now.
1446 if (SpeculationCost > 1)
1449 // Don't hoist the instruction if it's unsafe or expensive.
1450 if (!isSafeToSpeculativelyExecute(I, DL) &&
1451 !(HoistCondStores &&
1452 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1455 if (!SpeculatedStoreValue &&
1456 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
1459 // Store the store speculation candidate.
1460 if (SpeculatedStoreValue)
1461 SpeculatedStore = cast<StoreInst>(I);
1463 // Do not hoist the instruction if any of its operands are defined but not
1464 // used in BB. The transformation will prevent the operand from
1465 // being sunk into the use block.
1466 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1468 Instruction *OpI = dyn_cast<Instruction>(*i);
1469 if (!OpI || OpI->getParent() != BB ||
1470 OpI->mayHaveSideEffects())
1471 continue; // Not a candidate for sinking.
1473 ++SinkCandidateUseCounts[OpI];
1477 // Consider any sink candidates which are only used in CondBB as costs for
1478 // speculation. Note, while we iterate over a DenseMap here, we are summing
1479 // and so iteration order isn't significant.
1480 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1481 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1483 if (I->first->getNumUses() == I->second) {
1485 if (SpeculationCost > 1)
1489 // Check that the PHI nodes can be converted to selects.
1490 bool HaveRewritablePHIs = false;
1491 for (BasicBlock::iterator I = EndBB->begin();
1492 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1493 Value *OrigV = PN->getIncomingValueForBlock(BB);
1494 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1496 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1497 // Skip PHIs which are trivial.
1501 HaveRewritablePHIs = true;
1502 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1503 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1504 if (!OrigCE && !ThenCE)
1505 continue; // Known safe and cheap.
1507 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1508 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1510 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1511 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
1512 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1515 // Account for the cost of an unfolded ConstantExpr which could end up
1516 // getting expanded into Instructions.
1517 // FIXME: This doesn't account for how many operations are combined in the
1518 // constant expression.
1520 if (SpeculationCost > 1)
1524 // If there are no PHIs to process, bail early. This helps ensure idempotence
1526 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1529 // If we get here, we can hoist the instruction and if-convert.
1530 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1532 // Insert a select of the value of the speculated store.
1533 if (SpeculatedStoreValue) {
1534 IRBuilder<true, NoFolder> Builder(BI);
1535 Value *TrueV = SpeculatedStore->getValueOperand();
1536 Value *FalseV = SpeculatedStoreValue;
1538 std::swap(TrueV, FalseV);
1539 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1540 "." + FalseV->getName());
1541 SpeculatedStore->setOperand(0, S);
1544 // Hoist the instructions.
1545 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1546 std::prev(ThenBB->end()));
1548 // Insert selects and rewrite the PHI operands.
1549 IRBuilder<true, NoFolder> Builder(BI);
1550 for (BasicBlock::iterator I = EndBB->begin();
1551 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1552 unsigned OrigI = PN->getBasicBlockIndex(BB);
1553 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1554 Value *OrigV = PN->getIncomingValue(OrigI);
1555 Value *ThenV = PN->getIncomingValue(ThenI);
1557 // Skip PHIs which are trivial.
1561 // Create a select whose true value is the speculatively executed value and
1562 // false value is the preexisting value. Swap them if the branch
1563 // destinations were inverted.
1564 Value *TrueV = ThenV, *FalseV = OrigV;
1566 std::swap(TrueV, FalseV);
1567 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1568 TrueV->getName() + "." + FalseV->getName());
1569 PN->setIncomingValue(OrigI, V);
1570 PN->setIncomingValue(ThenI, V);
1577 /// \returns True if this block contains a CallInst with the NoDuplicate
1579 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1580 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1581 const CallInst *CI = dyn_cast<CallInst>(I);
1584 if (CI->cannotDuplicate())
1590 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1591 /// across this block.
1592 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1593 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1596 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1597 if (isa<DbgInfoIntrinsic>(BBI))
1599 if (Size > 10) return false; // Don't clone large BB's.
1602 // We can only support instructions that do not define values that are
1603 // live outside of the current basic block.
1604 for (User *U : BBI->users()) {
1605 Instruction *UI = cast<Instruction>(U);
1606 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1609 // Looks ok, continue checking.
1615 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1616 /// that is defined in the same block as the branch and if any PHI entries are
1617 /// constants, thread edges corresponding to that entry to be branches to their
1618 /// ultimate destination.
1619 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1620 BasicBlock *BB = BI->getParent();
1621 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1622 // NOTE: we currently cannot transform this case if the PHI node is used
1623 // outside of the block.
1624 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1627 // Degenerate case of a single entry PHI.
1628 if (PN->getNumIncomingValues() == 1) {
1629 FoldSingleEntryPHINodes(PN->getParent());
1633 // Now we know that this block has multiple preds and two succs.
1634 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1636 if (HasNoDuplicateCall(BB)) return false;
1638 // Okay, this is a simple enough basic block. See if any phi values are
1640 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1641 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1642 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1644 // Okay, we now know that all edges from PredBB should be revectored to
1645 // branch to RealDest.
1646 BasicBlock *PredBB = PN->getIncomingBlock(i);
1647 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1649 if (RealDest == BB) continue; // Skip self loops.
1650 // Skip if the predecessor's terminator is an indirect branch.
1651 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1653 // The dest block might have PHI nodes, other predecessors and other
1654 // difficult cases. Instead of being smart about this, just insert a new
1655 // block that jumps to the destination block, effectively splitting
1656 // the edge we are about to create.
1657 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1658 RealDest->getName()+".critedge",
1659 RealDest->getParent(), RealDest);
1660 BranchInst::Create(RealDest, EdgeBB);
1662 // Update PHI nodes.
1663 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1665 // BB may have instructions that are being threaded over. Clone these
1666 // instructions into EdgeBB. We know that there will be no uses of the
1667 // cloned instructions outside of EdgeBB.
1668 BasicBlock::iterator InsertPt = EdgeBB->begin();
1669 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1670 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1671 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1672 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1675 // Clone the instruction.
1676 Instruction *N = BBI->clone();
1677 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1679 // Update operands due to translation.
1680 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1682 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1683 if (PI != TranslateMap.end())
1687 // Check for trivial simplification.
1688 if (Value *V = SimplifyInstruction(N, DL)) {
1689 TranslateMap[BBI] = V;
1690 delete N; // Instruction folded away, don't need actual inst
1692 // Insert the new instruction into its new home.
1693 EdgeBB->getInstList().insert(InsertPt, N);
1694 if (!BBI->use_empty())
1695 TranslateMap[BBI] = N;
1699 // Loop over all of the edges from PredBB to BB, changing them to branch
1700 // to EdgeBB instead.
1701 TerminatorInst *PredBBTI = PredBB->getTerminator();
1702 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1703 if (PredBBTI->getSuccessor(i) == BB) {
1704 BB->removePredecessor(PredBB);
1705 PredBBTI->setSuccessor(i, EdgeBB);
1708 // Recurse, simplifying any other constants.
1709 return FoldCondBranchOnPHI(BI, DL) | true;
1715 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1716 /// PHI node, see if we can eliminate it.
1717 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1718 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1719 // statement", which has a very simple dominance structure. Basically, we
1720 // are trying to find the condition that is being branched on, which
1721 // subsequently causes this merge to happen. We really want control
1722 // dependence information for this check, but simplifycfg can't keep it up
1723 // to date, and this catches most of the cases we care about anyway.
1724 BasicBlock *BB = PN->getParent();
1725 BasicBlock *IfTrue, *IfFalse;
1726 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1728 // Don't bother if the branch will be constant folded trivially.
1729 isa<ConstantInt>(IfCond))
1732 // Okay, we found that we can merge this two-entry phi node into a select.
1733 // Doing so would require us to fold *all* two entry phi nodes in this block.
1734 // At some point this becomes non-profitable (particularly if the target
1735 // doesn't support cmov's). Only do this transformation if there are two or
1736 // fewer PHI nodes in this block.
1737 unsigned NumPhis = 0;
1738 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1742 // Loop over the PHI's seeing if we can promote them all to select
1743 // instructions. While we are at it, keep track of the instructions
1744 // that need to be moved to the dominating block.
1745 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1746 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1747 MaxCostVal1 = PHINodeFoldingThreshold;
1749 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1750 PHINode *PN = cast<PHINode>(II++);
1751 if (Value *V = SimplifyInstruction(PN, DL)) {
1752 PN->replaceAllUsesWith(V);
1753 PN->eraseFromParent();
1757 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1759 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1764 // If we folded the first phi, PN dangles at this point. Refresh it. If
1765 // we ran out of PHIs then we simplified them all.
1766 PN = dyn_cast<PHINode>(BB->begin());
1767 if (!PN) return true;
1769 // Don't fold i1 branches on PHIs which contain binary operators. These can
1770 // often be turned into switches and other things.
1771 if (PN->getType()->isIntegerTy(1) &&
1772 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1773 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1774 isa<BinaryOperator>(IfCond)))
1777 // If we all PHI nodes are promotable, check to make sure that all
1778 // instructions in the predecessor blocks can be promoted as well. If
1779 // not, we won't be able to get rid of the control flow, so it's not
1780 // worth promoting to select instructions.
1781 BasicBlock *DomBlock = nullptr;
1782 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1783 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1784 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1787 DomBlock = *pred_begin(IfBlock1);
1788 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1789 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1790 // This is not an aggressive instruction that we can promote.
1791 // Because of this, we won't be able to get rid of the control
1792 // flow, so the xform is not worth it.
1797 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1800 DomBlock = *pred_begin(IfBlock2);
1801 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1802 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1803 // This is not an aggressive instruction that we can promote.
1804 // Because of this, we won't be able to get rid of the control
1805 // flow, so the xform is not worth it.
1810 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1811 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1813 // If we can still promote the PHI nodes after this gauntlet of tests,
1814 // do all of the PHI's now.
1815 Instruction *InsertPt = DomBlock->getTerminator();
1816 IRBuilder<true, NoFolder> Builder(InsertPt);
1818 // Move all 'aggressive' instructions, which are defined in the
1819 // conditional parts of the if's up to the dominating block.
1821 DomBlock->getInstList().splice(InsertPt,
1822 IfBlock1->getInstList(), IfBlock1->begin(),
1823 IfBlock1->getTerminator());
1825 DomBlock->getInstList().splice(InsertPt,
1826 IfBlock2->getInstList(), IfBlock2->begin(),
1827 IfBlock2->getTerminator());
1829 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1830 // Change the PHI node into a select instruction.
1831 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1832 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1835 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1836 PN->replaceAllUsesWith(NV);
1838 PN->eraseFromParent();
1841 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1842 // has been flattened. Change DomBlock to jump directly to our new block to
1843 // avoid other simplifycfg's kicking in on the diamond.
1844 TerminatorInst *OldTI = DomBlock->getTerminator();
1845 Builder.SetInsertPoint(OldTI);
1846 Builder.CreateBr(BB);
1847 OldTI->eraseFromParent();
1851 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1852 /// to two returning blocks, try to merge them together into one return,
1853 /// introducing a select if the return values disagree.
1854 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1855 IRBuilder<> &Builder) {
1856 assert(BI->isConditional() && "Must be a conditional branch");
1857 BasicBlock *TrueSucc = BI->getSuccessor(0);
1858 BasicBlock *FalseSucc = BI->getSuccessor(1);
1859 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1860 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1862 // Check to ensure both blocks are empty (just a return) or optionally empty
1863 // with PHI nodes. If there are other instructions, merging would cause extra
1864 // computation on one path or the other.
1865 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1867 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1870 Builder.SetInsertPoint(BI);
1871 // Okay, we found a branch that is going to two return nodes. If
1872 // there is no return value for this function, just change the
1873 // branch into a return.
1874 if (FalseRet->getNumOperands() == 0) {
1875 TrueSucc->removePredecessor(BI->getParent());
1876 FalseSucc->removePredecessor(BI->getParent());
1877 Builder.CreateRetVoid();
1878 EraseTerminatorInstAndDCECond(BI);
1882 // Otherwise, figure out what the true and false return values are
1883 // so we can insert a new select instruction.
1884 Value *TrueValue = TrueRet->getReturnValue();
1885 Value *FalseValue = FalseRet->getReturnValue();
1887 // Unwrap any PHI nodes in the return blocks.
1888 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1889 if (TVPN->getParent() == TrueSucc)
1890 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1891 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1892 if (FVPN->getParent() == FalseSucc)
1893 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1895 // In order for this transformation to be safe, we must be able to
1896 // unconditionally execute both operands to the return. This is
1897 // normally the case, but we could have a potentially-trapping
1898 // constant expression that prevents this transformation from being
1900 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1903 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1907 // Okay, we collected all the mapped values and checked them for sanity, and
1908 // defined to really do this transformation. First, update the CFG.
1909 TrueSucc->removePredecessor(BI->getParent());
1910 FalseSucc->removePredecessor(BI->getParent());
1912 // Insert select instructions where needed.
1913 Value *BrCond = BI->getCondition();
1915 // Insert a select if the results differ.
1916 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1917 } else if (isa<UndefValue>(TrueValue)) {
1918 TrueValue = FalseValue;
1920 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1921 FalseValue, "retval");
1925 Value *RI = !TrueValue ?
1926 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1930 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1931 << "\n " << *BI << "NewRet = " << *RI
1932 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1934 EraseTerminatorInstAndDCECond(BI);
1939 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1940 /// probabilities of the branch taking each edge. Fills in the two APInt
1941 /// parameters and return true, or returns false if no or invalid metadata was
1943 static bool ExtractBranchMetadata(BranchInst *BI,
1944 uint64_t &ProbTrue, uint64_t &ProbFalse) {
1945 assert(BI->isConditional() &&
1946 "Looking for probabilities on unconditional branch?");
1947 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1948 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1949 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1950 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1951 if (!CITrue || !CIFalse) return false;
1952 ProbTrue = CITrue->getValue().getZExtValue();
1953 ProbFalse = CIFalse->getValue().getZExtValue();
1957 /// checkCSEInPredecessor - Return true if the given instruction is available
1958 /// in its predecessor block. If yes, the instruction will be removed.
1960 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1961 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1963 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1964 Instruction *PBI = &*I;
1965 // Check whether Inst and PBI generate the same value.
1966 if (Inst->isIdenticalTo(PBI)) {
1967 Inst->replaceAllUsesWith(PBI);
1968 Inst->eraseFromParent();
1975 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1976 /// predecessor branches to us and one of our successors, fold the block into
1977 /// the predecessor and use logical operations to pick the right destination.
1978 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
1979 unsigned BonusInstThreshold) {
1980 BasicBlock *BB = BI->getParent();
1982 Instruction *Cond = nullptr;
1983 if (BI->isConditional())
1984 Cond = dyn_cast<Instruction>(BI->getCondition());
1986 // For unconditional branch, check for a simple CFG pattern, where
1987 // BB has a single predecessor and BB's successor is also its predecessor's
1988 // successor. If such pattern exisits, check for CSE between BB and its
1990 if (BasicBlock *PB = BB->getSinglePredecessor())
1991 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1992 if (PBI->isConditional() &&
1993 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1994 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1995 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1997 Instruction *Curr = I++;
1998 if (isa<CmpInst>(Curr)) {
2002 // Quit if we can't remove this instruction.
2003 if (!checkCSEInPredecessor(Curr, PB))
2012 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2013 Cond->getParent() != BB || !Cond->hasOneUse())
2016 // Make sure the instruction after the condition is the cond branch.
2017 BasicBlock::iterator CondIt = Cond; ++CondIt;
2019 // Ignore dbg intrinsics.
2020 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2025 // Only allow this transformation if computing the condition doesn't involve
2026 // too many instructions and these involved instructions can be executed
2027 // unconditionally. We denote all involved instructions except the condition
2028 // as "bonus instructions", and only allow this transformation when the
2029 // number of the bonus instructions does not exceed a certain threshold.
2030 unsigned NumBonusInsts = 0;
2031 for (auto I = BB->begin(); Cond != I; ++I) {
2032 // Ignore dbg intrinsics.
2033 if (isa<DbgInfoIntrinsic>(I))
2035 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2037 // I has only one use and can be executed unconditionally.
2038 Instruction *User = dyn_cast<Instruction>(I->user_back());
2039 if (User == nullptr || User->getParent() != BB)
2041 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2042 // to use any other instruction, User must be an instruction between next(I)
2045 // Early exits once we reach the limit.
2046 if (NumBonusInsts > BonusInstThreshold)
2050 // Cond is known to be a compare or binary operator. Check to make sure that
2051 // neither operand is a potentially-trapping constant expression.
2052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2055 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2059 // Finally, don't infinitely unroll conditional loops.
2060 BasicBlock *TrueDest = BI->getSuccessor(0);
2061 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2062 if (TrueDest == BB || FalseDest == BB)
2065 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2066 BasicBlock *PredBlock = *PI;
2067 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2069 // Check that we have two conditional branches. If there is a PHI node in
2070 // the common successor, verify that the same value flows in from both
2072 SmallVector<PHINode*, 4> PHIs;
2073 if (!PBI || PBI->isUnconditional() ||
2074 (BI->isConditional() &&
2075 !SafeToMergeTerminators(BI, PBI)) ||
2076 (!BI->isConditional() &&
2077 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2080 // Determine if the two branches share a common destination.
2081 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2082 bool InvertPredCond = false;
2084 if (BI->isConditional()) {
2085 if (PBI->getSuccessor(0) == TrueDest)
2086 Opc = Instruction::Or;
2087 else if (PBI->getSuccessor(1) == FalseDest)
2088 Opc = Instruction::And;
2089 else if (PBI->getSuccessor(0) == FalseDest)
2090 Opc = Instruction::And, InvertPredCond = true;
2091 else if (PBI->getSuccessor(1) == TrueDest)
2092 Opc = Instruction::Or, InvertPredCond = true;
2096 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2100 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2101 IRBuilder<> Builder(PBI);
2103 // If we need to invert the condition in the pred block to match, do so now.
2104 if (InvertPredCond) {
2105 Value *NewCond = PBI->getCondition();
2107 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2108 CmpInst *CI = cast<CmpInst>(NewCond);
2109 CI->setPredicate(CI->getInversePredicate());
2111 NewCond = Builder.CreateNot(NewCond,
2112 PBI->getCondition()->getName()+".not");
2115 PBI->setCondition(NewCond);
2116 PBI->swapSuccessors();
2119 // If we have bonus instructions, clone them into the predecessor block.
2120 // Note that there may be mutliple predecessor blocks, so we cannot move
2121 // bonus instructions to a predecessor block.
2122 ValueToValueMapTy VMap; // maps original values to cloned values
2123 // We already make sure Cond is the last instruction before BI. Therefore,
2124 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2126 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2127 if (isa<DbgInfoIntrinsic>(BonusInst))
2129 Instruction *NewBonusInst = BonusInst->clone();
2130 RemapInstruction(NewBonusInst, VMap,
2131 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2132 VMap[BonusInst] = NewBonusInst;
2134 // If we moved a load, we cannot any longer claim any knowledge about
2135 // its potential value. The previous information might have been valid
2136 // only given the branch precondition.
2137 // For an analogous reason, we must also drop all the metadata whose
2138 // semantics we don't understand.
2139 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2141 PredBlock->getInstList().insert(PBI, NewBonusInst);
2142 NewBonusInst->takeName(BonusInst);
2143 BonusInst->setName(BonusInst->getName() + ".old");
2146 // Clone Cond into the predecessor basic block, and or/and the
2147 // two conditions together.
2148 Instruction *New = Cond->clone();
2149 RemapInstruction(New, VMap,
2150 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2151 PredBlock->getInstList().insert(PBI, New);
2152 New->takeName(Cond);
2153 Cond->setName(New->getName() + ".old");
2155 if (BI->isConditional()) {
2156 Instruction *NewCond =
2157 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2159 PBI->setCondition(NewCond);
2161 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2162 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2164 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2166 SmallVector<uint64_t, 8> NewWeights;
2168 if (PBI->getSuccessor(0) == BB) {
2169 if (PredHasWeights && SuccHasWeights) {
2170 // PBI: br i1 %x, BB, FalseDest
2171 // BI: br i1 %y, TrueDest, FalseDest
2172 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2173 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2174 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2175 // TrueWeight for PBI * FalseWeight for BI.
2176 // We assume that total weights of a BranchInst can fit into 32 bits.
2177 // Therefore, we will not have overflow using 64-bit arithmetic.
2178 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2179 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2181 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2182 PBI->setSuccessor(0, TrueDest);
2184 if (PBI->getSuccessor(1) == BB) {
2185 if (PredHasWeights && SuccHasWeights) {
2186 // PBI: br i1 %x, TrueDest, BB
2187 // BI: br i1 %y, TrueDest, FalseDest
2188 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2189 // FalseWeight for PBI * TrueWeight for BI.
2190 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2191 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2192 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2193 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2195 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2196 PBI->setSuccessor(1, FalseDest);
2198 if (NewWeights.size() == 2) {
2199 // Halve the weights if any of them cannot fit in an uint32_t
2200 FitWeights(NewWeights);
2202 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2203 PBI->setMetadata(LLVMContext::MD_prof,
2204 MDBuilder(BI->getContext()).
2205 createBranchWeights(MDWeights));
2207 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2209 // Update PHI nodes in the common successors.
2210 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2211 ConstantInt *PBI_C = cast<ConstantInt>(
2212 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2213 assert(PBI_C->getType()->isIntegerTy(1));
2214 Instruction *MergedCond = nullptr;
2215 if (PBI->getSuccessor(0) == TrueDest) {
2216 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2217 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2218 // is false: !PBI_Cond and BI_Value
2219 Instruction *NotCond =
2220 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2223 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2228 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2229 PBI->getCondition(), MergedCond,
2232 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2233 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2234 // is false: PBI_Cond and BI_Value
2236 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2237 PBI->getCondition(), New,
2239 if (PBI_C->isOne()) {
2240 Instruction *NotCond =
2241 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2244 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2245 NotCond, MergedCond,
2250 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2253 // Change PBI from Conditional to Unconditional.
2254 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2255 EraseTerminatorInstAndDCECond(PBI);
2259 // TODO: If BB is reachable from all paths through PredBlock, then we
2260 // could replace PBI's branch probabilities with BI's.
2262 // Copy any debug value intrinsics into the end of PredBlock.
2263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2264 if (isa<DbgInfoIntrinsic>(*I))
2265 I->clone()->insertBefore(PBI);
2272 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2273 /// predecessor of another block, this function tries to simplify it. We know
2274 /// that PBI and BI are both conditional branches, and BI is in one of the
2275 /// successor blocks of PBI - PBI branches to BI.
2276 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2277 assert(PBI->isConditional() && BI->isConditional());
2278 BasicBlock *BB = BI->getParent();
2280 // If this block ends with a branch instruction, and if there is a
2281 // predecessor that ends on a branch of the same condition, make
2282 // this conditional branch redundant.
2283 if (PBI->getCondition() == BI->getCondition() &&
2284 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2285 // Okay, the outcome of this conditional branch is statically
2286 // knowable. If this block had a single pred, handle specially.
2287 if (BB->getSinglePredecessor()) {
2288 // Turn this into a branch on constant.
2289 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2290 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2292 return true; // Nuke the branch on constant.
2295 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2296 // in the constant and simplify the block result. Subsequent passes of
2297 // simplifycfg will thread the block.
2298 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2299 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2300 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2301 std::distance(PB, PE),
2302 BI->getCondition()->getName() + ".pr",
2304 // Okay, we're going to insert the PHI node. Since PBI is not the only
2305 // predecessor, compute the PHI'd conditional value for all of the preds.
2306 // Any predecessor where the condition is not computable we keep symbolic.
2307 for (pred_iterator PI = PB; PI != PE; ++PI) {
2308 BasicBlock *P = *PI;
2309 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2310 PBI != BI && PBI->isConditional() &&
2311 PBI->getCondition() == BI->getCondition() &&
2312 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2313 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2314 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2317 NewPN->addIncoming(BI->getCondition(), P);
2321 BI->setCondition(NewPN);
2326 // If this is a conditional branch in an empty block, and if any
2327 // predecessors are a conditional branch to one of our destinations,
2328 // fold the conditions into logical ops and one cond br.
2329 BasicBlock::iterator BBI = BB->begin();
2330 // Ignore dbg intrinsics.
2331 while (isa<DbgInfoIntrinsic>(BBI))
2337 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2342 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2344 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2345 PBIOp = 0, BIOp = 1;
2346 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2347 PBIOp = 1, BIOp = 0;
2348 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2353 // Check to make sure that the other destination of this branch
2354 // isn't BB itself. If so, this is an infinite loop that will
2355 // keep getting unwound.
2356 if (PBI->getSuccessor(PBIOp) == BB)
2359 // Do not perform this transformation if it would require
2360 // insertion of a large number of select instructions. For targets
2361 // without predication/cmovs, this is a big pessimization.
2363 // Also do not perform this transformation if any phi node in the common
2364 // destination block can trap when reached by BB or PBB (PR17073). In that
2365 // case, it would be unsafe to hoist the operation into a select instruction.
2367 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2368 unsigned NumPhis = 0;
2369 for (BasicBlock::iterator II = CommonDest->begin();
2370 isa<PHINode>(II); ++II, ++NumPhis) {
2371 if (NumPhis > 2) // Disable this xform.
2374 PHINode *PN = cast<PHINode>(II);
2375 Value *BIV = PN->getIncomingValueForBlock(BB);
2376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2380 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2381 Value *PBIV = PN->getIncomingValue(PBBIdx);
2382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2387 // Finally, if everything is ok, fold the branches to logical ops.
2388 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2390 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2391 << "AND: " << *BI->getParent());
2394 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2395 // branch in it, where one edge (OtherDest) goes back to itself but the other
2396 // exits. We don't *know* that the program avoids the infinite loop
2397 // (even though that seems likely). If we do this xform naively, we'll end up
2398 // recursively unpeeling the loop. Since we know that (after the xform is
2399 // done) that the block *is* infinite if reached, we just make it an obviously
2400 // infinite loop with no cond branch.
2401 if (OtherDest == BB) {
2402 // Insert it at the end of the function, because it's either code,
2403 // or it won't matter if it's hot. :)
2404 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2405 "infloop", BB->getParent());
2406 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2407 OtherDest = InfLoopBlock;
2410 DEBUG(dbgs() << *PBI->getParent()->getParent());
2412 // BI may have other predecessors. Because of this, we leave
2413 // it alone, but modify PBI.
2415 // Make sure we get to CommonDest on True&True directions.
2416 Value *PBICond = PBI->getCondition();
2417 IRBuilder<true, NoFolder> Builder(PBI);
2419 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2421 Value *BICond = BI->getCondition();
2423 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2425 // Merge the conditions.
2426 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2428 // Modify PBI to branch on the new condition to the new dests.
2429 PBI->setCondition(Cond);
2430 PBI->setSuccessor(0, CommonDest);
2431 PBI->setSuccessor(1, OtherDest);
2433 // Update branch weight for PBI.
2434 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2435 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2437 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2439 if (PredHasWeights && SuccHasWeights) {
2440 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2441 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2442 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2443 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2444 // The weight to CommonDest should be PredCommon * SuccTotal +
2445 // PredOther * SuccCommon.
2446 // The weight to OtherDest should be PredOther * SuccOther.
2447 SmallVector<uint64_t, 2> NewWeights;
2448 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2449 PredOther * SuccCommon);
2450 NewWeights.push_back(PredOther * SuccOther);
2451 // Halve the weights if any of them cannot fit in an uint32_t
2452 FitWeights(NewWeights);
2454 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2455 PBI->setMetadata(LLVMContext::MD_prof,
2456 MDBuilder(BI->getContext()).
2457 createBranchWeights(MDWeights));
2460 // OtherDest may have phi nodes. If so, add an entry from PBI's
2461 // block that are identical to the entries for BI's block.
2462 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2464 // We know that the CommonDest already had an edge from PBI to
2465 // it. If it has PHIs though, the PHIs may have different
2466 // entries for BB and PBI's BB. If so, insert a select to make
2469 for (BasicBlock::iterator II = CommonDest->begin();
2470 (PN = dyn_cast<PHINode>(II)); ++II) {
2471 Value *BIV = PN->getIncomingValueForBlock(BB);
2472 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2473 Value *PBIV = PN->getIncomingValue(PBBIdx);
2475 // Insert a select in PBI to pick the right value.
2476 Value *NV = cast<SelectInst>
2477 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2478 PN->setIncomingValue(PBBIdx, NV);
2482 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2483 DEBUG(dbgs() << *PBI->getParent()->getParent());
2485 // This basic block is probably dead. We know it has at least
2486 // one fewer predecessor.
2490 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2491 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2492 // Takes care of updating the successors and removing the old terminator.
2493 // Also makes sure not to introduce new successors by assuming that edges to
2494 // non-successor TrueBBs and FalseBBs aren't reachable.
2495 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2496 BasicBlock *TrueBB, BasicBlock *FalseBB,
2497 uint32_t TrueWeight,
2498 uint32_t FalseWeight){
2499 // Remove any superfluous successor edges from the CFG.
2500 // First, figure out which successors to preserve.
2501 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2503 BasicBlock *KeepEdge1 = TrueBB;
2504 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2506 // Then remove the rest.
2507 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2508 BasicBlock *Succ = OldTerm->getSuccessor(I);
2509 // Make sure only to keep exactly one copy of each edge.
2510 if (Succ == KeepEdge1)
2511 KeepEdge1 = nullptr;
2512 else if (Succ == KeepEdge2)
2513 KeepEdge2 = nullptr;
2515 Succ->removePredecessor(OldTerm->getParent());
2518 IRBuilder<> Builder(OldTerm);
2519 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2521 // Insert an appropriate new terminator.
2522 if (!KeepEdge1 && !KeepEdge2) {
2523 if (TrueBB == FalseBB)
2524 // We were only looking for one successor, and it was present.
2525 // Create an unconditional branch to it.
2526 Builder.CreateBr(TrueBB);
2528 // We found both of the successors we were looking for.
2529 // Create a conditional branch sharing the condition of the select.
2530 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2531 if (TrueWeight != FalseWeight)
2532 NewBI->setMetadata(LLVMContext::MD_prof,
2533 MDBuilder(OldTerm->getContext()).
2534 createBranchWeights(TrueWeight, FalseWeight));
2536 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2537 // Neither of the selected blocks were successors, so this
2538 // terminator must be unreachable.
2539 new UnreachableInst(OldTerm->getContext(), OldTerm);
2541 // One of the selected values was a successor, but the other wasn't.
2542 // Insert an unconditional branch to the one that was found;
2543 // the edge to the one that wasn't must be unreachable.
2545 // Only TrueBB was found.
2546 Builder.CreateBr(TrueBB);
2548 // Only FalseBB was found.
2549 Builder.CreateBr(FalseBB);
2552 EraseTerminatorInstAndDCECond(OldTerm);
2556 // SimplifySwitchOnSelect - Replaces
2557 // (switch (select cond, X, Y)) on constant X, Y
2558 // with a branch - conditional if X and Y lead to distinct BBs,
2559 // unconditional otherwise.
2560 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2561 // Check for constant integer values in the select.
2562 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2563 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2564 if (!TrueVal || !FalseVal)
2567 // Find the relevant condition and destinations.
2568 Value *Condition = Select->getCondition();
2569 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2570 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2572 // Get weight for TrueBB and FalseBB.
2573 uint32_t TrueWeight = 0, FalseWeight = 0;
2574 SmallVector<uint64_t, 8> Weights;
2575 bool HasWeights = HasBranchWeights(SI);
2577 GetBranchWeights(SI, Weights);
2578 if (Weights.size() == 1 + SI->getNumCases()) {
2579 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2580 getSuccessorIndex()];
2581 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2582 getSuccessorIndex()];
2586 // Perform the actual simplification.
2587 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2588 TrueWeight, FalseWeight);
2591 // SimplifyIndirectBrOnSelect - Replaces
2592 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2593 // blockaddress(@fn, BlockB)))
2595 // (br cond, BlockA, BlockB).
2596 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2597 // Check that both operands of the select are block addresses.
2598 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2599 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2603 // Extract the actual blocks.
2604 BasicBlock *TrueBB = TBA->getBasicBlock();
2605 BasicBlock *FalseBB = FBA->getBasicBlock();
2607 // Perform the actual simplification.
2608 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2612 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2613 /// instruction (a seteq/setne with a constant) as the only instruction in a
2614 /// block that ends with an uncond branch. We are looking for a very specific
2615 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2616 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2617 /// default value goes to an uncond block with a seteq in it, we get something
2620 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2622 /// %tmp = icmp eq i8 %A, 92
2625 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2627 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2628 /// the PHI, merging the third icmp into the switch.
2629 static bool TryToSimplifyUncondBranchWithICmpInIt(
2630 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2631 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
2632 BasicBlock *BB = ICI->getParent();
2634 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2636 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2638 Value *V = ICI->getOperand(0);
2639 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2641 // The pattern we're looking for is where our only predecessor is a switch on
2642 // 'V' and this block is the default case for the switch. In this case we can
2643 // fold the compared value into the switch to simplify things.
2644 BasicBlock *Pred = BB->getSinglePredecessor();
2645 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2647 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2648 if (SI->getCondition() != V)
2651 // If BB is reachable on a non-default case, then we simply know the value of
2652 // V in this block. Substitute it and constant fold the icmp instruction
2654 if (SI->getDefaultDest() != BB) {
2655 ConstantInt *VVal = SI->findCaseDest(BB);
2656 assert(VVal && "Should have a unique destination value");
2657 ICI->setOperand(0, VVal);
2659 if (Value *V = SimplifyInstruction(ICI, DL)) {
2660 ICI->replaceAllUsesWith(V);
2661 ICI->eraseFromParent();
2663 // BB is now empty, so it is likely to simplify away.
2664 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2667 // Ok, the block is reachable from the default dest. If the constant we're
2668 // comparing exists in one of the other edges, then we can constant fold ICI
2670 if (SI->findCaseValue(Cst) != SI->case_default()) {
2672 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2673 V = ConstantInt::getFalse(BB->getContext());
2675 V = ConstantInt::getTrue(BB->getContext());
2677 ICI->replaceAllUsesWith(V);
2678 ICI->eraseFromParent();
2679 // BB is now empty, so it is likely to simplify away.
2680 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2683 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2685 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2686 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2687 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2688 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2691 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2693 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2694 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2696 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2697 std::swap(DefaultCst, NewCst);
2699 // Replace ICI (which is used by the PHI for the default value) with true or
2700 // false depending on if it is EQ or NE.
2701 ICI->replaceAllUsesWith(DefaultCst);
2702 ICI->eraseFromParent();
2704 // Okay, the switch goes to this block on a default value. Add an edge from
2705 // the switch to the merge point on the compared value.
2706 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2707 BB->getParent(), BB);
2708 SmallVector<uint64_t, 8> Weights;
2709 bool HasWeights = HasBranchWeights(SI);
2711 GetBranchWeights(SI, Weights);
2712 if (Weights.size() == 1 + SI->getNumCases()) {
2713 // Split weight for default case to case for "Cst".
2714 Weights[0] = (Weights[0]+1) >> 1;
2715 Weights.push_back(Weights[0]);
2717 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2718 SI->setMetadata(LLVMContext::MD_prof,
2719 MDBuilder(SI->getContext()).
2720 createBranchWeights(MDWeights));
2723 SI->addCase(Cst, NewBB);
2725 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2726 Builder.SetInsertPoint(NewBB);
2727 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2728 Builder.CreateBr(SuccBlock);
2729 PHIUse->addIncoming(NewCst, NewBB);
2733 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2734 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2735 /// fold it into a switch instruction if so.
2736 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2737 IRBuilder<> &Builder) {
2738 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2739 if (!Cond) return false;
2742 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2743 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2744 // 'setne's and'ed together, collect them.
2745 Value *CompVal = nullptr;
2746 std::vector<ConstantInt*> Values;
2747 bool TrueWhenEqual = true;
2748 Value *ExtraCase = nullptr;
2749 unsigned UsedICmps = 0;
2751 if (Cond->getOpcode() == Instruction::Or) {
2752 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
2754 } else if (Cond->getOpcode() == Instruction::And) {
2755 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
2757 TrueWhenEqual = false;
2760 // If we didn't have a multiply compared value, fail.
2761 if (!CompVal) return false;
2763 // Avoid turning single icmps into a switch.
2767 // There might be duplicate constants in the list, which the switch
2768 // instruction can't handle, remove them now.
2769 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2770 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2772 // If Extra was used, we require at least two switch values to do the
2773 // transformation. A switch with one value is just an cond branch.
2774 if (ExtraCase && Values.size() < 2) return false;
2776 // TODO: Preserve branch weight metadata, similarly to how
2777 // FoldValueComparisonIntoPredecessors preserves it.
2779 // Figure out which block is which destination.
2780 BasicBlock *DefaultBB = BI->getSuccessor(1);
2781 BasicBlock *EdgeBB = BI->getSuccessor(0);
2782 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2784 BasicBlock *BB = BI->getParent();
2786 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2787 << " cases into SWITCH. BB is:\n" << *BB);
2789 // If there are any extra values that couldn't be folded into the switch
2790 // then we evaluate them with an explicit branch first. Split the block
2791 // right before the condbr to handle it.
2793 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2794 // Remove the uncond branch added to the old block.
2795 TerminatorInst *OldTI = BB->getTerminator();
2796 Builder.SetInsertPoint(OldTI);
2799 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2801 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2803 OldTI->eraseFromParent();
2805 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2806 // for the edge we just added.
2807 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2809 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2810 << "\nEXTRABB = " << *BB);
2814 Builder.SetInsertPoint(BI);
2815 // Convert pointer to int before we switch.
2816 if (CompVal->getType()->isPointerTy()) {
2817 assert(DL && "Cannot switch on pointer without DataLayout");
2818 CompVal = Builder.CreatePtrToInt(CompVal,
2819 DL->getIntPtrType(CompVal->getType()),
2823 // Create the new switch instruction now.
2824 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2826 // Add all of the 'cases' to the switch instruction.
2827 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2828 New->addCase(Values[i], EdgeBB);
2830 // We added edges from PI to the EdgeBB. As such, if there were any
2831 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2832 // the number of edges added.
2833 for (BasicBlock::iterator BBI = EdgeBB->begin();
2834 isa<PHINode>(BBI); ++BBI) {
2835 PHINode *PN = cast<PHINode>(BBI);
2836 Value *InVal = PN->getIncomingValueForBlock(BB);
2837 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2838 PN->addIncoming(InVal, BB);
2841 // Erase the old branch instruction.
2842 EraseTerminatorInstAndDCECond(BI);
2844 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2848 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2849 // If this is a trivial landing pad that just continues unwinding the caught
2850 // exception then zap the landing pad, turning its invokes into calls.
2851 BasicBlock *BB = RI->getParent();
2852 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2853 if (RI->getValue() != LPInst)
2854 // Not a landing pad, or the resume is not unwinding the exception that
2855 // caused control to branch here.
2858 // Check that there are no other instructions except for debug intrinsics.
2859 BasicBlock::iterator I = LPInst, E = RI;
2861 if (!isa<DbgInfoIntrinsic>(I))
2864 // Turn all invokes that unwind here into calls and delete the basic block.
2865 bool InvokeRequiresTableEntry = false;
2866 bool Changed = false;
2867 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2868 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2870 if (II->hasFnAttr(Attribute::UWTable)) {
2871 // Don't remove an `invoke' instruction if the ABI requires an entry into
2873 InvokeRequiresTableEntry = true;
2877 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2879 // Insert a call instruction before the invoke.
2880 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2882 Call->setCallingConv(II->getCallingConv());
2883 Call->setAttributes(II->getAttributes());
2884 Call->setDebugLoc(II->getDebugLoc());
2886 // Anything that used the value produced by the invoke instruction now uses
2887 // the value produced by the call instruction. Note that we do this even
2888 // for void functions and calls with no uses so that the callgraph edge is
2890 II->replaceAllUsesWith(Call);
2891 BB->removePredecessor(II->getParent());
2893 // Insert a branch to the normal destination right before the invoke.
2894 BranchInst::Create(II->getNormalDest(), II);
2896 // Finally, delete the invoke instruction!
2897 II->eraseFromParent();
2901 if (!InvokeRequiresTableEntry)
2902 // The landingpad is now unreachable. Zap it.
2903 BB->eraseFromParent();
2908 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2909 BasicBlock *BB = RI->getParent();
2910 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2912 // Find predecessors that end with branches.
2913 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2914 SmallVector<BranchInst*, 8> CondBranchPreds;
2915 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2916 BasicBlock *P = *PI;
2917 TerminatorInst *PTI = P->getTerminator();
2918 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2919 if (BI->isUnconditional())
2920 UncondBranchPreds.push_back(P);
2922 CondBranchPreds.push_back(BI);
2926 // If we found some, do the transformation!
2927 if (!UncondBranchPreds.empty() && DupRet) {
2928 while (!UncondBranchPreds.empty()) {
2929 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2930 DEBUG(dbgs() << "FOLDING: " << *BB
2931 << "INTO UNCOND BRANCH PRED: " << *Pred);
2932 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2935 // If we eliminated all predecessors of the block, delete the block now.
2936 if (pred_begin(BB) == pred_end(BB))
2937 // We know there are no successors, so just nuke the block.
2938 BB->eraseFromParent();
2943 // Check out all of the conditional branches going to this return
2944 // instruction. If any of them just select between returns, change the
2945 // branch itself into a select/return pair.
2946 while (!CondBranchPreds.empty()) {
2947 BranchInst *BI = CondBranchPreds.pop_back_val();
2949 // Check to see if the non-BB successor is also a return block.
2950 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2951 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2952 SimplifyCondBranchToTwoReturns(BI, Builder))
2958 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2959 BasicBlock *BB = UI->getParent();
2961 bool Changed = false;
2963 // If there are any instructions immediately before the unreachable that can
2964 // be removed, do so.
2965 while (UI != BB->begin()) {
2966 BasicBlock::iterator BBI = UI;
2968 // Do not delete instructions that can have side effects which might cause
2969 // the unreachable to not be reachable; specifically, calls and volatile
2970 // operations may have this effect.
2971 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2973 if (BBI->mayHaveSideEffects()) {
2974 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2975 if (SI->isVolatile())
2977 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2978 if (LI->isVolatile())
2980 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2981 if (RMWI->isVolatile())
2983 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2984 if (CXI->isVolatile())
2986 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2987 !isa<LandingPadInst>(BBI)) {
2990 // Note that deleting LandingPad's here is in fact okay, although it
2991 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2992 // all the predecessors of this block will be the unwind edges of Invokes,
2993 // and we can therefore guarantee this block will be erased.
2996 // Delete this instruction (any uses are guaranteed to be dead)
2997 if (!BBI->use_empty())
2998 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2999 BBI->eraseFromParent();
3003 // If the unreachable instruction is the first in the block, take a gander
3004 // at all of the predecessors of this instruction, and simplify them.
3005 if (&BB->front() != UI) return Changed;
3007 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3008 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3009 TerminatorInst *TI = Preds[i]->getTerminator();
3010 IRBuilder<> Builder(TI);
3011 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3012 if (BI->isUnconditional()) {
3013 if (BI->getSuccessor(0) == BB) {
3014 new UnreachableInst(TI->getContext(), TI);
3015 TI->eraseFromParent();
3019 if (BI->getSuccessor(0) == BB) {
3020 Builder.CreateBr(BI->getSuccessor(1));
3021 EraseTerminatorInstAndDCECond(BI);
3022 } else if (BI->getSuccessor(1) == BB) {
3023 Builder.CreateBr(BI->getSuccessor(0));
3024 EraseTerminatorInstAndDCECond(BI);
3028 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3029 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3031 if (i.getCaseSuccessor() == BB) {
3032 BB->removePredecessor(SI->getParent());
3037 // If the default value is unreachable, figure out the most popular
3038 // destination and make it the default.
3039 if (SI->getDefaultDest() == BB) {
3040 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3041 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3043 std::pair<unsigned, unsigned> &entry =
3044 Popularity[i.getCaseSuccessor()];
3045 if (entry.first == 0) {
3047 entry.second = i.getCaseIndex();
3053 // Find the most popular block.
3054 unsigned MaxPop = 0;
3055 unsigned MaxIndex = 0;
3056 BasicBlock *MaxBlock = nullptr;
3057 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3058 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3059 if (I->second.first > MaxPop ||
3060 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3061 MaxPop = I->second.first;
3062 MaxIndex = I->second.second;
3063 MaxBlock = I->first;
3067 // Make this the new default, allowing us to delete any explicit
3069 SI->setDefaultDest(MaxBlock);
3072 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3074 if (isa<PHINode>(MaxBlock->begin()))
3075 for (unsigned i = 0; i != MaxPop-1; ++i)
3076 MaxBlock->removePredecessor(SI->getParent());
3078 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3080 if (i.getCaseSuccessor() == MaxBlock) {
3086 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3087 if (II->getUnwindDest() == BB) {
3088 // Convert the invoke to a call instruction. This would be a good
3089 // place to note that the call does not throw though.
3090 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3091 II->removeFromParent(); // Take out of symbol table
3093 // Insert the call now...
3094 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3095 Builder.SetInsertPoint(BI);
3096 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3097 Args, II->getName());
3098 CI->setCallingConv(II->getCallingConv());
3099 CI->setAttributes(II->getAttributes());
3100 // If the invoke produced a value, the call does now instead.
3101 II->replaceAllUsesWith(CI);
3108 // If this block is now dead, remove it.
3109 if (pred_begin(BB) == pred_end(BB) &&
3110 BB != &BB->getParent()->getEntryBlock()) {
3111 // We know there are no successors, so just nuke the block.
3112 BB->eraseFromParent();
3119 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3120 /// integer range comparison into a sub, an icmp and a branch.
3121 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3122 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3124 // Make sure all cases point to the same destination and gather the values.
3125 SmallVector<ConstantInt *, 16> Cases;
3126 SwitchInst::CaseIt I = SI->case_begin();
3127 Cases.push_back(I.getCaseValue());
3128 SwitchInst::CaseIt PrevI = I++;
3129 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3130 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3132 Cases.push_back(I.getCaseValue());
3134 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3136 // Sort the case values, then check if they form a range we can transform.
3137 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3138 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3139 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3143 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3144 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3146 Value *Sub = SI->getCondition();
3147 if (!Offset->isNullValue())
3148 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3150 // If NumCases overflowed, then all possible values jump to the successor.
3151 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3152 Cmp = ConstantInt::getTrue(SI->getContext());
3154 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3155 BranchInst *NewBI = Builder.CreateCondBr(
3156 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3158 // Update weight for the newly-created conditional branch.
3159 SmallVector<uint64_t, 8> Weights;
3160 bool HasWeights = HasBranchWeights(SI);
3162 GetBranchWeights(SI, Weights);
3163 if (Weights.size() == 1 + SI->getNumCases()) {
3164 // Combine all weights for the cases to be the true weight of NewBI.
3165 // We assume that the sum of all weights for a Terminator can fit into 32
3167 uint32_t NewTrueWeight = 0;
3168 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3169 NewTrueWeight += (uint32_t)Weights[I];
3170 NewBI->setMetadata(LLVMContext::MD_prof,
3171 MDBuilder(SI->getContext()).
3172 createBranchWeights(NewTrueWeight,
3173 (uint32_t)Weights[0]));
3177 // Prune obsolete incoming values off the successor's PHI nodes.
3178 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3179 isa<PHINode>(BBI); ++BBI) {
3180 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3181 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3183 SI->eraseFromParent();
3188 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3189 /// and use it to remove dead cases.
3190 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3191 AssumptionTracker *AT) {
3192 Value *Cond = SI->getCondition();
3193 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3194 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3195 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3197 // Gather dead cases.
3198 SmallVector<ConstantInt*, 8> DeadCases;
3199 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3200 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3201 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3202 DeadCases.push_back(I.getCaseValue());
3203 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3204 << I.getCaseValue() << "' is dead.\n");
3208 SmallVector<uint64_t, 8> Weights;
3209 bool HasWeight = HasBranchWeights(SI);
3211 GetBranchWeights(SI, Weights);
3212 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3215 // Remove dead cases from the switch.
3216 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3217 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3218 assert(Case != SI->case_default() &&
3219 "Case was not found. Probably mistake in DeadCases forming.");
3221 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3225 // Prune unused values from PHI nodes.
3226 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3227 SI->removeCase(Case);
3229 if (HasWeight && Weights.size() >= 2) {
3230 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3231 SI->setMetadata(LLVMContext::MD_prof,
3232 MDBuilder(SI->getParent()->getContext()).
3233 createBranchWeights(MDWeights));
3236 return !DeadCases.empty();
3239 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3240 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3241 /// by an unconditional branch), look at the phi node for BB in the successor
3242 /// block and see if the incoming value is equal to CaseValue. If so, return
3243 /// the phi node, and set PhiIndex to BB's index in the phi node.
3244 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3247 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3248 return nullptr; // BB must be empty to be a candidate for simplification.
3249 if (!BB->getSinglePredecessor())
3250 return nullptr; // BB must be dominated by the switch.
3252 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3253 if (!Branch || !Branch->isUnconditional())
3254 return nullptr; // Terminator must be unconditional branch.
3256 BasicBlock *Succ = Branch->getSuccessor(0);
3258 BasicBlock::iterator I = Succ->begin();
3259 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3260 int Idx = PHI->getBasicBlockIndex(BB);
3261 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3263 Value *InValue = PHI->getIncomingValue(Idx);
3264 if (InValue != CaseValue) continue;
3273 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3274 /// instruction to a phi node dominated by the switch, if that would mean that
3275 /// some of the destination blocks of the switch can be folded away.
3276 /// Returns true if a change is made.
3277 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3278 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3279 ForwardingNodesMap ForwardingNodes;
3281 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3282 ConstantInt *CaseValue = I.getCaseValue();
3283 BasicBlock *CaseDest = I.getCaseSuccessor();
3286 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3290 ForwardingNodes[PHI].push_back(PhiIndex);
3293 bool Changed = false;
3295 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3296 E = ForwardingNodes.end(); I != E; ++I) {
3297 PHINode *Phi = I->first;
3298 SmallVectorImpl<int> &Indexes = I->second;
3300 if (Indexes.size() < 2) continue;
3302 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3303 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3310 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3311 /// initializing an array of constants like C.
3312 static bool ValidLookupTableConstant(Constant *C) {
3313 if (C->isThreadDependent())
3315 if (C->isDLLImportDependent())
3318 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3319 return CE->isGEPWithNoNotionalOverIndexing();
3321 return isa<ConstantFP>(C) ||
3322 isa<ConstantInt>(C) ||
3323 isa<ConstantPointerNull>(C) ||
3324 isa<GlobalValue>(C) ||
3328 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3329 /// its constant value in ConstantPool, returning 0 if it's not there.
3330 static Constant *LookupConstant(Value *V,
3331 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3332 if (Constant *C = dyn_cast<Constant>(V))
3334 return ConstantPool.lookup(V);
3337 /// ConstantFold - Try to fold instruction I into a constant. This works for
3338 /// simple instructions such as binary operations where both operands are
3339 /// constant or can be replaced by constants from the ConstantPool. Returns the
3340 /// resulting constant on success, 0 otherwise.
3342 ConstantFold(Instruction *I,
3343 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3344 const DataLayout *DL) {
3345 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3346 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3349 if (A->isAllOnesValue())
3350 return LookupConstant(Select->getTrueValue(), ConstantPool);
3351 if (A->isNullValue())
3352 return LookupConstant(Select->getFalseValue(), ConstantPool);
3356 SmallVector<Constant *, 4> COps;
3357 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3358 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3364 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3365 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3368 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3371 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3372 /// at the common destination basic block, *CommonDest, for one of the case
3373 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3374 /// case), of a switch instruction SI.
3376 GetCaseResults(SwitchInst *SI,
3377 ConstantInt *CaseVal,
3378 BasicBlock *CaseDest,
3379 BasicBlock **CommonDest,
3380 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3381 const DataLayout *DL) {
3382 // The block from which we enter the common destination.
3383 BasicBlock *Pred = SI->getParent();
3385 // If CaseDest is empty except for some side-effect free instructions through
3386 // which we can constant-propagate the CaseVal, continue to its successor.
3387 SmallDenseMap<Value*, Constant*> ConstantPool;
3388 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3389 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3391 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3392 // If the terminator is a simple branch, continue to the next block.
3393 if (T->getNumSuccessors() != 1)
3396 CaseDest = T->getSuccessor(0);
3397 } else if (isa<DbgInfoIntrinsic>(I)) {
3398 // Skip debug intrinsic.
3400 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3401 // Instruction is side-effect free and constant.
3402 ConstantPool.insert(std::make_pair(I, C));
3408 // If we did not have a CommonDest before, use the current one.
3410 *CommonDest = CaseDest;
3411 // If the destination isn't the common one, abort.
3412 if (CaseDest != *CommonDest)
3415 // Get the values for this case from phi nodes in the destination block.
3416 BasicBlock::iterator I = (*CommonDest)->begin();
3417 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3418 int Idx = PHI->getBasicBlockIndex(Pred);
3422 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3427 // Note: If the constant comes from constant-propagating the case value
3428 // through the CaseDest basic block, it will be safe to remove the
3429 // instructions in that block. They cannot be used (except in the phi nodes
3430 // we visit) outside CaseDest, because that block does not dominate its
3431 // successor. If it did, we would not be in this phi node.
3433 // Be conservative about which kinds of constants we support.
3434 if (!ValidLookupTableConstant(ConstVal))
3437 Res.push_back(std::make_pair(PHI, ConstVal));
3440 return Res.size() > 0;
3444 /// SwitchLookupTable - This class represents a lookup table that can be used
3445 /// to replace a switch.
3446 class SwitchLookupTable {
3448 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3449 /// with the contents of Values, using DefaultValue to fill any holes in the
3451 SwitchLookupTable(Module &M,
3453 ConstantInt *Offset,
3454 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3455 Constant *DefaultValue,
3456 const DataLayout *DL);
3458 /// BuildLookup - Build instructions with Builder to retrieve the value at
3459 /// the position given by Index in the lookup table.
3460 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3462 /// WouldFitInRegister - Return true if a table with TableSize elements of
3463 /// type ElementType would fit in a target-legal register.
3464 static bool WouldFitInRegister(const DataLayout *DL,
3466 const Type *ElementType);
3469 // Depending on the contents of the table, it can be represented in
3472 // For tables where each element contains the same value, we just have to
3473 // store that single value and return it for each lookup.
3476 // For small tables with integer elements, we can pack them into a bitmap
3477 // that fits into a target-legal register. Values are retrieved by
3478 // shift and mask operations.
3481 // The table is stored as an array of values. Values are retrieved by load
3482 // instructions from the table.
3486 // For SingleValueKind, this is the single value.
3487 Constant *SingleValue;
3489 // For BitMapKind, this is the bitmap.
3490 ConstantInt *BitMap;
3491 IntegerType *BitMapElementTy;
3493 // For ArrayKind, this is the array.
3494 GlobalVariable *Array;
3498 SwitchLookupTable::SwitchLookupTable(Module &M,
3500 ConstantInt *Offset,
3501 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3502 Constant *DefaultValue,
3503 const DataLayout *DL)
3504 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3506 assert(Values.size() && "Can't build lookup table without values!");
3507 assert(TableSize >= Values.size() && "Can't fit values in table!");
3509 // If all values in the table are equal, this is that value.
3510 SingleValue = Values.begin()->second;
3512 Type *ValueType = Values.begin()->second->getType();
3514 // Build up the table contents.
3515 SmallVector<Constant*, 64> TableContents(TableSize);
3516 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3517 ConstantInt *CaseVal = Values[I].first;
3518 Constant *CaseRes = Values[I].second;
3519 assert(CaseRes->getType() == ValueType);
3521 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3523 TableContents[Idx] = CaseRes;
3525 if (CaseRes != SingleValue)
3526 SingleValue = nullptr;
3529 // Fill in any holes in the table with the default result.
3530 if (Values.size() < TableSize) {
3531 assert(DefaultValue &&
3532 "Need a default value to fill the lookup table holes.");
3533 assert(DefaultValue->getType() == ValueType);
3534 for (uint64_t I = 0; I < TableSize; ++I) {
3535 if (!TableContents[I])
3536 TableContents[I] = DefaultValue;
3539 if (DefaultValue != SingleValue)
3540 SingleValue = nullptr;
3543 // If each element in the table contains the same value, we only need to store
3544 // that single value.
3546 Kind = SingleValueKind;
3550 // If the type is integer and the table fits in a register, build a bitmap.
3551 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3552 IntegerType *IT = cast<IntegerType>(ValueType);
3553 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3554 for (uint64_t I = TableSize; I > 0; --I) {
3555 TableInt <<= IT->getBitWidth();
3556 // Insert values into the bitmap. Undef values are set to zero.
3557 if (!isa<UndefValue>(TableContents[I - 1])) {
3558 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3559 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3562 BitMap = ConstantInt::get(M.getContext(), TableInt);
3563 BitMapElementTy = IT;
3569 // Store the table in an array.
3570 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3571 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3573 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3574 GlobalVariable::PrivateLinkage,
3577 Array->setUnnamedAddr(true);
3581 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3583 case SingleValueKind:
3586 // Type of the bitmap (e.g. i59).
3587 IntegerType *MapTy = BitMap->getType();
3589 // Cast Index to the same type as the bitmap.
3590 // Note: The Index is <= the number of elements in the table, so
3591 // truncating it to the width of the bitmask is safe.
3592 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3594 // Multiply the shift amount by the element width.
3595 ShiftAmt = Builder.CreateMul(ShiftAmt,
3596 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3600 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3601 "switch.downshift");
3603 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3607 // Make sure the table index will not overflow when treated as signed.
3608 IntegerType *IT = cast<IntegerType>(Index->getType());
3609 uint64_t TableSize = Array->getInitializer()->getType()
3610 ->getArrayNumElements();
3611 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3612 Index = Builder.CreateZExt(Index,
3613 IntegerType::get(IT->getContext(),
3614 IT->getBitWidth() + 1),
3615 "switch.tableidx.zext");
3617 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3618 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3620 return Builder.CreateLoad(GEP, "switch.load");
3623 llvm_unreachable("Unknown lookup table kind!");
3626 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3628 const Type *ElementType) {
3631 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3634 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3635 // are <= 15, we could try to narrow the type.
3637 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3638 if (TableSize >= UINT_MAX/IT->getBitWidth())
3640 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3643 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3644 /// for this switch, based on the number of cases, size of the table and the
3645 /// types of the results.
3646 static bool ShouldBuildLookupTable(SwitchInst *SI,
3648 const TargetTransformInfo &TTI,
3649 const DataLayout *DL,
3650 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3651 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3652 return false; // TableSize overflowed, or mul below might overflow.
3654 bool AllTablesFitInRegister = true;
3655 bool HasIllegalType = false;
3656 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3657 E = ResultTypes.end(); I != E; ++I) {
3658 Type *Ty = I->second;
3660 // Saturate this flag to true.
3661 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3663 // Saturate this flag to false.
3664 AllTablesFitInRegister = AllTablesFitInRegister &&
3665 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3667 // If both flags saturate, we're done. NOTE: This *only* works with
3668 // saturating flags, and all flags have to saturate first due to the
3669 // non-deterministic behavior of iterating over a dense map.
3670 if (HasIllegalType && !AllTablesFitInRegister)
3674 // If each table would fit in a register, we should build it anyway.
3675 if (AllTablesFitInRegister)
3678 // Don't build a table that doesn't fit in-register if it has illegal types.
3682 // The table density should be at least 40%. This is the same criterion as for
3683 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3684 // FIXME: Find the best cut-off.
3685 return SI->getNumCases() * 10 >= TableSize * 4;
3688 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3689 /// phi nodes in a common successor block with different constant values,
3690 /// replace the switch with lookup tables.
3691 static bool SwitchToLookupTable(SwitchInst *SI,
3692 IRBuilder<> &Builder,
3693 const TargetTransformInfo &TTI,
3694 const DataLayout* DL) {
3695 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3697 // Only build lookup table when we have a target that supports it.
3698 if (!TTI.shouldBuildLookupTables())
3701 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3702 // split off a dense part and build a lookup table for that.
3704 // FIXME: This creates arrays of GEPs to constant strings, which means each
3705 // GEP needs a runtime relocation in PIC code. We should just build one big
3706 // string and lookup indices into that.
3708 // Ignore switches with less than three cases. Lookup tables will not make them
3709 // faster, so we don't analyze them.
3710 if (SI->getNumCases() < 3)
3713 // Figure out the corresponding result for each case value and phi node in the
3714 // common destination, as well as the the min and max case values.
3715 assert(SI->case_begin() != SI->case_end());
3716 SwitchInst::CaseIt CI = SI->case_begin();
3717 ConstantInt *MinCaseVal = CI.getCaseValue();
3718 ConstantInt *MaxCaseVal = CI.getCaseValue();
3720 BasicBlock *CommonDest = nullptr;
3721 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3722 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3723 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3724 SmallDenseMap<PHINode*, Type*> ResultTypes;
3725 SmallVector<PHINode*, 4> PHIs;
3727 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3728 ConstantInt *CaseVal = CI.getCaseValue();
3729 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3730 MinCaseVal = CaseVal;
3731 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3732 MaxCaseVal = CaseVal;
3734 // Resulting value at phi nodes for this case value.
3735 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3737 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3741 // Append the result from this case to the list for each phi.
3742 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3743 if (!ResultLists.count(I->first))
3744 PHIs.push_back(I->first);
3745 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3749 // Keep track of the result types.
3750 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3751 PHINode *PHI = PHIs[I];
3752 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3755 uint64_t NumResults = ResultLists[PHIs[0]].size();
3756 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3757 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3758 bool TableHasHoles = (NumResults < TableSize);
3760 // If the table has holes, we need a constant result for the default case
3761 // or a bitmask that fits in a register.
3762 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3763 bool HasDefaultResults = false;
3764 if (TableHasHoles) {
3765 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3766 &CommonDest, DefaultResultsList, DL);
3768 bool NeedMask = (TableHasHoles && !HasDefaultResults);
3770 // As an extra penalty for the validity test we require more cases.
3771 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
3773 if (!(DL && DL->fitsInLegalInteger(TableSize)))
3777 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3778 PHINode *PHI = DefaultResultsList[I].first;
3779 Constant *Result = DefaultResultsList[I].second;
3780 DefaultResults[PHI] = Result;
3783 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
3786 // Create the BB that does the lookups.
3787 Module &Mod = *CommonDest->getParent()->getParent();
3788 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3790 CommonDest->getParent(),
3793 // Compute the table index value.
3794 Builder.SetInsertPoint(SI);
3795 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3798 // Compute the maximum table size representable by the integer type we are
3800 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
3801 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
3802 assert(MaxTableSize >= TableSize &&
3803 "It is impossible for a switch to have more entries than the max "
3804 "representable value of its input integer type's size.");
3806 // If we have a fully covered lookup table, unconditionally branch to the
3807 // lookup table BB. Otherwise, check if the condition value is within the case
3808 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3810 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3811 if (GeneratingCoveredLookupTable) {
3812 Builder.CreateBr(LookupBB);
3813 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
3814 // do not delete PHINodes here.
3815 SI->getDefaultDest()->removePredecessor(SI->getParent(),
3816 true/*DontDeleteUselessPHIs*/);
3818 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3819 MinCaseVal->getType(), TableSize));
3820 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3823 // Populate the BB that does the lookups.
3824 Builder.SetInsertPoint(LookupBB);
3827 // Before doing the lookup we do the hole check.
3828 // The LookupBB is therefore re-purposed to do the hole check
3829 // and we create a new LookupBB.
3830 BasicBlock *MaskBB = LookupBB;
3831 MaskBB->setName("switch.hole_check");
3832 LookupBB = BasicBlock::Create(Mod.getContext(),
3834 CommonDest->getParent(),
3837 // Build bitmask; fill in a 1 bit for every case.
3838 APInt MaskInt(TableSize, 0);
3839 APInt One(TableSize, 1);
3840 const ResultListTy &ResultList = ResultLists[PHIs[0]];
3841 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3842 uint64_t Idx = (ResultList[I].first->getValue() -
3843 MinCaseVal->getValue()).getLimitedValue();
3844 MaskInt |= One << Idx;
3846 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3848 // Get the TableIndex'th bit of the bitmask.
3849 // If this bit is 0 (meaning hole) jump to the default destination,
3850 // else continue with table lookup.
3851 IntegerType *MapTy = TableMask->getType();
3852 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3853 "switch.maskindex");
3854 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3856 Value *LoBit = Builder.CreateTrunc(Shifted,
3857 Type::getInt1Ty(Mod.getContext()),
3859 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3861 Builder.SetInsertPoint(LookupBB);
3862 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3865 bool ReturnedEarly = false;
3866 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3867 PHINode *PHI = PHIs[I];
3869 // If using a bitmask, use any value to fill the lookup table holes.
3870 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
3871 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3874 Value *Result = Table.BuildLookup(TableIndex, Builder);
3876 // If the result is used to return immediately from the function, we want to
3877 // do that right here.
3878 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3879 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
3880 Builder.CreateRet(Result);
3881 ReturnedEarly = true;
3885 PHI->addIncoming(Result, LookupBB);
3889 Builder.CreateBr(CommonDest);
3891 // Remove the switch.
3892 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3893 BasicBlock *Succ = SI->getSuccessor(i);
3895 if (Succ == SI->getDefaultDest())
3897 Succ->removePredecessor(SI->getParent());
3899 SI->eraseFromParent();
3903 ++NumLookupTablesHoles;
3907 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3908 BasicBlock *BB = SI->getParent();
3910 if (isValueEqualityComparison(SI)) {
3911 // If we only have one predecessor, and if it is a branch on this value,
3912 // see if that predecessor totally determines the outcome of this switch.
3913 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3914 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3915 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3917 Value *Cond = SI->getCondition();
3918 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3919 if (SimplifySwitchOnSelect(SI, Select))
3920 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3922 // If the block only contains the switch, see if we can fold the block
3923 // away into any preds.
3924 BasicBlock::iterator BBI = BB->begin();
3925 // Ignore dbg intrinsics.
3926 while (isa<DbgInfoIntrinsic>(BBI))
3929 if (FoldValueComparisonIntoPredecessors(SI, Builder))
3930 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3933 // Try to transform the switch into an icmp and a branch.
3934 if (TurnSwitchRangeIntoICmp(SI, Builder))
3935 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3937 // Remove unreachable cases.
3938 if (EliminateDeadSwitchCases(SI, DL, AT))
3939 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3941 if (ForwardSwitchConditionToPHI(SI))
3942 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3944 if (SwitchToLookupTable(SI, Builder, TTI, DL))
3945 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3950 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3951 BasicBlock *BB = IBI->getParent();
3952 bool Changed = false;
3954 // Eliminate redundant destinations.
3955 SmallPtrSet<Value *, 8> Succs;
3956 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3957 BasicBlock *Dest = IBI->getDestination(i);
3958 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3959 Dest->removePredecessor(BB);
3960 IBI->removeDestination(i);
3966 if (IBI->getNumDestinations() == 0) {
3967 // If the indirectbr has no successors, change it to unreachable.
3968 new UnreachableInst(IBI->getContext(), IBI);
3969 EraseTerminatorInstAndDCECond(IBI);
3973 if (IBI->getNumDestinations() == 1) {
3974 // If the indirectbr has one successor, change it to a direct branch.
3975 BranchInst::Create(IBI->getDestination(0), IBI);
3976 EraseTerminatorInstAndDCECond(IBI);
3980 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3981 if (SimplifyIndirectBrOnSelect(IBI, SI))
3982 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
3987 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
3988 BasicBlock *BB = BI->getParent();
3990 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3993 // If the Terminator is the only non-phi instruction, simplify the block.
3994 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
3995 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3996 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3999 // If the only instruction in the block is a seteq/setne comparison
4000 // against a constant, try to simplify the block.
4001 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4002 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4003 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4005 if (I->isTerminator() &&
4006 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4007 BonusInstThreshold, DL, AT))
4011 // If this basic block is ONLY a compare and a branch, and if a predecessor
4012 // branches to us and our successor, fold the comparison into the
4013 // predecessor and use logical operations to update the incoming value
4014 // for PHI nodes in common successor.
4015 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4016 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4021 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4022 BasicBlock *BB = BI->getParent();
4024 // Conditional branch
4025 if (isValueEqualityComparison(BI)) {
4026 // If we only have one predecessor, and if it is a branch on this value,
4027 // see if that predecessor totally determines the outcome of this
4029 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4030 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4031 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4033 // This block must be empty, except for the setcond inst, if it exists.
4034 // Ignore dbg intrinsics.
4035 BasicBlock::iterator I = BB->begin();
4036 // Ignore dbg intrinsics.
4037 while (isa<DbgInfoIntrinsic>(I))
4040 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4041 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4042 } else if (&*I == cast<Instruction>(BI->getCondition())){
4044 // Ignore dbg intrinsics.
4045 while (isa<DbgInfoIntrinsic>(I))
4047 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4048 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4052 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4053 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4056 // If this basic block is ONLY a compare and a branch, and if a predecessor
4057 // branches to us and one of our successors, fold the comparison into the
4058 // predecessor and use logical operations to pick the right destination.
4059 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4060 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4062 // We have a conditional branch to two blocks that are only reachable
4063 // from BI. We know that the condbr dominates the two blocks, so see if
4064 // there is any identical code in the "then" and "else" blocks. If so, we
4065 // can hoist it up to the branching block.
4066 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4067 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4068 if (HoistThenElseCodeToIf(BI, DL))
4069 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4071 // If Successor #1 has multiple preds, we may be able to conditionally
4072 // execute Successor #0 if it branches to Successor #1.
4073 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4074 if (Succ0TI->getNumSuccessors() == 1 &&
4075 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4076 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4077 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4079 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4080 // If Successor #0 has multiple preds, we may be able to conditionally
4081 // execute Successor #1 if it branches to Successor #0.
4082 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4083 if (Succ1TI->getNumSuccessors() == 1 &&
4084 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4085 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4086 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4089 // If this is a branch on a phi node in the current block, thread control
4090 // through this block if any PHI node entries are constants.
4091 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4092 if (PN->getParent() == BI->getParent())
4093 if (FoldCondBranchOnPHI(BI, DL))
4094 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4096 // Scan predecessor blocks for conditional branches.
4097 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4098 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4099 if (PBI != BI && PBI->isConditional())
4100 if (SimplifyCondBranchToCondBranch(PBI, BI))
4101 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4106 /// Check if passing a value to an instruction will cause undefined behavior.
4107 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4108 Constant *C = dyn_cast<Constant>(V);
4115 if (C->isNullValue()) {
4116 // Only look at the first use, avoid hurting compile time with long uselists
4117 User *Use = *I->user_begin();
4119 // Now make sure that there are no instructions in between that can alter
4120 // control flow (eg. calls)
4121 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4122 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4125 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4126 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4127 if (GEP->getPointerOperand() == I)
4128 return passingValueIsAlwaysUndefined(V, GEP);
4130 // Look through bitcasts.
4131 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4132 return passingValueIsAlwaysUndefined(V, BC);
4134 // Load from null is undefined.
4135 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4136 if (!LI->isVolatile())
4137 return LI->getPointerAddressSpace() == 0;
4139 // Store to null is undefined.
4140 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4141 if (!SI->isVolatile())
4142 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4147 /// If BB has an incoming value that will always trigger undefined behavior
4148 /// (eg. null pointer dereference), remove the branch leading here.
4149 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4150 for (BasicBlock::iterator i = BB->begin();
4151 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4152 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4153 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4154 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4155 IRBuilder<> Builder(T);
4156 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4157 BB->removePredecessor(PHI->getIncomingBlock(i));
4158 // Turn uncoditional branches into unreachables and remove the dead
4159 // destination from conditional branches.
4160 if (BI->isUnconditional())
4161 Builder.CreateUnreachable();
4163 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4164 BI->getSuccessor(0));
4165 BI->eraseFromParent();
4168 // TODO: SwitchInst.
4174 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4175 bool Changed = false;
4177 assert(BB && BB->getParent() && "Block not embedded in function!");
4178 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4180 // Remove basic blocks that have no predecessors (except the entry block)...
4181 // or that just have themself as a predecessor. These are unreachable.
4182 if ((pred_begin(BB) == pred_end(BB) &&
4183 BB != &BB->getParent()->getEntryBlock()) ||
4184 BB->getSinglePredecessor() == BB) {
4185 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4186 DeleteDeadBlock(BB);
4190 // Check to see if we can constant propagate this terminator instruction
4192 Changed |= ConstantFoldTerminator(BB, true);
4194 // Check for and eliminate duplicate PHI nodes in this block.
4195 Changed |= EliminateDuplicatePHINodes(BB);
4197 // Check for and remove branches that will always cause undefined behavior.
4198 Changed |= removeUndefIntroducingPredecessor(BB);
4200 // Merge basic blocks into their predecessor if there is only one distinct
4201 // pred, and if there is only one distinct successor of the predecessor, and
4202 // if there are no PHI nodes.
4204 if (MergeBlockIntoPredecessor(BB))
4207 IRBuilder<> Builder(BB);
4209 // If there is a trivial two-entry PHI node in this basic block, and we can
4210 // eliminate it, do so now.
4211 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4212 if (PN->getNumIncomingValues() == 2)
4213 Changed |= FoldTwoEntryPHINode(PN, DL);
4215 Builder.SetInsertPoint(BB->getTerminator());
4216 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4217 if (BI->isUnconditional()) {
4218 if (SimplifyUncondBranch(BI, Builder)) return true;
4220 if (SimplifyCondBranch(BI, Builder)) return true;
4222 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4223 if (SimplifyReturn(RI, Builder)) return true;
4224 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4225 if (SimplifyResume(RI, Builder)) return true;
4226 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4227 if (SimplifySwitch(SI, Builder)) return true;
4228 } else if (UnreachableInst *UI =
4229 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4230 if (SimplifyUnreachable(UI)) return true;
4231 } else if (IndirectBrInst *IBI =
4232 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4233 if (SimplifyIndirectBr(IBI)) return true;
4239 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4240 /// example, it adjusts branches to branches to eliminate the extra hop, it
4241 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4242 /// of the CFG. It returns true if a modification was made.
4244 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4245 unsigned BonusInstThreshold,
4246 const DataLayout *DL, AssumptionTracker *AT) {
4247 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);