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 #define DEBUG_TYPE "simplifycfg"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Type.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ConstantRange.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/IRBuilder.h"
38 #include "llvm/Support/NoFolder.h"
39 #include "llvm/Support/raw_ostream.h"
45 static cl::opt<unsigned>
46 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
47 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
50 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
51 cl::desc("Duplicate return instructions into unconditional branches"));
53 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
56 class SimplifyCFGOpt {
57 const TargetData *const TD;
59 Value *isValueEqualityComparison(TerminatorInst *TI);
60 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
61 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
62 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
64 IRBuilder<> &Builder);
65 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
66 IRBuilder<> &Builder);
68 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
69 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
70 bool SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder);
71 bool SimplifyUnreachable(UnreachableInst *UI);
72 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
73 bool SimplifyIndirectBr(IndirectBrInst *IBI);
74 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
75 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
78 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
79 bool run(BasicBlock *BB);
83 /// SafeToMergeTerminators - Return true if it is safe to merge these two
84 /// terminator instructions together.
86 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
87 if (SI1 == SI2) return false; // Can't merge with self!
89 // It is not safe to merge these two switch instructions if they have a common
90 // successor, and if that successor has a PHI node, and if *that* PHI node has
91 // conflicting incoming values from the two switch blocks.
92 BasicBlock *SI1BB = SI1->getParent();
93 BasicBlock *SI2BB = SI2->getParent();
94 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
96 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
97 if (SI1Succs.count(*I))
98 for (BasicBlock::iterator BBI = (*I)->begin();
99 isa<PHINode>(BBI); ++BBI) {
100 PHINode *PN = cast<PHINode>(BBI);
101 if (PN->getIncomingValueForBlock(SI1BB) !=
102 PN->getIncomingValueForBlock(SI2BB))
109 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
110 /// now be entries in it from the 'NewPred' block. The values that will be
111 /// flowing into the PHI nodes will be the same as those coming in from
112 /// ExistPred, an existing predecessor of Succ.
113 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
114 BasicBlock *ExistPred) {
115 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
118 for (BasicBlock::iterator I = Succ->begin();
119 (PN = dyn_cast<PHINode>(I)); ++I)
120 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
124 /// GetIfCondition - Given a basic block (BB) with two predecessors (and at
125 /// least one PHI node in it), check to see if the merge at this block is due
126 /// to an "if condition". If so, return the boolean condition that determines
127 /// which entry into BB will be taken. Also, return by references the block
128 /// that will be entered from if the condition is true, and the block that will
129 /// be entered if the condition is false.
131 /// This does no checking to see if the true/false blocks have large or unsavory
132 /// instructions in them.
133 static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
134 BasicBlock *&IfFalse) {
135 PHINode *SomePHI = cast<PHINode>(BB->begin());
136 assert(SomePHI->getNumIncomingValues() == 2 &&
137 "Function can only handle blocks with 2 predecessors!");
138 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
139 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
141 // We can only handle branches. Other control flow will be lowered to
142 // branches if possible anyway.
143 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
144 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
145 if (Pred1Br == 0 || Pred2Br == 0)
148 // Eliminate code duplication by ensuring that Pred1Br is conditional if
150 if (Pred2Br->isConditional()) {
151 // If both branches are conditional, we don't have an "if statement". In
152 // reality, we could transform this case, but since the condition will be
153 // required anyway, we stand no chance of eliminating it, so the xform is
154 // probably not profitable.
155 if (Pred1Br->isConditional())
158 std::swap(Pred1, Pred2);
159 std::swap(Pred1Br, Pred2Br);
162 if (Pred1Br->isConditional()) {
163 // The only thing we have to watch out for here is to make sure that Pred2
164 // doesn't have incoming edges from other blocks. If it does, the condition
165 // doesn't dominate BB.
166 if (Pred2->getSinglePredecessor() == 0)
169 // If we found a conditional branch predecessor, make sure that it branches
170 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
171 if (Pred1Br->getSuccessor(0) == BB &&
172 Pred1Br->getSuccessor(1) == Pred2) {
175 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
176 Pred1Br->getSuccessor(1) == BB) {
180 // We know that one arm of the conditional goes to BB, so the other must
181 // go somewhere unrelated, and this must not be an "if statement".
185 return Pred1Br->getCondition();
188 // Ok, if we got here, both predecessors end with an unconditional branch to
189 // BB. Don't panic! If both blocks only have a single (identical)
190 // predecessor, and THAT is a conditional branch, then we're all ok!
191 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
192 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
195 // Otherwise, if this is a conditional branch, then we can use it!
196 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
197 if (BI == 0) return 0;
199 assert(BI->isConditional() && "Two successors but not conditional?");
200 if (BI->getSuccessor(0) == Pred1) {
207 return BI->getCondition();
210 /// DominatesMergePoint - If we have a merge point of an "if condition" as
211 /// accepted above, return true if the specified value dominates the block. We
212 /// don't handle the true generality of domination here, just a special case
213 /// which works well enough for us.
215 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
216 /// see if V (which must be an instruction) and its recursive operands
217 /// that do not dominate BB have a combined cost lower than CostRemaining and
218 /// are non-trapping. If both are true, the instruction is inserted into the
219 /// set and true is returned.
221 /// The cost for most non-trapping instructions is defined as 1 except for
222 /// Select whose cost is 2.
224 /// After this function returns, CostRemaining is decreased by the cost of
225 /// V plus its non-dominating operands. If that cost is greater than
226 /// CostRemaining, false is returned and CostRemaining is undefined.
227 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
228 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
229 unsigned &CostRemaining) {
230 Instruction *I = dyn_cast<Instruction>(V);
232 // Non-instructions all dominate instructions, but not all constantexprs
233 // can be executed unconditionally.
234 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
239 BasicBlock *PBB = I->getParent();
241 // We don't want to allow weird loops that might have the "if condition" in
242 // the bottom of this block.
243 if (PBB == BB) return false;
245 // If this instruction is defined in a block that contains an unconditional
246 // branch to BB, then it must be in the 'conditional' part of the "if
247 // statement". If not, it definitely dominates the region.
248 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
249 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
252 // If we aren't allowing aggressive promotion anymore, then don't consider
253 // instructions in the 'if region'.
254 if (AggressiveInsts == 0) return false;
256 // If we have seen this instruction before, don't count it again.
257 if (AggressiveInsts->count(I)) return true;
259 // Okay, it looks like the instruction IS in the "condition". Check to
260 // see if it's a cheap instruction to unconditionally compute, and if it
261 // only uses stuff defined outside of the condition. If so, hoist it out.
262 if (!isSafeToSpeculativelyExecute(I))
267 switch (I->getOpcode()) {
268 default: return false; // Cannot hoist this out safely.
269 case Instruction::Load:
270 // We have to check to make sure there are no instructions before the
271 // load in its basic block, as we are going to hoist the load out to its
273 if (PBB->getFirstNonPHIOrDbg() != I)
277 case Instruction::GetElementPtr:
278 // GEPs are cheap if all indices are constant.
279 if (!cast<GetElementPtrInst>(I)->hasAllConstantIndices())
283 case Instruction::Add:
284 case Instruction::Sub:
285 case Instruction::And:
286 case Instruction::Or:
287 case Instruction::Xor:
288 case Instruction::Shl:
289 case Instruction::LShr:
290 case Instruction::AShr:
291 case Instruction::ICmp:
292 case Instruction::Trunc:
293 case Instruction::ZExt:
294 case Instruction::SExt:
296 break; // These are all cheap and non-trapping instructions.
298 case Instruction::Call:
299 case Instruction::Select:
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))
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 TargetData *TD) {
322 // Normal constant int.
323 ConstantInt *CI = dyn_cast<ConstantInt>(V);
324 if (CI || !TD || !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 = TD->getIntPtrType(V->getContext());
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 TargetData *TD, bool isEQ, unsigned &UsedICmps) {
356 Instruction *I = dyn_cast<Instruction>(V);
357 if (I == 0) return 0;
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), TD)) {
362 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
365 return I->getOperand(0);
368 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
371 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
373 // If this is an and/!= check then we want to optimize "x ugt 2" into
376 Span = Span.inverse();
378 // If there are a ton of values, we don't want to make a ginormous switch.
379 if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
380 // We don't handle wrapped sets yet.
384 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
385 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
387 return I->getOperand(0);
392 // Otherwise, we can only handle an | or &, depending on isEQ.
393 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
396 unsigned NumValsBeforeLHS = Vals.size();
397 unsigned UsedICmpsBeforeLHS = UsedICmps;
398 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
400 unsigned NumVals = Vals.size();
401 unsigned UsedICmpsBeforeRHS = UsedICmps;
402 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
406 Vals.resize(NumVals);
407 UsedICmps = UsedICmpsBeforeRHS;
410 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
411 // set it and return success.
412 if (Extra == 0 || Extra == I->getOperand(1)) {
413 Extra = I->getOperand(1);
417 Vals.resize(NumValsBeforeLHS);
418 UsedICmps = UsedICmpsBeforeLHS;
422 // If the LHS can't be folded in, but Extra is available and RHS can, try to
424 if (Extra == 0 || Extra == I->getOperand(0)) {
425 Value *OldExtra = Extra;
426 Extra = I->getOperand(0);
427 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
430 assert(Vals.size() == NumValsBeforeLHS);
437 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
438 Instruction *Cond = 0;
439 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
440 Cond = dyn_cast<Instruction>(SI->getCondition());
441 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
442 if (BI->isConditional())
443 Cond = dyn_cast<Instruction>(BI->getCondition());
444 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
445 Cond = dyn_cast<Instruction>(IBI->getAddress());
448 TI->eraseFromParent();
449 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
452 /// isValueEqualityComparison - Return true if the specified terminator checks
453 /// to see if a value is equal to constant integer value.
454 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
456 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
457 // Do not permit merging of large switch instructions into their
458 // predecessors unless there is only one predecessor.
459 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
460 pred_end(SI->getParent())) <= 128)
461 CV = SI->getCondition();
462 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
463 if (BI->isConditional() && BI->getCondition()->hasOneUse())
464 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
465 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
466 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
467 GetConstantInt(ICI->getOperand(1), TD))
468 CV = ICI->getOperand(0);
470 // Unwrap any lossless ptrtoint cast.
471 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
472 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
473 CV = PTII->getOperand(0);
477 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
478 /// decode all of the 'cases' that it represents and return the 'default' block.
479 BasicBlock *SimplifyCFGOpt::
480 GetValueEqualityComparisonCases(TerminatorInst *TI,
481 std::vector<std::pair<ConstantInt*,
482 BasicBlock*> > &Cases) {
483 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
484 Cases.reserve(SI->getNumCases());
485 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
486 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
487 return SI->getDefaultDest();
490 BranchInst *BI = cast<BranchInst>(TI);
491 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
492 Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
493 BI->getSuccessor(ICI->getPredicate() ==
494 ICmpInst::ICMP_NE)));
495 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
499 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
500 /// in the list that match the specified block.
501 static void EliminateBlockCases(BasicBlock *BB,
502 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
503 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
504 if (Cases[i].second == BB) {
505 Cases.erase(Cases.begin()+i);
510 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
513 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
514 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
515 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
517 // Make V1 be smaller than V2.
518 if (V1->size() > V2->size())
521 if (V1->size() == 0) return false;
522 if (V1->size() == 1) {
524 ConstantInt *TheVal = (*V1)[0].first;
525 for (unsigned i = 0, e = V2->size(); i != e; ++i)
526 if (TheVal == (*V2)[i].first)
530 // Otherwise, just sort both lists and compare element by element.
531 array_pod_sort(V1->begin(), V1->end());
532 array_pod_sort(V2->begin(), V2->end());
533 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
534 while (i1 != e1 && i2 != e2) {
535 if ((*V1)[i1].first == (*V2)[i2].first)
537 if ((*V1)[i1].first < (*V2)[i2].first)
545 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
546 /// terminator instruction and its block is known to only have a single
547 /// predecessor block, check to see if that predecessor is also a value
548 /// comparison with the same value, and if that comparison determines the
549 /// outcome of this comparison. If so, simplify TI. This does a very limited
550 /// form of jump threading.
551 bool SimplifyCFGOpt::
552 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
554 IRBuilder<> &Builder) {
555 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
556 if (!PredVal) return false; // Not a value comparison in predecessor.
558 Value *ThisVal = isValueEqualityComparison(TI);
559 assert(ThisVal && "This isn't a value comparison!!");
560 if (ThisVal != PredVal) return false; // Different predicates.
562 // Find out information about when control will move from Pred to TI's block.
563 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
564 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
566 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
568 // Find information about how control leaves this block.
569 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
570 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
571 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
573 // If TI's block is the default block from Pred's comparison, potentially
574 // simplify TI based on this knowledge.
575 if (PredDef == TI->getParent()) {
576 // If we are here, we know that the value is none of those cases listed in
577 // PredCases. If there are any cases in ThisCases that are in PredCases, we
579 if (!ValuesOverlap(PredCases, ThisCases))
582 if (isa<BranchInst>(TI)) {
583 // Okay, one of the successors of this condbr is dead. Convert it to a
585 assert(ThisCases.size() == 1 && "Branch can only have one case!");
586 // Insert the new branch.
587 Instruction *NI = Builder.CreateBr(ThisDef);
590 // Remove PHI node entries for the dead edge.
591 ThisCases[0].second->removePredecessor(TI->getParent());
593 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
594 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
596 EraseTerminatorInstAndDCECond(TI);
600 SwitchInst *SI = cast<SwitchInst>(TI);
601 // Okay, TI has cases that are statically dead, prune them away.
602 SmallPtrSet<Constant*, 16> DeadCases;
603 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
604 DeadCases.insert(PredCases[i].first);
606 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
607 << "Through successor TI: " << *TI);
609 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
610 if (DeadCases.count(SI->getCaseValue(i))) {
611 SI->getSuccessor(i)->removePredecessor(TI->getParent());
615 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
619 // Otherwise, TI's block must correspond to some matched value. Find out
620 // which value (or set of values) this is.
621 ConstantInt *TIV = 0;
622 BasicBlock *TIBB = TI->getParent();
623 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
624 if (PredCases[i].second == TIBB) {
626 return false; // Cannot handle multiple values coming to this block.
627 TIV = PredCases[i].first;
629 assert(TIV && "No edge from pred to succ?");
631 // Okay, we found the one constant that our value can be if we get into TI's
632 // BB. Find out which successor will unconditionally be branched to.
633 BasicBlock *TheRealDest = 0;
634 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
635 if (ThisCases[i].first == TIV) {
636 TheRealDest = ThisCases[i].second;
640 // If not handled by any explicit cases, it is handled by the default case.
641 if (TheRealDest == 0) TheRealDest = ThisDef;
643 // Remove PHI node entries for dead edges.
644 BasicBlock *CheckEdge = TheRealDest;
645 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
646 if (*SI != CheckEdge)
647 (*SI)->removePredecessor(TIBB);
651 // Insert the new branch.
652 Instruction *NI = Builder.CreateBr(TheRealDest);
655 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
656 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
658 EraseTerminatorInstAndDCECond(TI);
663 /// ConstantIntOrdering - This class implements a stable ordering of constant
664 /// integers that does not depend on their address. This is important for
665 /// applications that sort ConstantInt's to ensure uniqueness.
666 struct ConstantIntOrdering {
667 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
668 return LHS->getValue().ult(RHS->getValue());
673 static int ConstantIntSortPredicate(const void *P1, const void *P2) {
674 const ConstantInt *LHS = *(const ConstantInt**)P1;
675 const ConstantInt *RHS = *(const ConstantInt**)P2;
676 if (LHS->getValue().ult(RHS->getValue()))
678 if (LHS->getValue() == RHS->getValue())
683 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
684 /// equality comparison instruction (either a switch or a branch on "X == c").
685 /// See if any of the predecessors of the terminator block are value comparisons
686 /// on the same value. If so, and if safe to do so, fold them together.
687 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
688 IRBuilder<> &Builder) {
689 BasicBlock *BB = TI->getParent();
690 Value *CV = isValueEqualityComparison(TI); // CondVal
691 assert(CV && "Not a comparison?");
692 bool Changed = false;
694 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
695 while (!Preds.empty()) {
696 BasicBlock *Pred = Preds.pop_back_val();
698 // See if the predecessor is a comparison with the same value.
699 TerminatorInst *PTI = Pred->getTerminator();
700 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
702 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
703 // Figure out which 'cases' to copy from SI to PSI.
704 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
705 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
707 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
708 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
710 // Based on whether the default edge from PTI goes to BB or not, fill in
711 // PredCases and PredDefault with the new switch cases we would like to
713 SmallVector<BasicBlock*, 8> NewSuccessors;
715 if (PredDefault == BB) {
716 // If this is the default destination from PTI, only the edges in TI
717 // that don't occur in PTI, or that branch to BB will be activated.
718 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
719 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
720 if (PredCases[i].second != BB)
721 PTIHandled.insert(PredCases[i].first);
723 // The default destination is BB, we don't need explicit targets.
724 std::swap(PredCases[i], PredCases.back());
725 PredCases.pop_back();
729 // Reconstruct the new switch statement we will be building.
730 if (PredDefault != BBDefault) {
731 PredDefault->removePredecessor(Pred);
732 PredDefault = BBDefault;
733 NewSuccessors.push_back(BBDefault);
735 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
736 if (!PTIHandled.count(BBCases[i].first) &&
737 BBCases[i].second != BBDefault) {
738 PredCases.push_back(BBCases[i]);
739 NewSuccessors.push_back(BBCases[i].second);
743 // If this is not the default destination from PSI, only the edges
744 // in SI that occur in PSI with a destination of BB will be
746 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
747 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
748 if (PredCases[i].second == BB) {
749 PTIHandled.insert(PredCases[i].first);
750 std::swap(PredCases[i], PredCases.back());
751 PredCases.pop_back();
755 // Okay, now we know which constants were sent to BB from the
756 // predecessor. Figure out where they will all go now.
757 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
758 if (PTIHandled.count(BBCases[i].first)) {
759 // If this is one we are capable of getting...
760 PredCases.push_back(BBCases[i]);
761 NewSuccessors.push_back(BBCases[i].second);
762 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
765 // If there are any constants vectored to BB that TI doesn't handle,
766 // they must go to the default destination of TI.
767 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
769 E = PTIHandled.end(); I != E; ++I) {
770 PredCases.push_back(std::make_pair(*I, BBDefault));
771 NewSuccessors.push_back(BBDefault);
775 // Okay, at this point, we know which new successor Pred will get. Make
776 // sure we update the number of entries in the PHI nodes for these
778 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
779 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
781 Builder.SetInsertPoint(PTI);
782 // Convert pointer to int before we switch.
783 if (CV->getType()->isPointerTy()) {
784 assert(TD && "Cannot switch on pointer without TargetData");
785 CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
789 // Now that the successors are updated, create the new Switch instruction.
790 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
792 NewSI->setDebugLoc(PTI->getDebugLoc());
793 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
794 NewSI->addCase(PredCases[i].first, PredCases[i].second);
796 EraseTerminatorInstAndDCECond(PTI);
798 // Okay, last check. If BB is still a successor of PSI, then we must
799 // have an infinite loop case. If so, add an infinitely looping block
800 // to handle the case to preserve the behavior of the code.
801 BasicBlock *InfLoopBlock = 0;
802 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
803 if (NewSI->getSuccessor(i) == BB) {
804 if (InfLoopBlock == 0) {
805 // Insert it at the end of the function, because it's either code,
806 // or it won't matter if it's hot. :)
807 InfLoopBlock = BasicBlock::Create(BB->getContext(),
808 "infloop", BB->getParent());
809 BranchInst::Create(InfLoopBlock, InfLoopBlock);
811 NewSI->setSuccessor(i, InfLoopBlock);
820 // isSafeToHoistInvoke - If we would need to insert a select that uses the
821 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
822 // would need to do this), we can't hoist the invoke, as there is nowhere
823 // to put the select in this case.
824 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
825 Instruction *I1, Instruction *I2) {
826 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
828 for (BasicBlock::iterator BBI = SI->begin();
829 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
830 Value *BB1V = PN->getIncomingValueForBlock(BB1);
831 Value *BB2V = PN->getIncomingValueForBlock(BB2);
832 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
840 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
841 /// BB2, hoist any common code in the two blocks up into the branch block. The
842 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
843 static bool HoistThenElseCodeToIf(BranchInst *BI) {
844 // This does very trivial matching, with limited scanning, to find identical
845 // instructions in the two blocks. In particular, we don't want to get into
846 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
847 // such, we currently just scan for obviously identical instructions in an
849 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
850 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
852 BasicBlock::iterator BB1_Itr = BB1->begin();
853 BasicBlock::iterator BB2_Itr = BB2->begin();
855 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
856 // Skip debug info if it is not identical.
857 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
858 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
859 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
860 while (isa<DbgInfoIntrinsic>(I1))
862 while (isa<DbgInfoIntrinsic>(I2))
865 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
866 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
869 // If we get here, we can hoist at least one instruction.
870 BasicBlock *BIParent = BI->getParent();
873 // If we are hoisting the terminator instruction, don't move one (making a
874 // broken BB), instead clone it, and remove BI.
875 if (isa<TerminatorInst>(I1))
876 goto HoistTerminator;
878 // For a normal instruction, we just move one to right before the branch,
879 // then replace all uses of the other with the first. Finally, we remove
880 // the now redundant second instruction.
881 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
882 if (!I2->use_empty())
883 I2->replaceAllUsesWith(I1);
884 I1->intersectOptionalDataWith(I2);
885 I2->eraseFromParent();
889 // Skip debug info if it is not identical.
890 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
891 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
892 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
893 while (isa<DbgInfoIntrinsic>(I1))
895 while (isa<DbgInfoIntrinsic>(I2))
898 } while (I1->isIdenticalToWhenDefined(I2));
903 // It may not be possible to hoist an invoke.
904 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
907 // Okay, it is safe to hoist the terminator.
908 Instruction *NT = I1->clone();
909 BIParent->getInstList().insert(BI, NT);
910 if (!NT->getType()->isVoidTy()) {
911 I1->replaceAllUsesWith(NT);
912 I2->replaceAllUsesWith(NT);
916 IRBuilder<true, NoFolder> Builder(NT);
917 // Hoisting one of the terminators from our successor is a great thing.
918 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
919 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
920 // nodes, so we insert select instruction to compute the final result.
921 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
922 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
924 for (BasicBlock::iterator BBI = SI->begin();
925 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
926 Value *BB1V = PN->getIncomingValueForBlock(BB1);
927 Value *BB2V = PN->getIncomingValueForBlock(BB2);
928 if (BB1V == BB2V) continue;
930 // These values do not agree. Insert a select instruction before NT
931 // that determines the right value.
932 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
934 SI = cast<SelectInst>
935 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
936 BB1V->getName()+"."+BB2V->getName()));
938 // Make the PHI node use the select for all incoming values for BB1/BB2
939 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
940 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
941 PN->setIncomingValue(i, SI);
945 // Update any PHI nodes in our new successors.
946 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
947 AddPredecessorToBlock(*SI, BIParent, BB1);
949 EraseTerminatorInstAndDCECond(BI);
953 /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
954 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
955 /// (for now, restricted to a single instruction that's side effect free) from
956 /// the BB1 into the branch block to speculatively execute it.
957 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
958 // Only speculatively execution a single instruction (not counting the
959 // terminator) for now.
960 Instruction *HInst = NULL;
961 Instruction *Term = BB1->getTerminator();
962 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
964 Instruction *I = BBI;
966 if (isa<DbgInfoIntrinsic>(I)) continue;
967 if (I == Term) break;
976 // Be conservative for now. FP select instruction can often be expensive.
977 Value *BrCond = BI->getCondition();
978 if (isa<FCmpInst>(BrCond))
981 // If BB1 is actually on the false edge of the conditional branch, remember
982 // to swap the select operands later.
984 if (BB1 != BI->getSuccessor(0)) {
985 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
992 // br i1 %t1, label %BB1, label %BB2
1001 // %t3 = select i1 %t1, %t2, %t3
1002 switch (HInst->getOpcode()) {
1003 default: return false; // Not safe / profitable to hoist.
1004 case Instruction::Add:
1005 case Instruction::Sub:
1006 // Not worth doing for vector ops.
1007 if (HInst->getType()->isVectorTy())
1010 case Instruction::And:
1011 case Instruction::Or:
1012 case Instruction::Xor:
1013 case Instruction::Shl:
1014 case Instruction::LShr:
1015 case Instruction::AShr:
1016 // Don't mess with vector operations.
1017 if (HInst->getType()->isVectorTy())
1019 break; // These are all cheap and non-trapping instructions.
1022 // If the instruction is obviously dead, don't try to predicate it.
1023 if (HInst->use_empty()) {
1024 HInst->eraseFromParent();
1028 // Can we speculatively execute the instruction? And what is the value
1029 // if the condition is false? Consider the phi uses, if the incoming value
1030 // from the "if" block are all the same V, then V is the value of the
1031 // select if the condition is false.
1032 BasicBlock *BIParent = BI->getParent();
1033 SmallVector<PHINode*, 4> PHIUses;
1034 Value *FalseV = NULL;
1036 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
1037 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
1039 // Ignore any user that is not a PHI node in BB2. These can only occur in
1040 // unreachable blocks, because they would not be dominated by the instr.
1041 PHINode *PN = dyn_cast<PHINode>(*UI);
1042 if (!PN || PN->getParent() != BB2)
1044 PHIUses.push_back(PN);
1046 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
1049 else if (FalseV != PHIV)
1050 return false; // Inconsistent value when condition is false.
1053 assert(FalseV && "Must have at least one user, and it must be a PHI");
1055 // Do not hoist the instruction if any of its operands are defined but not
1056 // used in this BB. The transformation will prevent the operand from
1057 // being sunk into the use block.
1058 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1060 Instruction *OpI = dyn_cast<Instruction>(*i);
1061 if (OpI && OpI->getParent() == BIParent &&
1062 !OpI->isUsedInBasicBlock(BIParent))
1066 // If we get here, we can hoist the instruction.
1067 BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
1069 // Create a select whose true value is the speculatively executed value and
1070 // false value is the previously determined FalseV.
1071 IRBuilder<true, NoFolder> Builder(BI);
1074 SI = cast<SelectInst>
1075 (Builder.CreateSelect(BrCond, FalseV, HInst,
1076 FalseV->getName() + "." + HInst->getName()));
1078 SI = cast<SelectInst>
1079 (Builder.CreateSelect(BrCond, HInst, FalseV,
1080 HInst->getName() + "." + FalseV->getName()));
1082 // Make the PHI node use the select for all incoming values for "then" and
1084 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1085 PHINode *PN = PHIUses[i];
1086 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
1087 if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
1088 PN->setIncomingValue(j, SI);
1095 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1096 /// across this block.
1097 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1098 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1101 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1102 if (isa<DbgInfoIntrinsic>(BBI))
1104 if (Size > 10) return false; // Don't clone large BB's.
1107 // We can only support instructions that do not define values that are
1108 // live outside of the current basic block.
1109 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1111 Instruction *U = cast<Instruction>(*UI);
1112 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1115 // Looks ok, continue checking.
1121 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1122 /// that is defined in the same block as the branch and if any PHI entries are
1123 /// constants, thread edges corresponding to that entry to be branches to their
1124 /// ultimate destination.
1125 static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
1126 BasicBlock *BB = BI->getParent();
1127 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1128 // NOTE: we currently cannot transform this case if the PHI node is used
1129 // outside of the block.
1130 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1133 // Degenerate case of a single entry PHI.
1134 if (PN->getNumIncomingValues() == 1) {
1135 FoldSingleEntryPHINodes(PN->getParent());
1139 // Now we know that this block has multiple preds and two succs.
1140 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1142 // Okay, this is a simple enough basic block. See if any phi values are
1144 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1145 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1146 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1148 // Okay, we now know that all edges from PredBB should be revectored to
1149 // branch to RealDest.
1150 BasicBlock *PredBB = PN->getIncomingBlock(i);
1151 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1153 if (RealDest == BB) continue; // Skip self loops.
1154 // Skip if the predecessor's terminator is an indirect branch.
1155 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1157 // The dest block might have PHI nodes, other predecessors and other
1158 // difficult cases. Instead of being smart about this, just insert a new
1159 // block that jumps to the destination block, effectively splitting
1160 // the edge we are about to create.
1161 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1162 RealDest->getName()+".critedge",
1163 RealDest->getParent(), RealDest);
1164 BranchInst::Create(RealDest, EdgeBB);
1166 // Update PHI nodes.
1167 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1169 // BB may have instructions that are being threaded over. Clone these
1170 // instructions into EdgeBB. We know that there will be no uses of the
1171 // cloned instructions outside of EdgeBB.
1172 BasicBlock::iterator InsertPt = EdgeBB->begin();
1173 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1174 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1175 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1176 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1179 // Clone the instruction.
1180 Instruction *N = BBI->clone();
1181 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1183 // Update operands due to translation.
1184 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1186 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1187 if (PI != TranslateMap.end())
1191 // Check for trivial simplification.
1192 if (Value *V = SimplifyInstruction(N, TD)) {
1193 TranslateMap[BBI] = V;
1194 delete N; // Instruction folded away, don't need actual inst
1196 // Insert the new instruction into its new home.
1197 EdgeBB->getInstList().insert(InsertPt, N);
1198 if (!BBI->use_empty())
1199 TranslateMap[BBI] = N;
1203 // Loop over all of the edges from PredBB to BB, changing them to branch
1204 // to EdgeBB instead.
1205 TerminatorInst *PredBBTI = PredBB->getTerminator();
1206 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1207 if (PredBBTI->getSuccessor(i) == BB) {
1208 BB->removePredecessor(PredBB);
1209 PredBBTI->setSuccessor(i, EdgeBB);
1212 // Recurse, simplifying any other constants.
1213 return FoldCondBranchOnPHI(BI, TD) | true;
1219 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1220 /// PHI node, see if we can eliminate it.
1221 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
1222 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1223 // statement", which has a very simple dominance structure. Basically, we
1224 // are trying to find the condition that is being branched on, which
1225 // subsequently causes this merge to happen. We really want control
1226 // dependence information for this check, but simplifycfg can't keep it up
1227 // to date, and this catches most of the cases we care about anyway.
1228 BasicBlock *BB = PN->getParent();
1229 BasicBlock *IfTrue, *IfFalse;
1230 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1232 // Don't bother if the branch will be constant folded trivially.
1233 isa<ConstantInt>(IfCond))
1236 // Okay, we found that we can merge this two-entry phi node into a select.
1237 // Doing so would require us to fold *all* two entry phi nodes in this block.
1238 // At some point this becomes non-profitable (particularly if the target
1239 // doesn't support cmov's). Only do this transformation if there are two or
1240 // fewer PHI nodes in this block.
1241 unsigned NumPhis = 0;
1242 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1246 // Loop over the PHI's seeing if we can promote them all to select
1247 // instructions. While we are at it, keep track of the instructions
1248 // that need to be moved to the dominating block.
1249 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1250 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1251 MaxCostVal1 = PHINodeFoldingThreshold;
1253 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1254 PHINode *PN = cast<PHINode>(II++);
1255 if (Value *V = SimplifyInstruction(PN, TD)) {
1256 PN->replaceAllUsesWith(V);
1257 PN->eraseFromParent();
1261 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1263 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1268 // If we folded the the first phi, PN dangles at this point. Refresh it. If
1269 // we ran out of PHIs then we simplified them all.
1270 PN = dyn_cast<PHINode>(BB->begin());
1271 if (PN == 0) return true;
1273 // Don't fold i1 branches on PHIs which contain binary operators. These can
1274 // often be turned into switches and other things.
1275 if (PN->getType()->isIntegerTy(1) &&
1276 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1277 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1278 isa<BinaryOperator>(IfCond)))
1281 // If we all PHI nodes are promotable, check to make sure that all
1282 // instructions in the predecessor blocks can be promoted as well. If
1283 // not, we won't be able to get rid of the control flow, so it's not
1284 // worth promoting to select instructions.
1285 BasicBlock *DomBlock = 0;
1286 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1287 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1288 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1291 DomBlock = *pred_begin(IfBlock1);
1292 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1293 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1294 // This is not an aggressive instruction that we can promote.
1295 // Because of this, we won't be able to get rid of the control
1296 // flow, so the xform is not worth it.
1301 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1304 DomBlock = *pred_begin(IfBlock2);
1305 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1306 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1307 // This is not an aggressive instruction that we can promote.
1308 // Because of this, we won't be able to get rid of the control
1309 // flow, so the xform is not worth it.
1314 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1315 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1317 // If we can still promote the PHI nodes after this gauntlet of tests,
1318 // do all of the PHI's now.
1319 Instruction *InsertPt = DomBlock->getTerminator();
1320 IRBuilder<true, NoFolder> Builder(InsertPt);
1322 // Move all 'aggressive' instructions, which are defined in the
1323 // conditional parts of the if's up to the dominating block.
1325 DomBlock->getInstList().splice(InsertPt,
1326 IfBlock1->getInstList(), IfBlock1->begin(),
1327 IfBlock1->getTerminator());
1329 DomBlock->getInstList().splice(InsertPt,
1330 IfBlock2->getInstList(), IfBlock2->begin(),
1331 IfBlock2->getTerminator());
1333 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1334 // Change the PHI node into a select instruction.
1335 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1336 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1339 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1340 PN->replaceAllUsesWith(NV);
1342 PN->eraseFromParent();
1345 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1346 // has been flattened. Change DomBlock to jump directly to our new block to
1347 // avoid other simplifycfg's kicking in on the diamond.
1348 TerminatorInst *OldTI = DomBlock->getTerminator();
1349 Builder.SetInsertPoint(OldTI);
1350 Builder.CreateBr(BB);
1351 OldTI->eraseFromParent();
1355 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1356 /// to two returning blocks, try to merge them together into one return,
1357 /// introducing a select if the return values disagree.
1358 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1359 IRBuilder<> &Builder) {
1360 assert(BI->isConditional() && "Must be a conditional branch");
1361 BasicBlock *TrueSucc = BI->getSuccessor(0);
1362 BasicBlock *FalseSucc = BI->getSuccessor(1);
1363 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1364 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1366 // Check to ensure both blocks are empty (just a return) or optionally empty
1367 // with PHI nodes. If there are other instructions, merging would cause extra
1368 // computation on one path or the other.
1369 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1371 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1374 Builder.SetInsertPoint(BI);
1375 // Okay, we found a branch that is going to two return nodes. If
1376 // there is no return value for this function, just change the
1377 // branch into a return.
1378 if (FalseRet->getNumOperands() == 0) {
1379 TrueSucc->removePredecessor(BI->getParent());
1380 FalseSucc->removePredecessor(BI->getParent());
1381 Builder.CreateRetVoid();
1382 EraseTerminatorInstAndDCECond(BI);
1386 // Otherwise, figure out what the true and false return values are
1387 // so we can insert a new select instruction.
1388 Value *TrueValue = TrueRet->getReturnValue();
1389 Value *FalseValue = FalseRet->getReturnValue();
1391 // Unwrap any PHI nodes in the return blocks.
1392 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1393 if (TVPN->getParent() == TrueSucc)
1394 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1395 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1396 if (FVPN->getParent() == FalseSucc)
1397 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1399 // In order for this transformation to be safe, we must be able to
1400 // unconditionally execute both operands to the return. This is
1401 // normally the case, but we could have a potentially-trapping
1402 // constant expression that prevents this transformation from being
1404 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1407 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1411 // Okay, we collected all the mapped values and checked them for sanity, and
1412 // defined to really do this transformation. First, update the CFG.
1413 TrueSucc->removePredecessor(BI->getParent());
1414 FalseSucc->removePredecessor(BI->getParent());
1416 // Insert select instructions where needed.
1417 Value *BrCond = BI->getCondition();
1419 // Insert a select if the results differ.
1420 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1421 } else if (isa<UndefValue>(TrueValue)) {
1422 TrueValue = FalseValue;
1424 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1425 FalseValue, "retval");
1429 Value *RI = !TrueValue ?
1430 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1434 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1435 << "\n " << *BI << "NewRet = " << *RI
1436 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1438 EraseTerminatorInstAndDCECond(BI);
1443 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1444 /// probabilities of the branch taking each edge. Fills in the two APInt
1445 /// parameters and return true, or returns false if no or invalid metadata was
1447 static bool ExtractBranchMetadata(BranchInst *BI,
1448 APInt &ProbTrue, APInt &ProbFalse) {
1449 assert(BI->isConditional() &&
1450 "Looking for probabilities on unconditional branch?");
1451 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1452 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1453 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1454 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1455 if (!CITrue || !CIFalse) return false;
1456 ProbTrue = CITrue->getValue();
1457 ProbFalse = CIFalse->getValue();
1458 assert(ProbTrue.getBitWidth() == 32 && ProbFalse.getBitWidth() == 32 &&
1459 "Branch probability metadata must be 32-bit integers");
1463 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1464 /// predecessor branches to us and one of our successors, fold the block into
1465 /// the predecessor and use logical operations to pick the right destination.
1466 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1467 BasicBlock *BB = BI->getParent();
1469 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1470 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1471 Cond->getParent() != BB || !Cond->hasOneUse())
1474 // Only allow this if the condition is a simple instruction that can be
1475 // executed unconditionally. It must be in the same block as the branch, and
1476 // must be at the front of the block.
1477 BasicBlock::iterator FrontIt = BB->front();
1479 // Ignore dbg intrinsics.
1480 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
1482 // Allow a single instruction to be hoisted in addition to the compare
1483 // that feeds the branch. We later ensure that any values that _it_ uses
1484 // were also live in the predecessor, so that we don't unnecessarily create
1485 // register pressure or inhibit out-of-order execution.
1486 Instruction *BonusInst = 0;
1487 if (&*FrontIt != Cond &&
1488 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1489 isSafeToSpeculativelyExecute(FrontIt)) {
1490 BonusInst = &*FrontIt;
1493 // Ignore dbg intrinsics.
1494 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
1497 // Only a single bonus inst is allowed.
1498 if (&*FrontIt != Cond)
1501 // Make sure the instruction after the condition is the cond branch.
1502 BasicBlock::iterator CondIt = Cond; ++CondIt;
1504 // Ingore dbg intrinsics.
1505 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
1510 // Cond is known to be a compare or binary operator. Check to make sure that
1511 // neither operand is a potentially-trapping constant expression.
1512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1515 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1519 // Finally, don't infinitely unroll conditional loops.
1520 BasicBlock *TrueDest = BI->getSuccessor(0);
1521 BasicBlock *FalseDest = BI->getSuccessor(1);
1522 if (TrueDest == BB || FalseDest == BB)
1525 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1526 BasicBlock *PredBlock = *PI;
1527 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
1529 // Check that we have two conditional branches. If there is a PHI node in
1530 // the common successor, verify that the same value flows in from both
1532 if (PBI == 0 || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
1535 // Determine if the two branches share a common destination.
1536 Instruction::BinaryOps Opc;
1537 bool InvertPredCond = false;
1539 if (PBI->getSuccessor(0) == TrueDest)
1540 Opc = Instruction::Or;
1541 else if (PBI->getSuccessor(1) == FalseDest)
1542 Opc = Instruction::And;
1543 else if (PBI->getSuccessor(0) == FalseDest)
1544 Opc = Instruction::And, InvertPredCond = true;
1545 else if (PBI->getSuccessor(1) == TrueDest)
1546 Opc = Instruction::Or, InvertPredCond = true;
1550 // Ensure that any values used in the bonus instruction are also used
1551 // by the terminator of the predecessor. This means that those values
1552 // must already have been resolved, so we won't be inhibiting the
1553 // out-of-order core by speculating them earlier.
1555 // Collect the values used by the bonus inst
1556 SmallPtrSet<Value*, 4> UsedValues;
1557 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1558 OE = BonusInst->op_end(); OI != OE; ++OI) {
1560 if (!isa<Constant>(V))
1561 UsedValues.insert(V);
1564 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1565 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1567 // Walk up to four levels back up the use-def chain of the predecessor's
1568 // terminator to see if all those values were used. The choice of four
1569 // levels is arbitrary, to provide a compile-time-cost bound.
1570 while (!Worklist.empty()) {
1571 std::pair<Value*, unsigned> Pair = Worklist.back();
1572 Worklist.pop_back();
1574 if (Pair.second >= 4) continue;
1575 UsedValues.erase(Pair.first);
1576 if (UsedValues.empty()) break;
1578 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
1579 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1581 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1585 if (!UsedValues.empty()) return false;
1588 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
1589 IRBuilder<> Builder(PBI);
1591 // If we need to invert the condition in the pred block to match, do so now.
1592 if (InvertPredCond) {
1593 Value *NewCond = PBI->getCondition();
1595 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1596 CmpInst *CI = cast<CmpInst>(NewCond);
1597 CI->setPredicate(CI->getInversePredicate());
1599 NewCond = Builder.CreateNot(NewCond,
1600 PBI->getCondition()->getName()+".not");
1603 PBI->setCondition(NewCond);
1604 PBI->swapSuccessors();
1607 // If we have a bonus inst, clone it into the predecessor block.
1608 Instruction *NewBonus = 0;
1610 NewBonus = BonusInst->clone();
1611 PredBlock->getInstList().insert(PBI, NewBonus);
1612 NewBonus->takeName(BonusInst);
1613 BonusInst->setName(BonusInst->getName()+".old");
1616 // Clone Cond into the predecessor basic block, and or/and the
1617 // two conditions together.
1618 Instruction *New = Cond->clone();
1619 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
1620 PredBlock->getInstList().insert(PBI, New);
1621 New->takeName(Cond);
1622 Cond->setName(New->getName()+".old");
1624 Instruction *NewCond =
1625 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
1627 PBI->setCondition(NewCond);
1628 if (PBI->getSuccessor(0) == BB) {
1629 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1630 PBI->setSuccessor(0, TrueDest);
1632 if (PBI->getSuccessor(1) == BB) {
1633 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1634 PBI->setSuccessor(1, FalseDest);
1637 // TODO: If BB is reachable from all paths through PredBlock, then we
1638 // could replace PBI's branch probabilities with BI's.
1640 // Merge probability data into PredBlock's branch.
1642 if (ExtractBranchMetadata(PBI, C, D) && ExtractBranchMetadata(BI, A, B)) {
1643 // Given IR which does:
1645 // br i1 %x, label %bbB, label %bbC
1647 // br i1 %y, label %bbD, label %bbC
1648 // Let's call the probability that we take the edge from %bbA to %bbB
1649 // 'a', from %bbA to %bbC, 'b', from %bbB to %bbD 'c' and from %bbB to
1650 // %bbC probability 'd'.
1652 // We transform the IR into:
1654 // br i1 %z, label %bbD, label %bbC
1655 // where the probability of going to %bbD is (a*c) and going to bbC is
1658 // Probabilities aren't stored as ratios directly. Using branch weights,
1660 // (a*c)% = A*C, (b+(a*d))% = A*D+B*C+B*D.
1662 bool Overflow1 = false, Overflow2 = false, Overflow3 = false;
1663 bool Overflow4 = false, Overflow5 = false, Overflow6 = false;
1664 APInt ProbTrue = A.umul_ov(C, Overflow1);
1666 APInt Tmp1 = A.umul_ov(D, Overflow2);
1667 APInt Tmp2 = B.umul_ov(C, Overflow3);
1668 APInt Tmp3 = B.umul_ov(D, Overflow4);
1669 APInt Tmp4 = Tmp1.uadd_ov(Tmp2, Overflow5);
1670 APInt ProbFalse = Tmp4.uadd_ov(Tmp3, Overflow6);
1672 APInt GCD = APIntOps::GreatestCommonDivisor(ProbTrue, ProbFalse);
1673 ProbTrue = ProbTrue.udiv(GCD);
1674 ProbFalse = ProbFalse.udiv(GCD);
1676 if (Overflow1 || Overflow2 || Overflow3 || Overflow4 || Overflow5 ||
1678 DEBUG(dbgs() << "Overflow recomputing branch weight on: " << *PBI
1679 << "when merging with: " << *BI);
1680 PBI->setMetadata(LLVMContext::MD_prof, NULL);
1682 LLVMContext &Context = BI->getContext();
1684 Ops[0] = BI->getMetadata(LLVMContext::MD_prof)->getOperand(0);
1685 Ops[1] = ConstantInt::get(Context, ProbTrue);
1686 Ops[2] = ConstantInt::get(Context, ProbFalse);
1687 PBI->setMetadata(LLVMContext::MD_prof, MDNode::get(Context, Ops));
1690 PBI->setMetadata(LLVMContext::MD_prof, NULL);
1693 // Copy any debug value intrinsics into the end of PredBlock.
1694 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1695 if (isa<DbgInfoIntrinsic>(*I))
1696 I->clone()->insertBefore(PBI);
1703 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1704 /// predecessor of another block, this function tries to simplify it. We know
1705 /// that PBI and BI are both conditional branches, and BI is in one of the
1706 /// successor blocks of PBI - PBI branches to BI.
1707 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1708 assert(PBI->isConditional() && BI->isConditional());
1709 BasicBlock *BB = BI->getParent();
1711 // If this block ends with a branch instruction, and if there is a
1712 // predecessor that ends on a branch of the same condition, make
1713 // this conditional branch redundant.
1714 if (PBI->getCondition() == BI->getCondition() &&
1715 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1716 // Okay, the outcome of this conditional branch is statically
1717 // knowable. If this block had a single pred, handle specially.
1718 if (BB->getSinglePredecessor()) {
1719 // Turn this into a branch on constant.
1720 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1721 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1723 return true; // Nuke the branch on constant.
1726 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1727 // in the constant and simplify the block result. Subsequent passes of
1728 // simplifycfg will thread the block.
1729 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1730 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
1731 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
1732 std::distance(PB, PE),
1733 BI->getCondition()->getName() + ".pr",
1735 // Okay, we're going to insert the PHI node. Since PBI is not the only
1736 // predecessor, compute the PHI'd conditional value for all of the preds.
1737 // Any predecessor where the condition is not computable we keep symbolic.
1738 for (pred_iterator PI = PB; PI != PE; ++PI) {
1739 BasicBlock *P = *PI;
1740 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
1741 PBI != BI && PBI->isConditional() &&
1742 PBI->getCondition() == BI->getCondition() &&
1743 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1744 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1745 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1748 NewPN->addIncoming(BI->getCondition(), P);
1752 BI->setCondition(NewPN);
1757 // If this is a conditional branch in an empty block, and if any
1758 // predecessors is a conditional branch to one of our destinations,
1759 // fold the conditions into logical ops and one cond br.
1760 BasicBlock::iterator BBI = BB->begin();
1761 // Ignore dbg intrinsics.
1762 while (isa<DbgInfoIntrinsic>(BBI))
1768 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1773 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1775 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1776 PBIOp = 0, BIOp = 1;
1777 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1778 PBIOp = 1, BIOp = 0;
1779 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1784 // Check to make sure that the other destination of this branch
1785 // isn't BB itself. If so, this is an infinite loop that will
1786 // keep getting unwound.
1787 if (PBI->getSuccessor(PBIOp) == BB)
1790 // Do not perform this transformation if it would require
1791 // insertion of a large number of select instructions. For targets
1792 // without predication/cmovs, this is a big pessimization.
1793 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1795 unsigned NumPhis = 0;
1796 for (BasicBlock::iterator II = CommonDest->begin();
1797 isa<PHINode>(II); ++II, ++NumPhis)
1798 if (NumPhis > 2) // Disable this xform.
1801 // Finally, if everything is ok, fold the branches to logical ops.
1802 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1804 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
1805 << "AND: " << *BI->getParent());
1808 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1809 // branch in it, where one edge (OtherDest) goes back to itself but the other
1810 // exits. We don't *know* that the program avoids the infinite loop
1811 // (even though that seems likely). If we do this xform naively, we'll end up
1812 // recursively unpeeling the loop. Since we know that (after the xform is
1813 // done) that the block *is* infinite if reached, we just make it an obviously
1814 // infinite loop with no cond branch.
1815 if (OtherDest == BB) {
1816 // Insert it at the end of the function, because it's either code,
1817 // or it won't matter if it's hot. :)
1818 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1819 "infloop", BB->getParent());
1820 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1821 OtherDest = InfLoopBlock;
1824 DEBUG(dbgs() << *PBI->getParent()->getParent());
1826 // BI may have other predecessors. Because of this, we leave
1827 // it alone, but modify PBI.
1829 // Make sure we get to CommonDest on True&True directions.
1830 Value *PBICond = PBI->getCondition();
1831 IRBuilder<true, NoFolder> Builder(PBI);
1833 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
1835 Value *BICond = BI->getCondition();
1837 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
1839 // Merge the conditions.
1840 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
1842 // Modify PBI to branch on the new condition to the new dests.
1843 PBI->setCondition(Cond);
1844 PBI->setSuccessor(0, CommonDest);
1845 PBI->setSuccessor(1, OtherDest);
1847 // OtherDest may have phi nodes. If so, add an entry from PBI's
1848 // block that are identical to the entries for BI's block.
1849 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
1851 // We know that the CommonDest already had an edge from PBI to
1852 // it. If it has PHIs though, the PHIs may have different
1853 // entries for BB and PBI's BB. If so, insert a select to make
1856 for (BasicBlock::iterator II = CommonDest->begin();
1857 (PN = dyn_cast<PHINode>(II)); ++II) {
1858 Value *BIV = PN->getIncomingValueForBlock(BB);
1859 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1860 Value *PBIV = PN->getIncomingValue(PBBIdx);
1862 // Insert a select in PBI to pick the right value.
1863 Value *NV = cast<SelectInst>
1864 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
1865 PN->setIncomingValue(PBBIdx, NV);
1869 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1870 DEBUG(dbgs() << *PBI->getParent()->getParent());
1872 // This basic block is probably dead. We know it has at least
1873 // one fewer predecessor.
1877 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
1878 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
1879 // Takes care of updating the successors and removing the old terminator.
1880 // Also makes sure not to introduce new successors by assuming that edges to
1881 // non-successor TrueBBs and FalseBBs aren't reachable.
1882 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
1883 BasicBlock *TrueBB, BasicBlock *FalseBB){
1884 // Remove any superfluous successor edges from the CFG.
1885 // First, figure out which successors to preserve.
1886 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1888 BasicBlock *KeepEdge1 = TrueBB;
1889 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1891 // Then remove the rest.
1892 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
1893 BasicBlock *Succ = OldTerm->getSuccessor(I);
1894 // Make sure only to keep exactly one copy of each edge.
1895 if (Succ == KeepEdge1)
1897 else if (Succ == KeepEdge2)
1900 Succ->removePredecessor(OldTerm->getParent());
1903 IRBuilder<> Builder(OldTerm);
1904 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
1906 // Insert an appropriate new terminator.
1907 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1908 if (TrueBB == FalseBB)
1909 // We were only looking for one successor, and it was present.
1910 // Create an unconditional branch to it.
1911 Builder.CreateBr(TrueBB);
1913 // We found both of the successors we were looking for.
1914 // Create a conditional branch sharing the condition of the select.
1915 Builder.CreateCondBr(Cond, TrueBB, FalseBB);
1916 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1917 // Neither of the selected blocks were successors, so this
1918 // terminator must be unreachable.
1919 new UnreachableInst(OldTerm->getContext(), OldTerm);
1921 // One of the selected values was a successor, but the other wasn't.
1922 // Insert an unconditional branch to the one that was found;
1923 // the edge to the one that wasn't must be unreachable.
1925 // Only TrueBB was found.
1926 Builder.CreateBr(TrueBB);
1928 // Only FalseBB was found.
1929 Builder.CreateBr(FalseBB);
1932 EraseTerminatorInstAndDCECond(OldTerm);
1936 // SimplifySwitchOnSelect - Replaces
1937 // (switch (select cond, X, Y)) on constant X, Y
1938 // with a branch - conditional if X and Y lead to distinct BBs,
1939 // unconditional otherwise.
1940 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
1941 // Check for constant integer values in the select.
1942 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
1943 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
1944 if (!TrueVal || !FalseVal)
1947 // Find the relevant condition and destinations.
1948 Value *Condition = Select->getCondition();
1949 BasicBlock *TrueBB = SI->getSuccessor(SI->findCaseValue(TrueVal));
1950 BasicBlock *FalseBB = SI->getSuccessor(SI->findCaseValue(FalseVal));
1952 // Perform the actual simplification.
1953 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
1956 // SimplifyIndirectBrOnSelect - Replaces
1957 // (indirectbr (select cond, blockaddress(@fn, BlockA),
1958 // blockaddress(@fn, BlockB)))
1960 // (br cond, BlockA, BlockB).
1961 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1962 // Check that both operands of the select are block addresses.
1963 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1964 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1968 // Extract the actual blocks.
1969 BasicBlock *TrueBB = TBA->getBasicBlock();
1970 BasicBlock *FalseBB = FBA->getBasicBlock();
1972 // Perform the actual simplification.
1973 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
1976 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
1977 /// instruction (a seteq/setne with a constant) as the only instruction in a
1978 /// block that ends with an uncond branch. We are looking for a very specific
1979 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
1980 /// this case, we merge the first two "or's of icmp" into a switch, but then the
1981 /// default value goes to an uncond block with a seteq in it, we get something
1984 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
1986 /// %tmp = icmp eq i8 %A, 92
1989 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
1991 /// We prefer to split the edge to 'end' so that there is a true/false entry to
1992 /// the PHI, merging the third icmp into the switch.
1993 static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
1994 const TargetData *TD,
1995 IRBuilder<> &Builder) {
1996 BasicBlock *BB = ICI->getParent();
1998 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2000 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2002 Value *V = ICI->getOperand(0);
2003 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2005 // The pattern we're looking for is where our only predecessor is a switch on
2006 // 'V' and this block is the default case for the switch. In this case we can
2007 // fold the compared value into the switch to simplify things.
2008 BasicBlock *Pred = BB->getSinglePredecessor();
2009 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
2011 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2012 if (SI->getCondition() != V)
2015 // If BB is reachable on a non-default case, then we simply know the value of
2016 // V in this block. Substitute it and constant fold the icmp instruction
2018 if (SI->getDefaultDest() != BB) {
2019 ConstantInt *VVal = SI->findCaseDest(BB);
2020 assert(VVal && "Should have a unique destination value");
2021 ICI->setOperand(0, VVal);
2023 if (Value *V = SimplifyInstruction(ICI, TD)) {
2024 ICI->replaceAllUsesWith(V);
2025 ICI->eraseFromParent();
2027 // BB is now empty, so it is likely to simplify away.
2028 return SimplifyCFG(BB) | true;
2031 // Ok, the block is reachable from the default dest. If the constant we're
2032 // comparing exists in one of the other edges, then we can constant fold ICI
2034 if (SI->findCaseValue(Cst) != 0) {
2036 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2037 V = ConstantInt::getFalse(BB->getContext());
2039 V = ConstantInt::getTrue(BB->getContext());
2041 ICI->replaceAllUsesWith(V);
2042 ICI->eraseFromParent();
2043 // BB is now empty, so it is likely to simplify away.
2044 return SimplifyCFG(BB) | true;
2047 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2049 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2050 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
2051 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
2052 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2055 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2057 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2058 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2060 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2061 std::swap(DefaultCst, NewCst);
2063 // Replace ICI (which is used by the PHI for the default value) with true or
2064 // false depending on if it is EQ or NE.
2065 ICI->replaceAllUsesWith(DefaultCst);
2066 ICI->eraseFromParent();
2068 // Okay, the switch goes to this block on a default value. Add an edge from
2069 // the switch to the merge point on the compared value.
2070 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2071 BB->getParent(), BB);
2072 SI->addCase(Cst, NewBB);
2074 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2075 Builder.SetInsertPoint(NewBB);
2076 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2077 Builder.CreateBr(SuccBlock);
2078 PHIUse->addIncoming(NewCst, NewBB);
2082 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2083 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2084 /// fold it into a switch instruction if so.
2085 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
2086 IRBuilder<> &Builder) {
2087 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2088 if (Cond == 0) return false;
2091 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2092 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2093 // 'setne's and'ed together, collect them.
2095 std::vector<ConstantInt*> Values;
2096 bool TrueWhenEqual = true;
2097 Value *ExtraCase = 0;
2098 unsigned UsedICmps = 0;
2100 if (Cond->getOpcode() == Instruction::Or) {
2101 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
2103 } else if (Cond->getOpcode() == Instruction::And) {
2104 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
2106 TrueWhenEqual = false;
2109 // If we didn't have a multiply compared value, fail.
2110 if (CompVal == 0) return false;
2112 // Avoid turning single icmps into a switch.
2116 // There might be duplicate constants in the list, which the switch
2117 // instruction can't handle, remove them now.
2118 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2119 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2121 // If Extra was used, we require at least two switch values to do the
2122 // transformation. A switch with one value is just an cond branch.
2123 if (ExtraCase && Values.size() < 2) return false;
2125 // Figure out which block is which destination.
2126 BasicBlock *DefaultBB = BI->getSuccessor(1);
2127 BasicBlock *EdgeBB = BI->getSuccessor(0);
2128 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2130 BasicBlock *BB = BI->getParent();
2132 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2133 << " cases into SWITCH. BB is:\n" << *BB);
2135 // If there are any extra values that couldn't be folded into the switch
2136 // then we evaluate them with an explicit branch first. Split the block
2137 // right before the condbr to handle it.
2139 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2140 // Remove the uncond branch added to the old block.
2141 TerminatorInst *OldTI = BB->getTerminator();
2142 Builder.SetInsertPoint(OldTI);
2145 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2147 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2149 OldTI->eraseFromParent();
2151 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2152 // for the edge we just added.
2153 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2155 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2156 << "\nEXTRABB = " << *BB);
2160 Builder.SetInsertPoint(BI);
2161 // Convert pointer to int before we switch.
2162 if (CompVal->getType()->isPointerTy()) {
2163 assert(TD && "Cannot switch on pointer without TargetData");
2164 CompVal = Builder.CreatePtrToInt(CompVal,
2165 TD->getIntPtrType(CompVal->getContext()),
2169 // Create the new switch instruction now.
2170 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2172 // Add all of the 'cases' to the switch instruction.
2173 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2174 New->addCase(Values[i], EdgeBB);
2176 // We added edges from PI to the EdgeBB. As such, if there were any
2177 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2178 // the number of edges added.
2179 for (BasicBlock::iterator BBI = EdgeBB->begin();
2180 isa<PHINode>(BBI); ++BBI) {
2181 PHINode *PN = cast<PHINode>(BBI);
2182 Value *InVal = PN->getIncomingValueForBlock(BB);
2183 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2184 PN->addIncoming(InVal, BB);
2187 // Erase the old branch instruction.
2188 EraseTerminatorInstAndDCECond(BI);
2190 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2194 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2195 // If this is a trivial landing pad that just continues unwinding the caught
2196 // exception then zap the landing pad, turning its invokes into calls.
2197 BasicBlock *BB = RI->getParent();
2198 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2199 if (RI->getValue() != LPInst)
2200 // Not a landing pad, or the resume is not unwinding the exception that
2201 // caused control to branch here.
2204 // Check that there are no other instructions except for debug intrinsics.
2205 BasicBlock::iterator I = LPInst, E = RI;
2207 if (!isa<DbgInfoIntrinsic>(I))
2210 // Turn all invokes that unwind here into calls and delete the basic block.
2211 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2212 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2213 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2214 // Insert a call instruction before the invoke.
2215 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2217 Call->setCallingConv(II->getCallingConv());
2218 Call->setAttributes(II->getAttributes());
2219 Call->setDebugLoc(II->getDebugLoc());
2221 // Anything that used the value produced by the invoke instruction now uses
2222 // the value produced by the call instruction. Note that we do this even
2223 // for void functions and calls with no uses so that the callgraph edge is
2225 II->replaceAllUsesWith(Call);
2226 BB->removePredecessor(II->getParent());
2228 // Insert a branch to the normal destination right before the invoke.
2229 BranchInst::Create(II->getNormalDest(), II);
2231 // Finally, delete the invoke instruction!
2232 II->eraseFromParent();
2235 // The landingpad is now unreachable. Zap it.
2236 BB->eraseFromParent();
2240 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2241 BasicBlock *BB = RI->getParent();
2242 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2244 // Find predecessors that end with branches.
2245 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2246 SmallVector<BranchInst*, 8> CondBranchPreds;
2247 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2248 BasicBlock *P = *PI;
2249 TerminatorInst *PTI = P->getTerminator();
2250 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2251 if (BI->isUnconditional())
2252 UncondBranchPreds.push_back(P);
2254 CondBranchPreds.push_back(BI);
2258 // If we found some, do the transformation!
2259 if (!UncondBranchPreds.empty() && DupRet) {
2260 while (!UncondBranchPreds.empty()) {
2261 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2262 DEBUG(dbgs() << "FOLDING: " << *BB
2263 << "INTO UNCOND BRANCH PRED: " << *Pred);
2264 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2267 // If we eliminated all predecessors of the block, delete the block now.
2268 if (pred_begin(BB) == pred_end(BB))
2269 // We know there are no successors, so just nuke the block.
2270 BB->eraseFromParent();
2275 // Check out all of the conditional branches going to this return
2276 // instruction. If any of them just select between returns, change the
2277 // branch itself into a select/return pair.
2278 while (!CondBranchPreds.empty()) {
2279 BranchInst *BI = CondBranchPreds.pop_back_val();
2281 // Check to see if the non-BB successor is also a return block.
2282 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2283 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2284 SimplifyCondBranchToTwoReturns(BI, Builder))
2290 bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder) {
2291 // Check to see if the first instruction in this block is just an unwind.
2292 // If so, replace any invoke instructions which use this as an exception
2293 // destination with call instructions.
2294 BasicBlock *BB = UI->getParent();
2295 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2297 bool Changed = false;
2298 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2299 while (!Preds.empty()) {
2300 BasicBlock *Pred = Preds.back();
2301 InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
2302 if (II && II->getUnwindDest() == BB) {
2303 // Insert a new branch instruction before the invoke, because this
2304 // is now a fall through.
2305 Builder.SetInsertPoint(II);
2306 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
2307 Pred->getInstList().remove(II); // Take out of symbol table
2309 // Insert the call now.
2310 SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
2311 Builder.SetInsertPoint(BI);
2312 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
2313 Args, II->getName());
2314 CI->setCallingConv(II->getCallingConv());
2315 CI->setAttributes(II->getAttributes());
2316 // If the invoke produced a value, the Call now does instead.
2317 II->replaceAllUsesWith(CI);
2325 // If this block is now dead (and isn't the entry block), remove it.
2326 if (pred_begin(BB) == pred_end(BB) &&
2327 BB != &BB->getParent()->getEntryBlock()) {
2328 // We know there are no successors, so just nuke the block.
2329 BB->eraseFromParent();
2336 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2337 BasicBlock *BB = UI->getParent();
2339 bool Changed = false;
2341 // If there are any instructions immediately before the unreachable that can
2342 // be removed, do so.
2343 while (UI != BB->begin()) {
2344 BasicBlock::iterator BBI = UI;
2346 // Do not delete instructions that can have side effects which might cause
2347 // the unreachable to not be reachable; specifically, calls and volatile
2348 // operations may have this effect.
2349 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2351 if (BBI->mayHaveSideEffects()) {
2352 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2353 if (SI->isVolatile())
2355 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2356 if (LI->isVolatile())
2358 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2359 if (RMWI->isVolatile())
2361 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2362 if (CXI->isVolatile())
2364 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2365 !isa<LandingPadInst>(BBI)) {
2368 // Note that deleting LandingPad's here is in fact okay, although it
2369 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2370 // all the predecessors of this block will be the unwind edges of Invokes,
2371 // and we can therefore guarantee this block will be erased.
2374 // Delete this instruction (any uses are guaranteed to be dead)
2375 if (!BBI->use_empty())
2376 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2377 BBI->eraseFromParent();
2381 // If the unreachable instruction is the first in the block, take a gander
2382 // at all of the predecessors of this instruction, and simplify them.
2383 if (&BB->front() != UI) return Changed;
2385 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2386 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2387 TerminatorInst *TI = Preds[i]->getTerminator();
2388 IRBuilder<> Builder(TI);
2389 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2390 if (BI->isUnconditional()) {
2391 if (BI->getSuccessor(0) == BB) {
2392 new UnreachableInst(TI->getContext(), TI);
2393 TI->eraseFromParent();
2397 if (BI->getSuccessor(0) == BB) {
2398 Builder.CreateBr(BI->getSuccessor(1));
2399 EraseTerminatorInstAndDCECond(BI);
2400 } else if (BI->getSuccessor(1) == BB) {
2401 Builder.CreateBr(BI->getSuccessor(0));
2402 EraseTerminatorInstAndDCECond(BI);
2406 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2407 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2408 if (SI->getSuccessor(i) == BB) {
2409 BB->removePredecessor(SI->getParent());
2414 // If the default value is unreachable, figure out the most popular
2415 // destination and make it the default.
2416 if (SI->getSuccessor(0) == BB) {
2417 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
2418 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
2419 std::pair<unsigned, unsigned> &entry =
2420 Popularity[SI->getSuccessor(i)];
2421 if (entry.first == 0) {
2429 // Find the most popular block.
2430 unsigned MaxPop = 0;
2431 unsigned MaxIndex = 0;
2432 BasicBlock *MaxBlock = 0;
2433 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
2434 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2435 if (I->second.first > MaxPop ||
2436 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
2437 MaxPop = I->second.first;
2438 MaxIndex = I->second.second;
2439 MaxBlock = I->first;
2443 // Make this the new default, allowing us to delete any explicit
2445 SI->setSuccessor(0, MaxBlock);
2448 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2450 if (isa<PHINode>(MaxBlock->begin()))
2451 for (unsigned i = 0; i != MaxPop-1; ++i)
2452 MaxBlock->removePredecessor(SI->getParent());
2454 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2455 if (SI->getSuccessor(i) == MaxBlock) {
2461 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2462 if (II->getUnwindDest() == BB) {
2463 // Convert the invoke to a call instruction. This would be a good
2464 // place to note that the call does not throw though.
2465 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
2466 II->removeFromParent(); // Take out of symbol table
2468 // Insert the call now...
2469 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2470 Builder.SetInsertPoint(BI);
2471 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
2472 Args, II->getName());
2473 CI->setCallingConv(II->getCallingConv());
2474 CI->setAttributes(II->getAttributes());
2475 // If the invoke produced a value, the call does now instead.
2476 II->replaceAllUsesWith(CI);
2483 // If this block is now dead, remove it.
2484 if (pred_begin(BB) == pred_end(BB) &&
2485 BB != &BB->getParent()->getEntryBlock()) {
2486 // We know there are no successors, so just nuke the block.
2487 BB->eraseFromParent();
2494 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
2495 /// integer range comparison into a sub, an icmp and a branch.
2496 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
2497 assert(SI->getNumCases() > 2 && "Degenerate switch?");
2499 // Make sure all cases point to the same destination and gather the values.
2500 SmallVector<ConstantInt *, 16> Cases;
2501 Cases.push_back(SI->getCaseValue(1));
2502 for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
2503 if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
2505 Cases.push_back(SI->getCaseValue(I));
2507 assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
2509 // Sort the case values, then check if they form a range we can transform.
2510 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
2511 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
2512 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
2516 Constant *Offset = ConstantExpr::getNeg(Cases.back());
2517 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
2519 Value *Sub = SI->getCondition();
2520 if (!Offset->isNullValue())
2521 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
2522 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
2523 Builder.CreateCondBr(Cmp, SI->getSuccessor(1), SI->getDefaultDest());
2525 // Prune obsolete incoming values off the successor's PHI nodes.
2526 for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
2527 isa<PHINode>(BBI); ++BBI) {
2528 for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
2529 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
2531 SI->eraseFromParent();
2536 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
2537 /// and use it to remove dead cases.
2538 static bool EliminateDeadSwitchCases(SwitchInst *SI) {
2539 Value *Cond = SI->getCondition();
2540 unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
2541 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
2542 ComputeMaskedBits(Cond, APInt::getAllOnesValue(Bits), KnownZero, KnownOne);
2544 // Gather dead cases.
2545 SmallVector<ConstantInt*, 8> DeadCases;
2546 for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
2547 if ((SI->getCaseValue(I)->getValue() & KnownZero) != 0 ||
2548 (SI->getCaseValue(I)->getValue() & KnownOne) != KnownOne) {
2549 DeadCases.push_back(SI->getCaseValue(I));
2550 DEBUG(dbgs() << "SimplifyCFG: switch case '"
2551 << SI->getCaseValue(I)->getValue() << "' is dead.\n");
2555 // Remove dead cases from the switch.
2556 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
2557 unsigned Case = SI->findCaseValue(DeadCases[I]);
2558 // Prune unused values from PHI nodes.
2559 SI->getSuccessor(Case)->removePredecessor(SI->getParent());
2560 SI->removeCase(Case);
2563 return !DeadCases.empty();
2566 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
2567 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
2568 /// by an unconditional branch), look at the phi node for BB in the successor
2569 /// block and see if the incoming value is equal to CaseValue. If so, return
2570 /// the phi node, and set PhiIndex to BB's index in the phi node.
2571 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
2574 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
2575 return NULL; // BB must be empty to be a candidate for simplification.
2576 if (!BB->getSinglePredecessor())
2577 return NULL; // BB must be dominated by the switch.
2579 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
2580 if (!Branch || !Branch->isUnconditional())
2581 return NULL; // Terminator must be unconditional branch.
2583 BasicBlock *Succ = Branch->getSuccessor(0);
2585 BasicBlock::iterator I = Succ->begin();
2586 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
2587 int Idx = PHI->getBasicBlockIndex(BB);
2588 assert(Idx >= 0 && "PHI has no entry for predecessor?");
2590 Value *InValue = PHI->getIncomingValue(Idx);
2591 if (InValue != CaseValue) continue;
2600 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
2601 /// instruction to a phi node dominated by the switch, if that would mean that
2602 /// some of the destination blocks of the switch can be folded away.
2603 /// Returns true if a change is made.
2604 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
2605 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
2606 ForwardingNodesMap ForwardingNodes;
2608 for (unsigned I = 1; I < SI->getNumCases(); ++I) { // 0 is the default case.
2609 ConstantInt *CaseValue = SI->getCaseValue(I);
2610 BasicBlock *CaseDest = SI->getSuccessor(I);
2613 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
2617 ForwardingNodes[PHI].push_back(PhiIndex);
2620 bool Changed = false;
2622 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
2623 E = ForwardingNodes.end(); I != E; ++I) {
2624 PHINode *Phi = I->first;
2625 SmallVector<int,4> &Indexes = I->second;
2627 if (Indexes.size() < 2) continue;
2629 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
2630 Phi->setIncomingValue(Indexes[I], SI->getCondition());
2637 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
2638 // If this switch is too complex to want to look at, ignore it.
2639 if (!isValueEqualityComparison(SI))
2642 BasicBlock *BB = SI->getParent();
2644 // If we only have one predecessor, and if it is a branch on this value,
2645 // see if that predecessor totally determines the outcome of this switch.
2646 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2647 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
2648 return SimplifyCFG(BB) | true;
2650 Value *Cond = SI->getCondition();
2651 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
2652 if (SimplifySwitchOnSelect(SI, Select))
2653 return SimplifyCFG(BB) | true;
2655 // If the block only contains the switch, see if we can fold the block
2656 // away into any preds.
2657 BasicBlock::iterator BBI = BB->begin();
2658 // Ignore dbg intrinsics.
2659 while (isa<DbgInfoIntrinsic>(BBI))
2662 if (FoldValueComparisonIntoPredecessors(SI, Builder))
2663 return SimplifyCFG(BB) | true;
2665 // Try to transform the switch into an icmp and a branch.
2666 if (TurnSwitchRangeIntoICmp(SI, Builder))
2667 return SimplifyCFG(BB) | true;
2669 // Remove unreachable cases.
2670 if (EliminateDeadSwitchCases(SI))
2671 return SimplifyCFG(BB) | true;
2673 if (ForwardSwitchConditionToPHI(SI))
2674 return SimplifyCFG(BB) | true;
2679 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2680 BasicBlock *BB = IBI->getParent();
2681 bool Changed = false;
2683 // Eliminate redundant destinations.
2684 SmallPtrSet<Value *, 8> Succs;
2685 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2686 BasicBlock *Dest = IBI->getDestination(i);
2687 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2688 Dest->removePredecessor(BB);
2689 IBI->removeDestination(i);
2695 if (IBI->getNumDestinations() == 0) {
2696 // If the indirectbr has no successors, change it to unreachable.
2697 new UnreachableInst(IBI->getContext(), IBI);
2698 EraseTerminatorInstAndDCECond(IBI);
2702 if (IBI->getNumDestinations() == 1) {
2703 // If the indirectbr has one successor, change it to a direct branch.
2704 BranchInst::Create(IBI->getDestination(0), IBI);
2705 EraseTerminatorInstAndDCECond(IBI);
2709 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2710 if (SimplifyIndirectBrOnSelect(IBI, SI))
2711 return SimplifyCFG(BB) | true;
2716 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
2717 BasicBlock *BB = BI->getParent();
2719 // If the Terminator is the only non-phi instruction, simplify the block.
2720 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
2721 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2722 TryToSimplifyUncondBranchFromEmptyBlock(BB))
2725 // If the only instruction in the block is a seteq/setne comparison
2726 // against a constant, try to simplify the block.
2727 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2728 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2729 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2731 if (I->isTerminator() &&
2732 TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
2740 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
2741 BasicBlock *BB = BI->getParent();
2743 // Conditional branch
2744 if (isValueEqualityComparison(BI)) {
2745 // If we only have one predecessor, and if it is a branch on this value,
2746 // see if that predecessor totally determines the outcome of this
2748 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2749 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
2750 return SimplifyCFG(BB) | true;
2752 // This block must be empty, except for the setcond inst, if it exists.
2753 // Ignore dbg intrinsics.
2754 BasicBlock::iterator I = BB->begin();
2755 // Ignore dbg intrinsics.
2756 while (isa<DbgInfoIntrinsic>(I))
2759 if (FoldValueComparisonIntoPredecessors(BI, Builder))
2760 return SimplifyCFG(BB) | true;
2761 } else if (&*I == cast<Instruction>(BI->getCondition())){
2763 // Ignore dbg intrinsics.
2764 while (isa<DbgInfoIntrinsic>(I))
2766 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
2767 return SimplifyCFG(BB) | true;
2771 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
2772 if (SimplifyBranchOnICmpChain(BI, TD, Builder))
2775 // We have a conditional branch to two blocks that are only reachable
2776 // from BI. We know that the condbr dominates the two blocks, so see if
2777 // there is any identical code in the "then" and "else" blocks. If so, we
2778 // can hoist it up to the branching block.
2779 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2780 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2781 if (HoistThenElseCodeToIf(BI))
2782 return SimplifyCFG(BB) | true;
2784 // If Successor #1 has multiple preds, we may be able to conditionally
2785 // execute Successor #0 if it branches to successor #1.
2786 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2787 if (Succ0TI->getNumSuccessors() == 1 &&
2788 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
2789 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
2790 return SimplifyCFG(BB) | true;
2792 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2793 // If Successor #0 has multiple preds, we may be able to conditionally
2794 // execute Successor #1 if it branches to successor #0.
2795 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2796 if (Succ1TI->getNumSuccessors() == 1 &&
2797 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
2798 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
2799 return SimplifyCFG(BB) | true;
2802 // If this is a branch on a phi node in the current block, thread control
2803 // through this block if any PHI node entries are constants.
2804 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2805 if (PN->getParent() == BI->getParent())
2806 if (FoldCondBranchOnPHI(BI, TD))
2807 return SimplifyCFG(BB) | true;
2809 // If this basic block is ONLY a compare and a branch, and if a predecessor
2810 // branches to us and one of our successors, fold the comparison into the
2811 // predecessor and use logical operations to pick the right destination.
2812 if (FoldBranchToCommonDest(BI))
2813 return SimplifyCFG(BB) | true;
2815 // Scan predecessor blocks for conditional branches.
2816 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2817 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2818 if (PBI != BI && PBI->isConditional())
2819 if (SimplifyCondBranchToCondBranch(PBI, BI))
2820 return SimplifyCFG(BB) | true;
2825 /// Check if passing a value to an instruction will cause undefined behavior.
2826 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
2827 Constant *C = dyn_cast<Constant>(V);
2831 if (!I->hasOneUse()) // Only look at single-use instructions, for compile time
2834 if (C->isNullValue()) {
2835 Instruction *Use = I->use_back();
2837 // Now make sure that there are no instructions in between that can alter
2838 // control flow (eg. calls)
2839 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
2840 if (i == I->getParent()->end() || i->mayHaveSideEffects())
2843 // Look through GEPs. A load from a GEP derived from NULL is still undefined
2844 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
2845 if (GEP->getPointerOperand() == I)
2846 return passingValueIsAlwaysUndefined(V, GEP);
2848 // Look through bitcasts.
2849 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
2850 return passingValueIsAlwaysUndefined(V, BC);
2852 // Load from null is undefined.
2853 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
2854 return LI->getPointerAddressSpace() == 0;
2856 // Store to null is undefined.
2857 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
2858 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
2863 /// If BB has an incoming value that will always trigger undefined behavior
2864 /// (eg. null pointer dereference), remove the branch leading here.
2865 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
2866 for (BasicBlock::iterator i = BB->begin();
2867 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
2868 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
2869 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
2870 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
2871 IRBuilder<> Builder(T);
2872 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
2873 BB->removePredecessor(PHI->getIncomingBlock(i));
2874 // Turn uncoditional branches into unreachables and remove the dead
2875 // destination from conditional branches.
2876 if (BI->isUnconditional())
2877 Builder.CreateUnreachable();
2879 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
2880 BI->getSuccessor(0));
2881 BI->eraseFromParent();
2884 // TODO: SwitchInst.
2890 bool SimplifyCFGOpt::run(BasicBlock *BB) {
2891 bool Changed = false;
2893 assert(BB && BB->getParent() && "Block not embedded in function!");
2894 assert(BB->getTerminator() && "Degenerate basic block encountered!");
2896 // Remove basic blocks that have no predecessors (except the entry block)...
2897 // or that just have themself as a predecessor. These are unreachable.
2898 if ((pred_begin(BB) == pred_end(BB) &&
2899 BB != &BB->getParent()->getEntryBlock()) ||
2900 BB->getSinglePredecessor() == BB) {
2901 DEBUG(dbgs() << "Removing BB: \n" << *BB);
2902 DeleteDeadBlock(BB);
2906 // Check to see if we can constant propagate this terminator instruction
2908 Changed |= ConstantFoldTerminator(BB, true);
2910 // Check for and eliminate duplicate PHI nodes in this block.
2911 Changed |= EliminateDuplicatePHINodes(BB);
2913 // Check for and remove branches that will always cause undefined behavior.
2914 Changed |= removeUndefIntroducingPredecessor(BB);
2916 // Merge basic blocks into their predecessor if there is only one distinct
2917 // pred, and if there is only one distinct successor of the predecessor, and
2918 // if there are no PHI nodes.
2920 if (MergeBlockIntoPredecessor(BB))
2923 IRBuilder<> Builder(BB);
2925 // If there is a trivial two-entry PHI node in this basic block, and we can
2926 // eliminate it, do so now.
2927 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
2928 if (PN->getNumIncomingValues() == 2)
2929 Changed |= FoldTwoEntryPHINode(PN, TD);
2931 Builder.SetInsertPoint(BB->getTerminator());
2932 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
2933 if (BI->isUnconditional()) {
2934 if (SimplifyUncondBranch(BI, Builder)) return true;
2936 if (SimplifyCondBranch(BI, Builder)) return true;
2938 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
2939 if (SimplifyResume(RI, Builder)) return true;
2940 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
2941 if (SimplifyReturn(RI, Builder)) return true;
2942 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2943 if (SimplifySwitch(SI, Builder)) return true;
2944 } else if (UnreachableInst *UI =
2945 dyn_cast<UnreachableInst>(BB->getTerminator())) {
2946 if (SimplifyUnreachable(UI)) return true;
2947 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
2948 if (SimplifyUnwind(UI, Builder)) return true;
2949 } else if (IndirectBrInst *IBI =
2950 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
2951 if (SimplifyIndirectBr(IBI)) return true;
2957 /// SimplifyCFG - This function is used to do simplification of a CFG. For
2958 /// example, it adjusts branches to branches to eliminate the extra hop, it
2959 /// eliminates unreachable basic blocks, and does other "peephole" optimization
2960 /// of the CFG. It returns true if a modification was made.
2962 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2963 return SimplifyCFGOpt(TD).run(BB);