PGO: create metadata for switch only if it has more than one targets.
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Peephole optimize the CFG.
11 //
12 //===----------------------------------------------------------------------===//
13
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/IRBuilder.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/MDBuilder.h"
24 #include "llvm/Metadata.h"
25 #include "llvm/Module.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/InstructionSimplify.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ConstantRange.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/NoFolder.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/DataLayout.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include <algorithm>
45 #include <set>
46 #include <map>
47 using namespace llvm;
48
49 static cl::opt<unsigned>
50 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
51    cl::desc("Control the amount of phi node folding to perform (default = 1)"));
52
53 static cl::opt<bool>
54 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
55        cl::desc("Duplicate return instructions into unconditional branches"));
56
57 static cl::opt<bool>
58 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
59        cl::desc("Sink common instructions down to the end block"));
60
61 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
62 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
63 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
64 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
65
66 namespace {
67   /// ValueEqualityComparisonCase - Represents a case of a switch.
68   struct ValueEqualityComparisonCase {
69     ConstantInt *Value;
70     BasicBlock *Dest;
71
72     ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
73       : Value(Value), Dest(Dest) {}
74
75     bool operator<(ValueEqualityComparisonCase RHS) const {
76       // Comparing pointers is ok as we only rely on the order for uniquing.
77       return Value < RHS.Value;
78     }
79   };
80
81 class SimplifyCFGOpt {
82   const DataLayout *const TD;
83
84   Value *isValueEqualityComparison(TerminatorInst *TI);
85   BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
86                                std::vector<ValueEqualityComparisonCase> &Cases);
87   bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
88                                                      BasicBlock *Pred,
89                                                      IRBuilder<> &Builder);
90   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
91                                            IRBuilder<> &Builder);
92
93   bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
94   bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
95   bool SimplifyUnreachable(UnreachableInst *UI);
96   bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
97   bool SimplifyIndirectBr(IndirectBrInst *IBI);
98   bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
99   bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
100
101 public:
102   explicit SimplifyCFGOpt(const DataLayout *td) : TD(td) {}
103   bool run(BasicBlock *BB);
104 };
105 }
106
107 /// SafeToMergeTerminators - Return true if it is safe to merge these two
108 /// terminator instructions together.
109 ///
110 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
111   if (SI1 == SI2) return false;  // Can't merge with self!
112
113   // It is not safe to merge these two switch instructions if they have a common
114   // successor, and if that successor has a PHI node, and if *that* PHI node has
115   // conflicting incoming values from the two switch blocks.
116   BasicBlock *SI1BB = SI1->getParent();
117   BasicBlock *SI2BB = SI2->getParent();
118   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
119
120   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
121     if (SI1Succs.count(*I))
122       for (BasicBlock::iterator BBI = (*I)->begin();
123            isa<PHINode>(BBI); ++BBI) {
124         PHINode *PN = cast<PHINode>(BBI);
125         if (PN->getIncomingValueForBlock(SI1BB) !=
126             PN->getIncomingValueForBlock(SI2BB))
127           return false;
128       }
129
130   return true;
131 }
132
133 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
134 /// to merge these two terminator instructions together, where SI1 is an
135 /// unconditional branch. PhiNodes will store all PHI nodes in common
136 /// successors.
137 ///
138 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
139                                           BranchInst *SI2,
140                                           Instruction *Cond,
141                                           SmallVectorImpl<PHINode*> &PhiNodes) {
142   if (SI1 == SI2) return false;  // Can't merge with self!
143   assert(SI1->isUnconditional() && SI2->isConditional());
144
145   // We fold the unconditional branch if we can easily update all PHI nodes in
146   // common successors:
147   // 1> We have a constant incoming value for the conditional branch;
148   // 2> We have "Cond" as the incoming value for the unconditional branch;
149   // 3> SI2->getCondition() and Cond have same operands.
150   CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
151   if (!Ci2) return false;
152   if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
153         Cond->getOperand(1) == Ci2->getOperand(1)) &&
154       !(Cond->getOperand(0) == Ci2->getOperand(1) &&
155         Cond->getOperand(1) == Ci2->getOperand(0)))
156     return false;
157
158   BasicBlock *SI1BB = SI1->getParent();
159   BasicBlock *SI2BB = SI2->getParent();
160   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
161   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
162     if (SI1Succs.count(*I))
163       for (BasicBlock::iterator BBI = (*I)->begin();
164            isa<PHINode>(BBI); ++BBI) {
165         PHINode *PN = cast<PHINode>(BBI);
166         if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
167             !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
168           return false;
169         PhiNodes.push_back(PN);
170       }
171   return true;
172 }
173
174 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
175 /// now be entries in it from the 'NewPred' block.  The values that will be
176 /// flowing into the PHI nodes will be the same as those coming in from
177 /// ExistPred, an existing predecessor of Succ.
178 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
179                                   BasicBlock *ExistPred) {
180   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
181
182   PHINode *PN;
183   for (BasicBlock::iterator I = Succ->begin();
184        (PN = dyn_cast<PHINode>(I)); ++I)
185     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
186 }
187
188
189 /// GetIfCondition - Given a basic block (BB) with two predecessors (and at
190 /// least one PHI node in it), check to see if the merge at this block is due
191 /// to an "if condition".  If so, return the boolean condition that determines
192 /// which entry into BB will be taken.  Also, return by references the block
193 /// that will be entered from if the condition is true, and the block that will
194 /// be entered if the condition is false.
195 ///
196 /// This does no checking to see if the true/false blocks have large or unsavory
197 /// instructions in them.
198 static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
199                              BasicBlock *&IfFalse) {
200   PHINode *SomePHI = cast<PHINode>(BB->begin());
201   assert(SomePHI->getNumIncomingValues() == 2 &&
202          "Function can only handle blocks with 2 predecessors!");
203   BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
204   BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
205
206   // We can only handle branches.  Other control flow will be lowered to
207   // branches if possible anyway.
208   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
209   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
210   if (Pred1Br == 0 || Pred2Br == 0)
211     return 0;
212
213   // Eliminate code duplication by ensuring that Pred1Br is conditional if
214   // either are.
215   if (Pred2Br->isConditional()) {
216     // If both branches are conditional, we don't have an "if statement".  In
217     // reality, we could transform this case, but since the condition will be
218     // required anyway, we stand no chance of eliminating it, so the xform is
219     // probably not profitable.
220     if (Pred1Br->isConditional())
221       return 0;
222
223     std::swap(Pred1, Pred2);
224     std::swap(Pred1Br, Pred2Br);
225   }
226
227   if (Pred1Br->isConditional()) {
228     // The only thing we have to watch out for here is to make sure that Pred2
229     // doesn't have incoming edges from other blocks.  If it does, the condition
230     // doesn't dominate BB.
231     if (Pred2->getSinglePredecessor() == 0)
232       return 0;
233
234     // If we found a conditional branch predecessor, make sure that it branches
235     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
236     if (Pred1Br->getSuccessor(0) == BB &&
237         Pred1Br->getSuccessor(1) == Pred2) {
238       IfTrue = Pred1;
239       IfFalse = Pred2;
240     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
241                Pred1Br->getSuccessor(1) == BB) {
242       IfTrue = Pred2;
243       IfFalse = Pred1;
244     } else {
245       // We know that one arm of the conditional goes to BB, so the other must
246       // go somewhere unrelated, and this must not be an "if statement".
247       return 0;
248     }
249
250     return Pred1Br->getCondition();
251   }
252
253   // Ok, if we got here, both predecessors end with an unconditional branch to
254   // BB.  Don't panic!  If both blocks only have a single (identical)
255   // predecessor, and THAT is a conditional branch, then we're all ok!
256   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
257   if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
258     return 0;
259
260   // Otherwise, if this is a conditional branch, then we can use it!
261   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
262   if (BI == 0) return 0;
263
264   assert(BI->isConditional() && "Two successors but not conditional?");
265   if (BI->getSuccessor(0) == Pred1) {
266     IfTrue = Pred1;
267     IfFalse = Pred2;
268   } else {
269     IfTrue = Pred2;
270     IfFalse = Pred1;
271   }
272   return BI->getCondition();
273 }
274
275 /// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
276 /// given instruction, which is assumed to be safe to speculate. 1 means
277 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
278 static unsigned ComputeSpeculationCost(const User *I) {
279   assert(isSafeToSpeculativelyExecute(I) &&
280          "Instruction is not safe to speculatively execute!");
281   switch (Operator::getOpcode(I)) {
282   default:
283     // In doubt, be conservative.
284     return UINT_MAX;
285   case Instruction::GetElementPtr:
286     // GEPs are cheap if all indices are constant.
287     if (!cast<GEPOperator>(I)->hasAllConstantIndices())
288       return UINT_MAX;
289     return 1;
290   case Instruction::Load:
291   case Instruction::Add:
292   case Instruction::Sub:
293   case Instruction::And:
294   case Instruction::Or:
295   case Instruction::Xor:
296   case Instruction::Shl:
297   case Instruction::LShr:
298   case Instruction::AShr:
299   case Instruction::ICmp:
300   case Instruction::Trunc:
301   case Instruction::ZExt:
302   case Instruction::SExt:
303     return 1; // These are all cheap.
304
305   case Instruction::Call:
306   case Instruction::Select:
307     return 2;
308   }
309 }
310
311 /// DominatesMergePoint - If we have a merge point of an "if condition" as
312 /// accepted above, return true if the specified value dominates the block.  We
313 /// don't handle the true generality of domination here, just a special case
314 /// which works well enough for us.
315 ///
316 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
317 /// see if V (which must be an instruction) and its recursive operands
318 /// that do not dominate BB have a combined cost lower than CostRemaining and
319 /// are non-trapping.  If both are true, the instruction is inserted into the
320 /// set and true is returned.
321 ///
322 /// The cost for most non-trapping instructions is defined as 1 except for
323 /// Select whose cost is 2.
324 ///
325 /// After this function returns, CostRemaining is decreased by the cost of
326 /// V plus its non-dominating operands.  If that cost is greater than
327 /// CostRemaining, false is returned and CostRemaining is undefined.
328 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
329                                 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
330                                 unsigned &CostRemaining) {
331   Instruction *I = dyn_cast<Instruction>(V);
332   if (!I) {
333     // Non-instructions all dominate instructions, but not all constantexprs
334     // can be executed unconditionally.
335     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
336       if (C->canTrap())
337         return false;
338     return true;
339   }
340   BasicBlock *PBB = I->getParent();
341
342   // We don't want to allow weird loops that might have the "if condition" in
343   // the bottom of this block.
344   if (PBB == BB) return false;
345
346   // If this instruction is defined in a block that contains an unconditional
347   // branch to BB, then it must be in the 'conditional' part of the "if
348   // statement".  If not, it definitely dominates the region.
349   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
350   if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
351     return true;
352
353   // If we aren't allowing aggressive promotion anymore, then don't consider
354   // instructions in the 'if region'.
355   if (AggressiveInsts == 0) return false;
356
357   // If we have seen this instruction before, don't count it again.
358   if (AggressiveInsts->count(I)) return true;
359
360   // Okay, it looks like the instruction IS in the "condition".  Check to
361   // see if it's a cheap instruction to unconditionally compute, and if it
362   // only uses stuff defined outside of the condition.  If so, hoist it out.
363   if (!isSafeToSpeculativelyExecute(I))
364     return false;
365
366   unsigned Cost = ComputeSpeculationCost(I);
367
368   if (Cost > CostRemaining)
369     return false;
370
371   CostRemaining -= Cost;
372
373   // Okay, we can only really hoist these out if their operands do
374   // not take us over the cost threshold.
375   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
376     if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
377       return false;
378   // Okay, it's safe to do this!  Remember this instruction.
379   AggressiveInsts->insert(I);
380   return true;
381 }
382
383 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
384 /// and PointerNullValue. Return NULL if value is not a constant int.
385 static ConstantInt *GetConstantInt(Value *V, const DataLayout *TD) {
386   // Normal constant int.
387   ConstantInt *CI = dyn_cast<ConstantInt>(V);
388   if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
389     return CI;
390
391   // This is some kind of pointer constant. Turn it into a pointer-sized
392   // ConstantInt if possible.
393   IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
394
395   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
396   if (isa<ConstantPointerNull>(V))
397     return ConstantInt::get(PtrTy, 0);
398
399   // IntToPtr const int.
400   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
401     if (CE->getOpcode() == Instruction::IntToPtr)
402       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
403         // The constant is very likely to have the right type already.
404         if (CI->getType() == PtrTy)
405           return CI;
406         else
407           return cast<ConstantInt>
408             (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
409       }
410   return 0;
411 }
412
413 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
414 /// collection of icmp eq/ne instructions that compare a value against a
415 /// constant, return the value being compared, and stick the constant into the
416 /// Values vector.
417 static Value *
418 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
419                        const DataLayout *TD, bool isEQ, unsigned &UsedICmps) {
420   Instruction *I = dyn_cast<Instruction>(V);
421   if (I == 0) return 0;
422
423   // If this is an icmp against a constant, handle this as one of the cases.
424   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
425     if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
426       if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
427         UsedICmps++;
428         Vals.push_back(C);
429         return I->getOperand(0);
430       }
431
432       // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
433       // the set.
434       ConstantRange Span =
435         ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
436
437       // If this is an and/!= check then we want to optimize "x ugt 2" into
438       // x != 0 && x != 1.
439       if (!isEQ)
440         Span = Span.inverse();
441
442       // If there are a ton of values, we don't want to make a ginormous switch.
443       if (Span.getSetSize().ugt(8) || Span.isEmptySet())
444         return 0;
445
446       for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
447         Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
448       UsedICmps++;
449       return I->getOperand(0);
450     }
451     return 0;
452   }
453
454   // Otherwise, we can only handle an | or &, depending on isEQ.
455   if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
456     return 0;
457
458   unsigned NumValsBeforeLHS = Vals.size();
459   unsigned UsedICmpsBeforeLHS = UsedICmps;
460   if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
461                                           isEQ, UsedICmps)) {
462     unsigned NumVals = Vals.size();
463     unsigned UsedICmpsBeforeRHS = UsedICmps;
464     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
465                                             isEQ, UsedICmps)) {
466       if (LHS == RHS)
467         return LHS;
468       Vals.resize(NumVals);
469       UsedICmps = UsedICmpsBeforeRHS;
470     }
471
472     // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
473     // set it and return success.
474     if (Extra == 0 || Extra == I->getOperand(1)) {
475       Extra = I->getOperand(1);
476       return LHS;
477     }
478
479     Vals.resize(NumValsBeforeLHS);
480     UsedICmps = UsedICmpsBeforeLHS;
481     return 0;
482   }
483
484   // If the LHS can't be folded in, but Extra is available and RHS can, try to
485   // use LHS as Extra.
486   if (Extra == 0 || Extra == I->getOperand(0)) {
487     Value *OldExtra = Extra;
488     Extra = I->getOperand(0);
489     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
490                                             isEQ, UsedICmps))
491       return RHS;
492     assert(Vals.size() == NumValsBeforeLHS);
493     Extra = OldExtra;
494   }
495
496   return 0;
497 }
498
499 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
500   Instruction *Cond = 0;
501   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
502     Cond = dyn_cast<Instruction>(SI->getCondition());
503   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
504     if (BI->isConditional())
505       Cond = dyn_cast<Instruction>(BI->getCondition());
506   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
507     Cond = dyn_cast<Instruction>(IBI->getAddress());
508   }
509
510   TI->eraseFromParent();
511   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
512 }
513
514 /// isValueEqualityComparison - Return true if the specified terminator checks
515 /// to see if a value is equal to constant integer value.
516 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
517   Value *CV = 0;
518   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
519     // Do not permit merging of large switch instructions into their
520     // predecessors unless there is only one predecessor.
521     if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
522                                              pred_end(SI->getParent())) <= 128)
523       CV = SI->getCondition();
524   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
525     if (BI->isConditional() && BI->getCondition()->hasOneUse())
526       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
527         if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
528              ICI->getPredicate() == ICmpInst::ICMP_NE) &&
529             GetConstantInt(ICI->getOperand(1), TD))
530           CV = ICI->getOperand(0);
531
532   // Unwrap any lossless ptrtoint cast.
533   if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
534     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
535       CV = PTII->getOperand(0);
536   return CV;
537 }
538
539 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
540 /// decode all of the 'cases' that it represents and return the 'default' block.
541 BasicBlock *SimplifyCFGOpt::
542 GetValueEqualityComparisonCases(TerminatorInst *TI,
543                                 std::vector<ValueEqualityComparisonCase>
544                                                                        &Cases) {
545   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
546     Cases.reserve(SI->getNumCases());
547     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
548       Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
549                                                   i.getCaseSuccessor()));
550     return SI->getDefaultDest();
551   }
552
553   BranchInst *BI = cast<BranchInst>(TI);
554   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
555   BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
556   Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
557                                                              TD),
558                                               Succ));
559   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
560 }
561
562
563 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
564 /// in the list that match the specified block.
565 static void EliminateBlockCases(BasicBlock *BB,
566                               std::vector<ValueEqualityComparisonCase> &Cases) {
567   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
568     if (Cases[i].Dest == BB) {
569       Cases.erase(Cases.begin()+i);
570       --i; --e;
571     }
572 }
573
574 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
575 /// well.
576 static bool
577 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
578               std::vector<ValueEqualityComparisonCase > &C2) {
579   std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
580
581   // Make V1 be smaller than V2.
582   if (V1->size() > V2->size())
583     std::swap(V1, V2);
584
585   if (V1->size() == 0) return false;
586   if (V1->size() == 1) {
587     // Just scan V2.
588     ConstantInt *TheVal = (*V1)[0].Value;
589     for (unsigned i = 0, e = V2->size(); i != e; ++i)
590       if (TheVal == (*V2)[i].Value)
591         return true;
592   }
593
594   // Otherwise, just sort both lists and compare element by element.
595   array_pod_sort(V1->begin(), V1->end());
596   array_pod_sort(V2->begin(), V2->end());
597   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
598   while (i1 != e1 && i2 != e2) {
599     if ((*V1)[i1].Value == (*V2)[i2].Value)
600       return true;
601     if ((*V1)[i1].Value < (*V2)[i2].Value)
602       ++i1;
603     else
604       ++i2;
605   }
606   return false;
607 }
608
609 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
610 /// terminator instruction and its block is known to only have a single
611 /// predecessor block, check to see if that predecessor is also a value
612 /// comparison with the same value, and if that comparison determines the
613 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
614 /// form of jump threading.
615 bool SimplifyCFGOpt::
616 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
617                                               BasicBlock *Pred,
618                                               IRBuilder<> &Builder) {
619   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
620   if (!PredVal) return false;  // Not a value comparison in predecessor.
621
622   Value *ThisVal = isValueEqualityComparison(TI);
623   assert(ThisVal && "This isn't a value comparison!!");
624   if (ThisVal != PredVal) return false;  // Different predicates.
625
626   // TODO: Preserve branch weight metadata, similarly to how
627   // FoldValueComparisonIntoPredecessors preserves it.
628
629   // Find out information about when control will move from Pred to TI's block.
630   std::vector<ValueEqualityComparisonCase> PredCases;
631   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
632                                                         PredCases);
633   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
634
635   // Find information about how control leaves this block.
636   std::vector<ValueEqualityComparisonCase> ThisCases;
637   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
638   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
639
640   // If TI's block is the default block from Pred's comparison, potentially
641   // simplify TI based on this knowledge.
642   if (PredDef == TI->getParent()) {
643     // If we are here, we know that the value is none of those cases listed in
644     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
645     // can simplify TI.
646     if (!ValuesOverlap(PredCases, ThisCases))
647       return false;
648
649     if (isa<BranchInst>(TI)) {
650       // Okay, one of the successors of this condbr is dead.  Convert it to a
651       // uncond br.
652       assert(ThisCases.size() == 1 && "Branch can only have one case!");
653       // Insert the new branch.
654       Instruction *NI = Builder.CreateBr(ThisDef);
655       (void) NI;
656
657       // Remove PHI node entries for the dead edge.
658       ThisCases[0].Dest->removePredecessor(TI->getParent());
659
660       DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
661            << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
662
663       EraseTerminatorInstAndDCECond(TI);
664       return true;
665     }
666
667     SwitchInst *SI = cast<SwitchInst>(TI);
668     // Okay, TI has cases that are statically dead, prune them away.
669     SmallPtrSet<Constant*, 16> DeadCases;
670     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
671       DeadCases.insert(PredCases[i].Value);
672
673     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
674                  << "Through successor TI: " << *TI);
675
676     // Collect branch weights into a vector.
677     SmallVector<uint32_t, 8> Weights;
678     MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
679     bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
680     if (HasWeight)
681       for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
682            ++MD_i) {
683         ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
684         assert(CI);
685         Weights.push_back(CI->getValue().getZExtValue());
686       }
687     for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
688       --i;
689       if (DeadCases.count(i.getCaseValue())) {
690         if (HasWeight) {
691           std::swap(Weights[i.getCaseIndex()+1], Weights.back());
692           Weights.pop_back();
693         }
694         i.getCaseSuccessor()->removePredecessor(TI->getParent());
695         SI->removeCase(i);
696       }
697     }
698     if (HasWeight && Weights.size() >= 2)
699       SI->setMetadata(LLVMContext::MD_prof,
700                       MDBuilder(SI->getParent()->getContext()).
701                       createBranchWeights(Weights));
702
703     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
704     return true;
705   }
706
707   // Otherwise, TI's block must correspond to some matched value.  Find out
708   // which value (or set of values) this is.
709   ConstantInt *TIV = 0;
710   BasicBlock *TIBB = TI->getParent();
711   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
712     if (PredCases[i].Dest == TIBB) {
713       if (TIV != 0)
714         return false;  // Cannot handle multiple values coming to this block.
715       TIV = PredCases[i].Value;
716     }
717   assert(TIV && "No edge from pred to succ?");
718
719   // Okay, we found the one constant that our value can be if we get into TI's
720   // BB.  Find out which successor will unconditionally be branched to.
721   BasicBlock *TheRealDest = 0;
722   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
723     if (ThisCases[i].Value == TIV) {
724       TheRealDest = ThisCases[i].Dest;
725       break;
726     }
727
728   // If not handled by any explicit cases, it is handled by the default case.
729   if (TheRealDest == 0) TheRealDest = ThisDef;
730
731   // Remove PHI node entries for dead edges.
732   BasicBlock *CheckEdge = TheRealDest;
733   for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
734     if (*SI != CheckEdge)
735       (*SI)->removePredecessor(TIBB);
736     else
737       CheckEdge = 0;
738
739   // Insert the new branch.
740   Instruction *NI = Builder.CreateBr(TheRealDest);
741   (void) NI;
742
743   DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
744             << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
745
746   EraseTerminatorInstAndDCECond(TI);
747   return true;
748 }
749
750 namespace {
751   /// ConstantIntOrdering - This class implements a stable ordering of constant
752   /// integers that does not depend on their address.  This is important for
753   /// applications that sort ConstantInt's to ensure uniqueness.
754   struct ConstantIntOrdering {
755     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
756       return LHS->getValue().ult(RHS->getValue());
757     }
758   };
759 }
760
761 static int ConstantIntSortPredicate(const void *P1, const void *P2) {
762   const ConstantInt *LHS = *(const ConstantInt*const*)P1;
763   const ConstantInt *RHS = *(const ConstantInt*const*)P2;
764   if (LHS->getValue().ult(RHS->getValue()))
765     return 1;
766   if (LHS->getValue() == RHS->getValue())
767     return 0;
768   return -1;
769 }
770
771 static inline bool HasBranchWeights(const Instruction* I) {
772   MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
773   if (ProfMD && ProfMD->getOperand(0))
774     if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
775       return MDS->getString().equals("branch_weights");
776
777   return false;
778 }
779
780 /// Get Weights of a given TerminatorInst, the default weight is at the front
781 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
782 /// metadata.
783 static void GetBranchWeights(TerminatorInst *TI,
784                              SmallVectorImpl<uint64_t> &Weights) {
785   MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
786   assert(MD);
787   for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
788     ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(i));
789     assert(CI);
790     Weights.push_back(CI->getValue().getZExtValue());
791   }
792
793   // If TI is a conditional eq, the default case is the false case,
794   // and the corresponding branch-weight data is at index 2. We swap the
795   // default weight to be the first entry.
796   if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
797     assert(Weights.size() == 2);
798     ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
799     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
800       std::swap(Weights.front(), Weights.back());
801   }
802 }
803
804 /// Sees if any of the weights are too big for a uint32_t, and halves all the
805 /// weights if any are.
806 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
807   bool Halve = false;
808   for (unsigned i = 0; i < Weights.size(); ++i)
809     if (Weights[i] > UINT_MAX) {
810       Halve = true;
811       break;
812     }
813
814   if (! Halve)
815     return;
816
817   for (unsigned i = 0; i < Weights.size(); ++i)
818     Weights[i] /= 2;
819 }
820
821 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
822 /// equality comparison instruction (either a switch or a branch on "X == c").
823 /// See if any of the predecessors of the terminator block are value comparisons
824 /// on the same value.  If so, and if safe to do so, fold them together.
825 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
826                                                          IRBuilder<> &Builder) {
827   BasicBlock *BB = TI->getParent();
828   Value *CV = isValueEqualityComparison(TI);  // CondVal
829   assert(CV && "Not a comparison?");
830   bool Changed = false;
831
832   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
833   while (!Preds.empty()) {
834     BasicBlock *Pred = Preds.pop_back_val();
835
836     // See if the predecessor is a comparison with the same value.
837     TerminatorInst *PTI = Pred->getTerminator();
838     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
839
840     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
841       // Figure out which 'cases' to copy from SI to PSI.
842       std::vector<ValueEqualityComparisonCase> BBCases;
843       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
844
845       std::vector<ValueEqualityComparisonCase> PredCases;
846       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
847
848       // Based on whether the default edge from PTI goes to BB or not, fill in
849       // PredCases and PredDefault with the new switch cases we would like to
850       // build.
851       SmallVector<BasicBlock*, 8> NewSuccessors;
852
853       // Update the branch weight metadata along the way
854       SmallVector<uint64_t, 8> Weights;
855       bool PredHasWeights = HasBranchWeights(PTI);
856       bool SuccHasWeights = HasBranchWeights(TI);
857
858       if (PredHasWeights) {
859         GetBranchWeights(PTI, Weights);
860         // branch-weight metadata is inconsistant here.
861         if (Weights.size() != 1 + PredCases.size())
862           PredHasWeights = SuccHasWeights = false;
863       } else if (SuccHasWeights)
864         // If there are no predecessor weights but there are successor weights,
865         // populate Weights with 1, which will later be scaled to the sum of
866         // successor's weights
867         Weights.assign(1 + PredCases.size(), 1);
868
869       SmallVector<uint64_t, 8> SuccWeights;
870       if (SuccHasWeights) {
871         GetBranchWeights(TI, SuccWeights);
872         // branch-weight metadata is inconsistant here.
873         if (SuccWeights.size() != 1 + BBCases.size())
874           PredHasWeights = SuccHasWeights = false;
875       } else if (PredHasWeights)
876         SuccWeights.assign(1 + BBCases.size(), 1);
877
878       if (PredDefault == BB) {
879         // If this is the default destination from PTI, only the edges in TI
880         // that don't occur in PTI, or that branch to BB will be activated.
881         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
882         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
883           if (PredCases[i].Dest != BB)
884             PTIHandled.insert(PredCases[i].Value);
885           else {
886             // The default destination is BB, we don't need explicit targets.
887             std::swap(PredCases[i], PredCases.back());
888
889             if (PredHasWeights || SuccHasWeights) {
890               // Increase weight for the default case.
891               Weights[0] += Weights[i+1];
892               std::swap(Weights[i+1], Weights.back());
893               Weights.pop_back();
894             }
895
896             PredCases.pop_back();
897             --i; --e;
898           }
899
900         // Reconstruct the new switch statement we will be building.
901         if (PredDefault != BBDefault) {
902           PredDefault->removePredecessor(Pred);
903           PredDefault = BBDefault;
904           NewSuccessors.push_back(BBDefault);
905         }
906
907         unsigned CasesFromPred = Weights.size();
908         uint64_t ValidTotalSuccWeight = 0;
909         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
910           if (!PTIHandled.count(BBCases[i].Value) &&
911               BBCases[i].Dest != BBDefault) {
912             PredCases.push_back(BBCases[i]);
913             NewSuccessors.push_back(BBCases[i].Dest);
914             if (SuccHasWeights || PredHasWeights) {
915               // The default weight is at index 0, so weight for the ith case
916               // should be at index i+1. Scale the cases from successor by
917               // PredDefaultWeight (Weights[0]).
918               Weights.push_back(Weights[0] * SuccWeights[i+1]);
919               ValidTotalSuccWeight += SuccWeights[i+1];
920             }
921           }
922
923         if (SuccHasWeights || PredHasWeights) {
924           ValidTotalSuccWeight += SuccWeights[0];
925           // Scale the cases from predecessor by ValidTotalSuccWeight.
926           for (unsigned i = 1; i < CasesFromPred; ++i)
927             Weights[i] *= ValidTotalSuccWeight;
928           // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
929           Weights[0] *= SuccWeights[0];
930         }
931       } else {
932         // If this is not the default destination from PSI, only the edges
933         // in SI that occur in PSI with a destination of BB will be
934         // activated.
935         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
936         std::map<ConstantInt*, uint64_t> WeightsForHandled;
937         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
938           if (PredCases[i].Dest == BB) {
939             PTIHandled.insert(PredCases[i].Value);
940
941             if (PredHasWeights || SuccHasWeights) {
942               WeightsForHandled[PredCases[i].Value] = Weights[i+1];
943               std::swap(Weights[i+1], Weights.back());
944               Weights.pop_back();
945             }
946
947             std::swap(PredCases[i], PredCases.back());
948             PredCases.pop_back();
949             --i; --e;
950           }
951
952         // Okay, now we know which constants were sent to BB from the
953         // predecessor.  Figure out where they will all go now.
954         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
955           if (PTIHandled.count(BBCases[i].Value)) {
956             // If this is one we are capable of getting...
957             if (PredHasWeights || SuccHasWeights)
958               Weights.push_back(WeightsForHandled[BBCases[i].Value]);
959             PredCases.push_back(BBCases[i]);
960             NewSuccessors.push_back(BBCases[i].Dest);
961             PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
962           }
963
964         // If there are any constants vectored to BB that TI doesn't handle,
965         // they must go to the default destination of TI.
966         for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
967                                     PTIHandled.begin(),
968                E = PTIHandled.end(); I != E; ++I) {
969           if (PredHasWeights || SuccHasWeights) 
970             Weights.push_back(WeightsForHandled[*I]); 
971           PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
972           NewSuccessors.push_back(BBDefault);
973         }
974       }
975
976       // Okay, at this point, we know which new successor Pred will get.  Make
977       // sure we update the number of entries in the PHI nodes for these
978       // successors.
979       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
980         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
981
982       Builder.SetInsertPoint(PTI);
983       // Convert pointer to int before we switch.
984       if (CV->getType()->isPointerTy()) {
985         assert(TD && "Cannot switch on pointer without DataLayout");
986         CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
987                                     "magicptr");
988       }
989
990       // Now that the successors are updated, create the new Switch instruction.
991       SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
992                                                PredCases.size());
993       NewSI->setDebugLoc(PTI->getDebugLoc());
994       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
995         NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
996
997       if (PredHasWeights || SuccHasWeights) {
998         // Halve the weights if any of them cannot fit in an uint32_t
999         FitWeights(Weights);
1000
1001         SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1002
1003         NewSI->setMetadata(LLVMContext::MD_prof,
1004                            MDBuilder(BB->getContext()).
1005                            createBranchWeights(MDWeights));
1006       }
1007
1008       EraseTerminatorInstAndDCECond(PTI);
1009
1010       // Okay, last check.  If BB is still a successor of PSI, then we must
1011       // have an infinite loop case.  If so, add an infinitely looping block
1012       // to handle the case to preserve the behavior of the code.
1013       BasicBlock *InfLoopBlock = 0;
1014       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1015         if (NewSI->getSuccessor(i) == BB) {
1016           if (InfLoopBlock == 0) {
1017             // Insert it at the end of the function, because it's either code,
1018             // or it won't matter if it's hot. :)
1019             InfLoopBlock = BasicBlock::Create(BB->getContext(),
1020                                               "infloop", BB->getParent());
1021             BranchInst::Create(InfLoopBlock, InfLoopBlock);
1022           }
1023           NewSI->setSuccessor(i, InfLoopBlock);
1024         }
1025
1026       Changed = true;
1027     }
1028   }
1029   return Changed;
1030 }
1031
1032 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1033 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1034 // would need to do this), we can't hoist the invoke, as there is nowhere
1035 // to put the select in this case.
1036 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1037                                 Instruction *I1, Instruction *I2) {
1038   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1039     PHINode *PN;
1040     for (BasicBlock::iterator BBI = SI->begin();
1041          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1042       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1043       Value *BB2V = PN->getIncomingValueForBlock(BB2);
1044       if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1045         return false;
1046       }
1047     }
1048   }
1049   return true;
1050 }
1051
1052 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1053 /// BB2, hoist any common code in the two blocks up into the branch block.  The
1054 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1055 static bool HoistThenElseCodeToIf(BranchInst *BI) {
1056   // This does very trivial matching, with limited scanning, to find identical
1057   // instructions in the two blocks.  In particular, we don't want to get into
1058   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
1059   // such, we currently just scan for obviously identical instructions in an
1060   // identical order.
1061   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
1062   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
1063
1064   BasicBlock::iterator BB1_Itr = BB1->begin();
1065   BasicBlock::iterator BB2_Itr = BB2->begin();
1066
1067   Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1068   // Skip debug info if it is not identical.
1069   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1070   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1071   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1072     while (isa<DbgInfoIntrinsic>(I1))
1073       I1 = BB1_Itr++;
1074     while (isa<DbgInfoIntrinsic>(I2))
1075       I2 = BB2_Itr++;
1076   }
1077   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1078       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1079     return false;
1080
1081   // If we get here, we can hoist at least one instruction.
1082   BasicBlock *BIParent = BI->getParent();
1083
1084   do {
1085     // If we are hoisting the terminator instruction, don't move one (making a
1086     // broken BB), instead clone it, and remove BI.
1087     if (isa<TerminatorInst>(I1))
1088       goto HoistTerminator;
1089
1090     // For a normal instruction, we just move one to right before the branch,
1091     // then replace all uses of the other with the first.  Finally, we remove
1092     // the now redundant second instruction.
1093     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1094     if (!I2->use_empty())
1095       I2->replaceAllUsesWith(I1);
1096     I1->intersectOptionalDataWith(I2);
1097     I2->eraseFromParent();
1098
1099     I1 = BB1_Itr++;
1100     I2 = BB2_Itr++;
1101     // Skip debug info if it is not identical.
1102     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1103     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1104     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1105       while (isa<DbgInfoIntrinsic>(I1))
1106         I1 = BB1_Itr++;
1107       while (isa<DbgInfoIntrinsic>(I2))
1108         I2 = BB2_Itr++;
1109     }
1110   } while (I1->isIdenticalToWhenDefined(I2));
1111
1112   return true;
1113
1114 HoistTerminator:
1115   // It may not be possible to hoist an invoke.
1116   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1117     return true;
1118
1119   // Okay, it is safe to hoist the terminator.
1120   Instruction *NT = I1->clone();
1121   BIParent->getInstList().insert(BI, NT);
1122   if (!NT->getType()->isVoidTy()) {
1123     I1->replaceAllUsesWith(NT);
1124     I2->replaceAllUsesWith(NT);
1125     NT->takeName(I1);
1126   }
1127
1128   IRBuilder<true, NoFolder> Builder(NT);
1129   // Hoisting one of the terminators from our successor is a great thing.
1130   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1131   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
1132   // nodes, so we insert select instruction to compute the final result.
1133   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1134   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1135     PHINode *PN;
1136     for (BasicBlock::iterator BBI = SI->begin();
1137          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1138       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1139       Value *BB2V = PN->getIncomingValueForBlock(BB2);
1140       if (BB1V == BB2V) continue;
1141
1142       // These values do not agree.  Insert a select instruction before NT
1143       // that determines the right value.
1144       SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1145       if (SI == 0)
1146         SI = cast<SelectInst>
1147           (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1148                                 BB1V->getName()+"."+BB2V->getName()));
1149
1150       // Make the PHI node use the select for all incoming values for BB1/BB2
1151       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1152         if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1153           PN->setIncomingValue(i, SI);
1154     }
1155   }
1156
1157   // Update any PHI nodes in our new successors.
1158   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1159     AddPredecessorToBlock(*SI, BIParent, BB1);
1160
1161   EraseTerminatorInstAndDCECond(BI);
1162   return true;
1163 }
1164
1165 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1166 /// check whether BBEnd has only two predecessors and the other predecessor
1167 /// ends with an unconditional branch. If it is true, sink any common code
1168 /// in the two predecessors to BBEnd.
1169 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1170   assert(BI1->isUnconditional());
1171   BasicBlock *BB1 = BI1->getParent();
1172   BasicBlock *BBEnd = BI1->getSuccessor(0);
1173
1174   // Check that BBEnd has two predecessors and the other predecessor ends with
1175   // an unconditional branch.
1176   pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1177   BasicBlock *Pred0 = *PI++;
1178   if (PI == PE) // Only one predecessor.
1179     return false;
1180   BasicBlock *Pred1 = *PI++;
1181   if (PI != PE) // More than two predecessors.
1182     return false;
1183   BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1184   BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1185   if (!BI2 || !BI2->isUnconditional())
1186     return false;
1187
1188   // Gather the PHI nodes in BBEnd.
1189   std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1190   Instruction *FirstNonPhiInBBEnd = 0;
1191   for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1192        I != E; ++I) {
1193     if (PHINode *PN = dyn_cast<PHINode>(I)) {
1194       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1195       Value *BB2V = PN->getIncomingValueForBlock(BB2); 
1196       MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1197     } else {
1198       FirstNonPhiInBBEnd = &*I;
1199       break;
1200     }
1201   }
1202   if (!FirstNonPhiInBBEnd)
1203     return false;
1204   
1205
1206   // This does very trivial matching, with limited scanning, to find identical
1207   // instructions in the two blocks.  We scan backward for obviously identical
1208   // instructions in an identical order.
1209   BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1210       RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1211       RE2 = BB2->getInstList().rend();
1212   // Skip debug info.
1213   while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1214   if (RI1 == RE1)
1215     return false;
1216   while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1217   if (RI2 == RE2)
1218     return false;
1219   // Skip the unconditional branches.
1220   ++RI1;
1221   ++RI2;
1222
1223   bool Changed = false;
1224   while (RI1 != RE1 && RI2 != RE2) {
1225     // Skip debug info.
1226     while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1227     if (RI1 == RE1)
1228       return Changed;
1229     while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1230     if (RI2 == RE2)
1231       return Changed;
1232
1233     Instruction *I1 = &*RI1, *I2 = &*RI2;
1234     // I1 and I2 should have a single use in the same PHI node, and they
1235     // perform the same operation.
1236     // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1237     if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1238         isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1239         isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1240         isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1241         I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1242         I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1243         !I1->hasOneUse() || !I2->hasOneUse() ||
1244         MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1245         MapValueFromBB1ToBB2[I1].first != I2)
1246       return Changed;
1247
1248     // Check whether we should swap the operands of ICmpInst.
1249     ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1250     bool SwapOpnds = false;
1251     if (ICmp1 && ICmp2 &&
1252         ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1253         ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1254         (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1255          ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1256       ICmp2->swapOperands();
1257       SwapOpnds = true;
1258     }
1259     if (!I1->isSameOperationAs(I2)) {
1260       if (SwapOpnds)
1261         ICmp2->swapOperands();
1262       return Changed;
1263     }
1264
1265     // The operands should be either the same or they need to be generated
1266     // with a PHI node after sinking. We only handle the case where there is
1267     // a single pair of different operands.
1268     Value *DifferentOp1 = 0, *DifferentOp2 = 0;
1269     unsigned Op1Idx = 0;
1270     for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1271       if (I1->getOperand(I) == I2->getOperand(I))
1272         continue;
1273       // Early exit if we have more-than one pair of different operands or
1274       // the different operand is already in MapValueFromBB1ToBB2.
1275       // Early exit if we need a PHI node to replace a constant.
1276       if (DifferentOp1 ||
1277           MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1278           MapValueFromBB1ToBB2.end() ||
1279           isa<Constant>(I1->getOperand(I)) ||
1280           isa<Constant>(I2->getOperand(I))) {
1281         // If we can't sink the instructions, undo the swapping.
1282         if (SwapOpnds)
1283           ICmp2->swapOperands();
1284         return Changed;
1285       }
1286       DifferentOp1 = I1->getOperand(I);
1287       Op1Idx = I;
1288       DifferentOp2 = I2->getOperand(I);
1289     }
1290
1291     // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1292     // remove (I1, I2) from MapValueFromBB1ToBB2.
1293     if (DifferentOp1) {
1294       PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1295                                        DifferentOp1->getName() + ".sink",
1296                                        BBEnd->begin());
1297       MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1298       // I1 should use NewPN instead of DifferentOp1.
1299       I1->setOperand(Op1Idx, NewPN);
1300       NewPN->addIncoming(DifferentOp1, BB1);
1301       NewPN->addIncoming(DifferentOp2, BB2);
1302       DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1303     }
1304     PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1305     MapValueFromBB1ToBB2.erase(I1);
1306
1307     DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1308     DEBUG(dbgs() << "                         " << *I2 << "\n";);
1309     // We need to update RE1 and RE2 if we are going to sink the first
1310     // instruction in the basic block down.
1311     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1312     // Sink the instruction.
1313     BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1314     if (!OldPN->use_empty())
1315       OldPN->replaceAllUsesWith(I1);
1316     OldPN->eraseFromParent();
1317
1318     if (!I2->use_empty())
1319       I2->replaceAllUsesWith(I1);
1320     I1->intersectOptionalDataWith(I2);
1321     I2->eraseFromParent();
1322
1323     if (UpdateRE1)
1324       RE1 = BB1->getInstList().rend();
1325     if (UpdateRE2)
1326       RE2 = BB2->getInstList().rend();
1327     FirstNonPhiInBBEnd = I1;
1328     NumSinkCommons++;
1329     Changed = true;
1330   }
1331   return Changed;
1332 }
1333
1334 /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
1335 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
1336 /// (for now, restricted to a single instruction that's side effect free) from
1337 /// the BB1 into the branch block to speculatively execute it.
1338 ///
1339 /// Turn
1340 /// BB:
1341 ///     %t1 = icmp
1342 ///     br i1 %t1, label %BB1, label %BB2
1343 /// BB1:
1344 ///     %t3 = add %t2, c
1345 ///     br label BB2
1346 /// BB2:
1347 /// =>
1348 /// BB:
1349 ///     %t1 = icmp
1350 ///     %t4 = add %t2, c
1351 ///     %t3 = select i1 %t1, %t2, %t3
1352 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
1353   // Only speculatively execution a single instruction (not counting the
1354   // terminator) for now.
1355   Instruction *HInst = NULL;
1356   Instruction *Term = BB1->getTerminator();
1357   for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
1358        BBI != BBE; ++BBI) {
1359     Instruction *I = BBI;
1360     // Skip debug info.
1361     if (isa<DbgInfoIntrinsic>(I)) continue;
1362     if (I == Term) break;
1363
1364     if (HInst)
1365       return false;
1366     HInst = I;
1367   }
1368
1369   BasicBlock *BIParent = BI->getParent();
1370
1371   // Check the instruction to be hoisted, if there is one.
1372   if (HInst) {
1373     // Don't hoist the instruction if it's unsafe or expensive.
1374     if (!isSafeToSpeculativelyExecute(HInst))
1375       return false;
1376     if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
1377       return false;
1378
1379     // Do not hoist the instruction if any of its operands are defined but not
1380     // used in this BB. The transformation will prevent the operand from
1381     // being sunk into the use block.
1382     for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1383          i != e; ++i) {
1384       Instruction *OpI = dyn_cast<Instruction>(*i);
1385       if (OpI && OpI->getParent() == BIParent &&
1386           !OpI->mayHaveSideEffects() &&
1387           !OpI->isUsedInBasicBlock(BIParent))
1388         return false;
1389     }
1390   }
1391
1392   // Be conservative for now. FP select instruction can often be expensive.
1393   Value *BrCond = BI->getCondition();
1394   if (isa<FCmpInst>(BrCond))
1395     return false;
1396
1397   // If BB1 is actually on the false edge of the conditional branch, remember
1398   // to swap the select operands later.
1399   bool Invert = false;
1400   if (BB1 != BI->getSuccessor(0)) {
1401     assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1402     Invert = true;
1403   }
1404
1405   // Collect interesting PHIs, and scan for hazards.
1406   SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
1407   BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
1408   for (BasicBlock::iterator I = BB2->begin();
1409        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1410     Value *BB1V = PN->getIncomingValueForBlock(BB1);
1411     Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
1412
1413     // Skip PHIs which are trivial.
1414     if (BB1V == BIParentV)
1415       continue;
1416
1417     // Check for saftey.
1418     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
1419       // An unfolded ConstantExpr could end up getting expanded into
1420       // Instructions. Don't speculate this and another instruction at
1421       // the same time.
1422       if (HInst)
1423         return false;
1424       if (!isSafeToSpeculativelyExecute(CE))
1425         return false;
1426       if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
1427         return false;
1428     }
1429
1430     // Ok, we may insert a select for this PHI.
1431     PHIs.insert(std::make_pair(BB1V, BIParentV));
1432   }
1433
1434   // If there are no PHIs to process, bail early. This helps ensure idempotence
1435   // as well.
1436   if (PHIs.empty())
1437     return false;
1438
1439   // If we get here, we can hoist the instruction and if-convert.
1440   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
1441
1442   // Hoist the instruction.
1443   if (HInst)
1444     BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
1445
1446   // Insert selects and rewrite the PHI operands.
1447   IRBuilder<true, NoFolder> Builder(BI);
1448   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
1449     Value *TrueV = PHIs[i].first;
1450     Value *FalseV = PHIs[i].second;
1451
1452     // Create a select whose true value is the speculatively executed value and
1453     // false value is the previously determined FalseV.
1454     SelectInst *SI;
1455     if (Invert)
1456       SI = cast<SelectInst>
1457         (Builder.CreateSelect(BrCond, FalseV, TrueV,
1458                               FalseV->getName() + "." + TrueV->getName()));
1459     else
1460       SI = cast<SelectInst>
1461         (Builder.CreateSelect(BrCond, TrueV, FalseV,
1462                               TrueV->getName() + "." + FalseV->getName()));
1463
1464     // Make the PHI node use the select for all incoming values for "then" and
1465     // "if" blocks.
1466     for (BasicBlock::iterator I = BB2->begin();
1467          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1468       unsigned BB1I = PN->getBasicBlockIndex(BB1);
1469       unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
1470       Value *BB1V = PN->getIncomingValue(BB1I);
1471       Value *BIParentV = PN->getIncomingValue(BIParentI);
1472       if (TrueV == BB1V && FalseV == BIParentV) {
1473         PN->setIncomingValue(BB1I, SI);
1474         PN->setIncomingValue(BIParentI, SI);
1475       }
1476     }
1477   }
1478
1479   ++NumSpeculations;
1480   return true;
1481 }
1482
1483 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1484 /// across this block.
1485 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1486   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1487   unsigned Size = 0;
1488
1489   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1490     if (isa<DbgInfoIntrinsic>(BBI))
1491       continue;
1492     if (Size > 10) return false;  // Don't clone large BB's.
1493     ++Size;
1494
1495     // We can only support instructions that do not define values that are
1496     // live outside of the current basic block.
1497     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1498          UI != E; ++UI) {
1499       Instruction *U = cast<Instruction>(*UI);
1500       if (U->getParent() != BB || isa<PHINode>(U)) return false;
1501     }
1502
1503     // Looks ok, continue checking.
1504   }
1505
1506   return true;
1507 }
1508
1509 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1510 /// that is defined in the same block as the branch and if any PHI entries are
1511 /// constants, thread edges corresponding to that entry to be branches to their
1512 /// ultimate destination.
1513 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *TD) {
1514   BasicBlock *BB = BI->getParent();
1515   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1516   // NOTE: we currently cannot transform this case if the PHI node is used
1517   // outside of the block.
1518   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1519     return false;
1520
1521   // Degenerate case of a single entry PHI.
1522   if (PN->getNumIncomingValues() == 1) {
1523     FoldSingleEntryPHINodes(PN->getParent());
1524     return true;
1525   }
1526
1527   // Now we know that this block has multiple preds and two succs.
1528   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1529
1530   // Okay, this is a simple enough basic block.  See if any phi values are
1531   // constants.
1532   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1533     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1534     if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1535
1536     // Okay, we now know that all edges from PredBB should be revectored to
1537     // branch to RealDest.
1538     BasicBlock *PredBB = PN->getIncomingBlock(i);
1539     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1540
1541     if (RealDest == BB) continue;  // Skip self loops.
1542     // Skip if the predecessor's terminator is an indirect branch.
1543     if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1544
1545     // The dest block might have PHI nodes, other predecessors and other
1546     // difficult cases.  Instead of being smart about this, just insert a new
1547     // block that jumps to the destination block, effectively splitting
1548     // the edge we are about to create.
1549     BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1550                                             RealDest->getName()+".critedge",
1551                                             RealDest->getParent(), RealDest);
1552     BranchInst::Create(RealDest, EdgeBB);
1553
1554     // Update PHI nodes.
1555     AddPredecessorToBlock(RealDest, EdgeBB, BB);
1556
1557     // BB may have instructions that are being threaded over.  Clone these
1558     // instructions into EdgeBB.  We know that there will be no uses of the
1559     // cloned instructions outside of EdgeBB.
1560     BasicBlock::iterator InsertPt = EdgeBB->begin();
1561     DenseMap<Value*, Value*> TranslateMap;  // Track translated values.
1562     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1563       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1564         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1565         continue;
1566       }
1567       // Clone the instruction.
1568       Instruction *N = BBI->clone();
1569       if (BBI->hasName()) N->setName(BBI->getName()+".c");
1570
1571       // Update operands due to translation.
1572       for (User::op_iterator i = N->op_begin(), e = N->op_end();
1573            i != e; ++i) {
1574         DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1575         if (PI != TranslateMap.end())
1576           *i = PI->second;
1577       }
1578
1579       // Check for trivial simplification.
1580       if (Value *V = SimplifyInstruction(N, TD)) {
1581         TranslateMap[BBI] = V;
1582         delete N;   // Instruction folded away, don't need actual inst
1583       } else {
1584         // Insert the new instruction into its new home.
1585         EdgeBB->getInstList().insert(InsertPt, N);
1586         if (!BBI->use_empty())
1587           TranslateMap[BBI] = N;
1588       }
1589     }
1590
1591     // Loop over all of the edges from PredBB to BB, changing them to branch
1592     // to EdgeBB instead.
1593     TerminatorInst *PredBBTI = PredBB->getTerminator();
1594     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1595       if (PredBBTI->getSuccessor(i) == BB) {
1596         BB->removePredecessor(PredBB);
1597         PredBBTI->setSuccessor(i, EdgeBB);
1598       }
1599
1600     // Recurse, simplifying any other constants.
1601     return FoldCondBranchOnPHI(BI, TD) | true;
1602   }
1603
1604   return false;
1605 }
1606
1607 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1608 /// PHI node, see if we can eliminate it.
1609 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *TD) {
1610   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1611   // statement", which has a very simple dominance structure.  Basically, we
1612   // are trying to find the condition that is being branched on, which
1613   // subsequently causes this merge to happen.  We really want control
1614   // dependence information for this check, but simplifycfg can't keep it up
1615   // to date, and this catches most of the cases we care about anyway.
1616   BasicBlock *BB = PN->getParent();
1617   BasicBlock *IfTrue, *IfFalse;
1618   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1619   if (!IfCond ||
1620       // Don't bother if the branch will be constant folded trivially.
1621       isa<ConstantInt>(IfCond))
1622     return false;
1623
1624   // Okay, we found that we can merge this two-entry phi node into a select.
1625   // Doing so would require us to fold *all* two entry phi nodes in this block.
1626   // At some point this becomes non-profitable (particularly if the target
1627   // doesn't support cmov's).  Only do this transformation if there are two or
1628   // fewer PHI nodes in this block.
1629   unsigned NumPhis = 0;
1630   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1631     if (NumPhis > 2)
1632       return false;
1633
1634   // Loop over the PHI's seeing if we can promote them all to select
1635   // instructions.  While we are at it, keep track of the instructions
1636   // that need to be moved to the dominating block.
1637   SmallPtrSet<Instruction*, 4> AggressiveInsts;
1638   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1639            MaxCostVal1 = PHINodeFoldingThreshold;
1640
1641   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1642     PHINode *PN = cast<PHINode>(II++);
1643     if (Value *V = SimplifyInstruction(PN, TD)) {
1644       PN->replaceAllUsesWith(V);
1645       PN->eraseFromParent();
1646       continue;
1647     }
1648
1649     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1650                              MaxCostVal0) ||
1651         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1652                              MaxCostVal1))
1653       return false;
1654   }
1655
1656   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
1657   // we ran out of PHIs then we simplified them all.
1658   PN = dyn_cast<PHINode>(BB->begin());
1659   if (PN == 0) return true;
1660
1661   // Don't fold i1 branches on PHIs which contain binary operators.  These can
1662   // often be turned into switches and other things.
1663   if (PN->getType()->isIntegerTy(1) &&
1664       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1665        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1666        isa<BinaryOperator>(IfCond)))
1667     return false;
1668
1669   // If we all PHI nodes are promotable, check to make sure that all
1670   // instructions in the predecessor blocks can be promoted as well.  If
1671   // not, we won't be able to get rid of the control flow, so it's not
1672   // worth promoting to select instructions.
1673   BasicBlock *DomBlock = 0;
1674   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1675   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1676   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1677     IfBlock1 = 0;
1678   } else {
1679     DomBlock = *pred_begin(IfBlock1);
1680     for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1681       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1682         // This is not an aggressive instruction that we can promote.
1683         // Because of this, we won't be able to get rid of the control
1684         // flow, so the xform is not worth it.
1685         return false;
1686       }
1687   }
1688
1689   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1690     IfBlock2 = 0;
1691   } else {
1692     DomBlock = *pred_begin(IfBlock2);
1693     for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1694       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1695         // This is not an aggressive instruction that we can promote.
1696         // Because of this, we won't be able to get rid of the control
1697         // flow, so the xform is not worth it.
1698         return false;
1699       }
1700   }
1701
1702   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1703                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
1704
1705   // If we can still promote the PHI nodes after this gauntlet of tests,
1706   // do all of the PHI's now.
1707   Instruction *InsertPt = DomBlock->getTerminator();
1708   IRBuilder<true, NoFolder> Builder(InsertPt);
1709
1710   // Move all 'aggressive' instructions, which are defined in the
1711   // conditional parts of the if's up to the dominating block.
1712   if (IfBlock1)
1713     DomBlock->getInstList().splice(InsertPt,
1714                                    IfBlock1->getInstList(), IfBlock1->begin(),
1715                                    IfBlock1->getTerminator());
1716   if (IfBlock2)
1717     DomBlock->getInstList().splice(InsertPt,
1718                                    IfBlock2->getInstList(), IfBlock2->begin(),
1719                                    IfBlock2->getTerminator());
1720
1721   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1722     // Change the PHI node into a select instruction.
1723     Value *TrueVal  = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1724     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1725
1726     SelectInst *NV =
1727       cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1728     PN->replaceAllUsesWith(NV);
1729     NV->takeName(PN);
1730     PN->eraseFromParent();
1731   }
1732
1733   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1734   // has been flattened.  Change DomBlock to jump directly to our new block to
1735   // avoid other simplifycfg's kicking in on the diamond.
1736   TerminatorInst *OldTI = DomBlock->getTerminator();
1737   Builder.SetInsertPoint(OldTI);
1738   Builder.CreateBr(BB);
1739   OldTI->eraseFromParent();
1740   return true;
1741 }
1742
1743 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1744 /// to two returning blocks, try to merge them together into one return,
1745 /// introducing a select if the return values disagree.
1746 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1747                                            IRBuilder<> &Builder) {
1748   assert(BI->isConditional() && "Must be a conditional branch");
1749   BasicBlock *TrueSucc = BI->getSuccessor(0);
1750   BasicBlock *FalseSucc = BI->getSuccessor(1);
1751   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1752   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1753
1754   // Check to ensure both blocks are empty (just a return) or optionally empty
1755   // with PHI nodes.  If there are other instructions, merging would cause extra
1756   // computation on one path or the other.
1757   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1758     return false;
1759   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1760     return false;
1761
1762   Builder.SetInsertPoint(BI);
1763   // Okay, we found a branch that is going to two return nodes.  If
1764   // there is no return value for this function, just change the
1765   // branch into a return.
1766   if (FalseRet->getNumOperands() == 0) {
1767     TrueSucc->removePredecessor(BI->getParent());
1768     FalseSucc->removePredecessor(BI->getParent());
1769     Builder.CreateRetVoid();
1770     EraseTerminatorInstAndDCECond(BI);
1771     return true;
1772   }
1773
1774   // Otherwise, figure out what the true and false return values are
1775   // so we can insert a new select instruction.
1776   Value *TrueValue = TrueRet->getReturnValue();
1777   Value *FalseValue = FalseRet->getReturnValue();
1778
1779   // Unwrap any PHI nodes in the return blocks.
1780   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1781     if (TVPN->getParent() == TrueSucc)
1782       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1783   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1784     if (FVPN->getParent() == FalseSucc)
1785       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1786
1787   // In order for this transformation to be safe, we must be able to
1788   // unconditionally execute both operands to the return.  This is
1789   // normally the case, but we could have a potentially-trapping
1790   // constant expression that prevents this transformation from being
1791   // safe.
1792   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1793     if (TCV->canTrap())
1794       return false;
1795   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1796     if (FCV->canTrap())
1797       return false;
1798
1799   // Okay, we collected all the mapped values and checked them for sanity, and
1800   // defined to really do this transformation.  First, update the CFG.
1801   TrueSucc->removePredecessor(BI->getParent());
1802   FalseSucc->removePredecessor(BI->getParent());
1803
1804   // Insert select instructions where needed.
1805   Value *BrCond = BI->getCondition();
1806   if (TrueValue) {
1807     // Insert a select if the results differ.
1808     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1809     } else if (isa<UndefValue>(TrueValue)) {
1810       TrueValue = FalseValue;
1811     } else {
1812       TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1813                                        FalseValue, "retval");
1814     }
1815   }
1816
1817   Value *RI = !TrueValue ?
1818     Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1819
1820   (void) RI;
1821
1822   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1823                << "\n  " << *BI << "NewRet = " << *RI
1824                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1825
1826   EraseTerminatorInstAndDCECond(BI);
1827
1828   return true;
1829 }
1830
1831 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1832 /// probabilities of the branch taking each edge. Fills in the two APInt
1833 /// parameters and return true, or returns false if no or invalid metadata was
1834 /// found.
1835 static bool ExtractBranchMetadata(BranchInst *BI,
1836                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
1837   assert(BI->isConditional() &&
1838          "Looking for probabilities on unconditional branch?");
1839   MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1840   if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1841   ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1842   ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1843   if (!CITrue || !CIFalse) return false;
1844   ProbTrue = CITrue->getValue().getZExtValue();
1845   ProbFalse = CIFalse->getValue().getZExtValue();
1846   return true;
1847 }
1848
1849 /// checkCSEInPredecessor - Return true if the given instruction is available
1850 /// in its predecessor block. If yes, the instruction will be removed.
1851 ///
1852 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1853   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1854     return false;
1855   for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1856     Instruction *PBI = &*I;
1857     // Check whether Inst and PBI generate the same value.
1858     if (Inst->isIdenticalTo(PBI)) {
1859       Inst->replaceAllUsesWith(PBI);
1860       Inst->eraseFromParent();
1861       return true;
1862     }
1863   }
1864   return false;
1865 }
1866
1867 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1868 /// predecessor branches to us and one of our successors, fold the block into
1869 /// the predecessor and use logical operations to pick the right destination.
1870 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1871   BasicBlock *BB = BI->getParent();
1872
1873   Instruction *Cond = 0;
1874   if (BI->isConditional())
1875     Cond = dyn_cast<Instruction>(BI->getCondition());
1876   else {
1877     // For unconditional branch, check for a simple CFG pattern, where
1878     // BB has a single predecessor and BB's successor is also its predecessor's
1879     // successor. If such pattern exisits, check for CSE between BB and its
1880     // predecessor.
1881     if (BasicBlock *PB = BB->getSinglePredecessor())
1882       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1883         if (PBI->isConditional() &&
1884             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1885              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1886           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1887                I != E; ) {
1888             Instruction *Curr = I++;
1889             if (isa<CmpInst>(Curr)) {
1890               Cond = Curr;
1891               break;
1892             }
1893             // Quit if we can't remove this instruction.
1894             if (!checkCSEInPredecessor(Curr, PB))
1895               return false;
1896           }
1897         }
1898
1899     if (Cond == 0)
1900       return false;
1901   }
1902
1903   if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1904     Cond->getParent() != BB || !Cond->hasOneUse())
1905   return false;
1906
1907   // Only allow this if the condition is a simple instruction that can be
1908   // executed unconditionally.  It must be in the same block as the branch, and
1909   // must be at the front of the block.
1910   BasicBlock::iterator FrontIt = BB->front();
1911
1912   // Ignore dbg intrinsics.
1913   while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
1914
1915   // Allow a single instruction to be hoisted in addition to the compare
1916   // that feeds the branch.  We later ensure that any values that _it_ uses
1917   // were also live in the predecessor, so that we don't unnecessarily create
1918   // register pressure or inhibit out-of-order execution.
1919   Instruction *BonusInst = 0;
1920   if (&*FrontIt != Cond &&
1921       FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1922       isSafeToSpeculativelyExecute(FrontIt)) {
1923     BonusInst = &*FrontIt;
1924     ++FrontIt;
1925
1926     // Ignore dbg intrinsics.
1927     while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
1928   }
1929
1930   // Only a single bonus inst is allowed.
1931   if (&*FrontIt != Cond)
1932     return false;
1933
1934   // Make sure the instruction after the condition is the cond branch.
1935   BasicBlock::iterator CondIt = Cond; ++CondIt;
1936
1937   // Ingore dbg intrinsics.
1938   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
1939
1940   if (&*CondIt != BI)
1941     return false;
1942
1943   // Cond is known to be a compare or binary operator.  Check to make sure that
1944   // neither operand is a potentially-trapping constant expression.
1945   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1946     if (CE->canTrap())
1947       return false;
1948   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1949     if (CE->canTrap())
1950       return false;
1951
1952   // Finally, don't infinitely unroll conditional loops.
1953   BasicBlock *TrueDest  = BI->getSuccessor(0);
1954   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0;
1955   if (TrueDest == BB || FalseDest == BB)
1956     return false;
1957
1958   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1959     BasicBlock *PredBlock = *PI;
1960     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
1961
1962     // Check that we have two conditional branches.  If there is a PHI node in
1963     // the common successor, verify that the same value flows in from both
1964     // blocks.
1965     SmallVector<PHINode*, 4> PHIs;
1966     if (PBI == 0 || PBI->isUnconditional() ||
1967         (BI->isConditional() &&
1968          !SafeToMergeTerminators(BI, PBI)) ||
1969         (!BI->isConditional() &&
1970          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
1971       continue;
1972
1973     // Determine if the two branches share a common destination.
1974     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
1975     bool InvertPredCond = false;
1976
1977     if (BI->isConditional()) {
1978       if (PBI->getSuccessor(0) == TrueDest)
1979         Opc = Instruction::Or;
1980       else if (PBI->getSuccessor(1) == FalseDest)
1981         Opc = Instruction::And;
1982       else if (PBI->getSuccessor(0) == FalseDest)
1983         Opc = Instruction::And, InvertPredCond = true;
1984       else if (PBI->getSuccessor(1) == TrueDest)
1985         Opc = Instruction::Or, InvertPredCond = true;
1986       else
1987         continue;
1988     } else {
1989       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
1990         continue;
1991     }
1992
1993     // Ensure that any values used in the bonus instruction are also used
1994     // by the terminator of the predecessor.  This means that those values
1995     // must already have been resolved, so we won't be inhibiting the
1996     // out-of-order core by speculating them earlier.
1997     if (BonusInst) {
1998       // Collect the values used by the bonus inst
1999       SmallPtrSet<Value*, 4> UsedValues;
2000       for (Instruction::op_iterator OI = BonusInst->op_begin(),
2001            OE = BonusInst->op_end(); OI != OE; ++OI) {
2002         Value *V = *OI;
2003         if (!isa<Constant>(V))
2004           UsedValues.insert(V);
2005       }
2006
2007       SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2008       Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
2009
2010       // Walk up to four levels back up the use-def chain of the predecessor's
2011       // terminator to see if all those values were used.  The choice of four
2012       // levels is arbitrary, to provide a compile-time-cost bound.
2013       while (!Worklist.empty()) {
2014         std::pair<Value*, unsigned> Pair = Worklist.back();
2015         Worklist.pop_back();
2016
2017         if (Pair.second >= 4) continue;
2018         UsedValues.erase(Pair.first);
2019         if (UsedValues.empty()) break;
2020
2021         if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
2022           for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2023                OI != OE; ++OI)
2024             Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
2025         }
2026       }
2027
2028       if (!UsedValues.empty()) return false;
2029     }
2030
2031     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2032     IRBuilder<> Builder(PBI);
2033
2034     // If we need to invert the condition in the pred block to match, do so now.
2035     if (InvertPredCond) {
2036       Value *NewCond = PBI->getCondition();
2037
2038       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2039         CmpInst *CI = cast<CmpInst>(NewCond);
2040         CI->setPredicate(CI->getInversePredicate());
2041       } else {
2042         NewCond = Builder.CreateNot(NewCond,
2043                                     PBI->getCondition()->getName()+".not");
2044       }
2045
2046       PBI->setCondition(NewCond);
2047       PBI->swapSuccessors();
2048     }
2049
2050     // If we have a bonus inst, clone it into the predecessor block.
2051     Instruction *NewBonus = 0;
2052     if (BonusInst) {
2053       NewBonus = BonusInst->clone();
2054       PredBlock->getInstList().insert(PBI, NewBonus);
2055       NewBonus->takeName(BonusInst);
2056       BonusInst->setName(BonusInst->getName()+".old");
2057     }
2058
2059     // Clone Cond into the predecessor basic block, and or/and the
2060     // two conditions together.
2061     Instruction *New = Cond->clone();
2062     if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
2063     PredBlock->getInstList().insert(PBI, New);
2064     New->takeName(Cond);
2065     Cond->setName(New->getName()+".old");
2066
2067     if (BI->isConditional()) {
2068       Instruction *NewCond =
2069         cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2070                                             New, "or.cond"));
2071       PBI->setCondition(NewCond);
2072
2073       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2074       bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2075                                                   PredFalseWeight);
2076       bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2077                                                   SuccFalseWeight);
2078       SmallVector<uint64_t, 8> NewWeights;
2079
2080       if (PBI->getSuccessor(0) == BB) {
2081         if (PredHasWeights && SuccHasWeights) {
2082           // PBI: br i1 %x, BB, FalseDest
2083           // BI:  br i1 %y, TrueDest, FalseDest
2084           //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2085           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2086           //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2087           //               TrueWeight for PBI * FalseWeight for BI.
2088           // We assume that total weights of a BranchInst can fit into 32 bits.
2089           // Therefore, we will not have overflow using 64-bit arithmetic.
2090           NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2091                SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2092         }
2093         AddPredecessorToBlock(TrueDest, PredBlock, BB);
2094         PBI->setSuccessor(0, TrueDest);
2095       }
2096       if (PBI->getSuccessor(1) == BB) {
2097         if (PredHasWeights && SuccHasWeights) {
2098           // PBI: br i1 %x, TrueDest, BB
2099           // BI:  br i1 %y, TrueDest, FalseDest
2100           //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2101           //              FalseWeight for PBI * TrueWeight for BI.
2102           NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2103               SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2104           //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2105           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2106         }
2107         AddPredecessorToBlock(FalseDest, PredBlock, BB);
2108         PBI->setSuccessor(1, FalseDest);
2109       }
2110       if (NewWeights.size() == 2) {
2111         // Halve the weights if any of them cannot fit in an uint32_t
2112         FitWeights(NewWeights);
2113
2114         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2115         PBI->setMetadata(LLVMContext::MD_prof,
2116                          MDBuilder(BI->getContext()).
2117                          createBranchWeights(MDWeights));
2118       } else
2119         PBI->setMetadata(LLVMContext::MD_prof, NULL);
2120     } else {
2121       // Update PHI nodes in the common successors.
2122       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2123         ConstantInt *PBI_C = cast<ConstantInt>(
2124           PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2125         assert(PBI_C->getType()->isIntegerTy(1));
2126         Instruction *MergedCond = 0;
2127         if (PBI->getSuccessor(0) == TrueDest) {
2128           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2129           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2130           //       is false: !PBI_Cond and BI_Value
2131           Instruction *NotCond =
2132             cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2133                                 "not.cond"));
2134           MergedCond =
2135             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2136                                 NotCond, New,
2137                                 "and.cond"));
2138           if (PBI_C->isOne())
2139             MergedCond =
2140               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2141                                   PBI->getCondition(), MergedCond,
2142                                   "or.cond"));
2143         } else {
2144           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2145           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2146           //       is false: PBI_Cond and BI_Value
2147           MergedCond =
2148             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2149                                 PBI->getCondition(), New,
2150                                 "and.cond"));
2151           if (PBI_C->isOne()) {
2152             Instruction *NotCond =
2153               cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2154                                   "not.cond"));
2155             MergedCond =
2156               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2157                                   NotCond, MergedCond,
2158                                   "or.cond"));
2159           }
2160         }
2161         // Update PHI Node.
2162         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2163                                   MergedCond);
2164       }
2165       // Change PBI from Conditional to Unconditional.
2166       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2167       EraseTerminatorInstAndDCECond(PBI);
2168       PBI = New_PBI;
2169     }
2170
2171     // TODO: If BB is reachable from all paths through PredBlock, then we
2172     // could replace PBI's branch probabilities with BI's.
2173
2174     // Copy any debug value intrinsics into the end of PredBlock.
2175     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2176       if (isa<DbgInfoIntrinsic>(*I))
2177         I->clone()->insertBefore(PBI);
2178
2179     return true;
2180   }
2181   return false;
2182 }
2183
2184 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2185 /// predecessor of another block, this function tries to simplify it.  We know
2186 /// that PBI and BI are both conditional branches, and BI is in one of the
2187 /// successor blocks of PBI - PBI branches to BI.
2188 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2189   assert(PBI->isConditional() && BI->isConditional());
2190   BasicBlock *BB = BI->getParent();
2191
2192   // If this block ends with a branch instruction, and if there is a
2193   // predecessor that ends on a branch of the same condition, make
2194   // this conditional branch redundant.
2195   if (PBI->getCondition() == BI->getCondition() &&
2196       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2197     // Okay, the outcome of this conditional branch is statically
2198     // knowable.  If this block had a single pred, handle specially.
2199     if (BB->getSinglePredecessor()) {
2200       // Turn this into a branch on constant.
2201       bool CondIsTrue = PBI->getSuccessor(0) == BB;
2202       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2203                                         CondIsTrue));
2204       return true;  // Nuke the branch on constant.
2205     }
2206
2207     // Otherwise, if there are multiple predecessors, insert a PHI that merges
2208     // in the constant and simplify the block result.  Subsequent passes of
2209     // simplifycfg will thread the block.
2210     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2211       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2212       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2213                                        std::distance(PB, PE),
2214                                        BI->getCondition()->getName() + ".pr",
2215                                        BB->begin());
2216       // Okay, we're going to insert the PHI node.  Since PBI is not the only
2217       // predecessor, compute the PHI'd conditional value for all of the preds.
2218       // Any predecessor where the condition is not computable we keep symbolic.
2219       for (pred_iterator PI = PB; PI != PE; ++PI) {
2220         BasicBlock *P = *PI;
2221         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2222             PBI != BI && PBI->isConditional() &&
2223             PBI->getCondition() == BI->getCondition() &&
2224             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2225           bool CondIsTrue = PBI->getSuccessor(0) == BB;
2226           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2227                                               CondIsTrue), P);
2228         } else {
2229           NewPN->addIncoming(BI->getCondition(), P);
2230         }
2231       }
2232
2233       BI->setCondition(NewPN);
2234       return true;
2235     }
2236   }
2237
2238   // If this is a conditional branch in an empty block, and if any
2239   // predecessors is a conditional branch to one of our destinations,
2240   // fold the conditions into logical ops and one cond br.
2241   BasicBlock::iterator BBI = BB->begin();
2242   // Ignore dbg intrinsics.
2243   while (isa<DbgInfoIntrinsic>(BBI))
2244     ++BBI;
2245   if (&*BBI != BI)
2246     return false;
2247
2248
2249   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2250     if (CE->canTrap())
2251       return false;
2252
2253   int PBIOp, BIOp;
2254   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2255     PBIOp = BIOp = 0;
2256   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2257     PBIOp = 0, BIOp = 1;
2258   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2259     PBIOp = 1, BIOp = 0;
2260   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2261     PBIOp = BIOp = 1;
2262   else
2263     return false;
2264
2265   // Check to make sure that the other destination of this branch
2266   // isn't BB itself.  If so, this is an infinite loop that will
2267   // keep getting unwound.
2268   if (PBI->getSuccessor(PBIOp) == BB)
2269     return false;
2270
2271   // Do not perform this transformation if it would require
2272   // insertion of a large number of select instructions. For targets
2273   // without predication/cmovs, this is a big pessimization.
2274   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2275
2276   unsigned NumPhis = 0;
2277   for (BasicBlock::iterator II = CommonDest->begin();
2278        isa<PHINode>(II); ++II, ++NumPhis)
2279     if (NumPhis > 2) // Disable this xform.
2280       return false;
2281
2282   // Finally, if everything is ok, fold the branches to logical ops.
2283   BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
2284
2285   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2286                << "AND: " << *BI->getParent());
2287
2288
2289   // If OtherDest *is* BB, then BB is a basic block with a single conditional
2290   // branch in it, where one edge (OtherDest) goes back to itself but the other
2291   // exits.  We don't *know* that the program avoids the infinite loop
2292   // (even though that seems likely).  If we do this xform naively, we'll end up
2293   // recursively unpeeling the loop.  Since we know that (after the xform is
2294   // done) that the block *is* infinite if reached, we just make it an obviously
2295   // infinite loop with no cond branch.
2296   if (OtherDest == BB) {
2297     // Insert it at the end of the function, because it's either code,
2298     // or it won't matter if it's hot. :)
2299     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2300                                                   "infloop", BB->getParent());
2301     BranchInst::Create(InfLoopBlock, InfLoopBlock);
2302     OtherDest = InfLoopBlock;
2303   }
2304
2305   DEBUG(dbgs() << *PBI->getParent()->getParent());
2306
2307   // BI may have other predecessors.  Because of this, we leave
2308   // it alone, but modify PBI.
2309
2310   // Make sure we get to CommonDest on True&True directions.
2311   Value *PBICond = PBI->getCondition();
2312   IRBuilder<true, NoFolder> Builder(PBI);
2313   if (PBIOp)
2314     PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2315
2316   Value *BICond = BI->getCondition();
2317   if (BIOp)
2318     BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2319
2320   // Merge the conditions.
2321   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2322
2323   // Modify PBI to branch on the new condition to the new dests.
2324   PBI->setCondition(Cond);
2325   PBI->setSuccessor(0, CommonDest);
2326   PBI->setSuccessor(1, OtherDest);
2327
2328   // Update branch weight for PBI.
2329   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2330   bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2331                                               PredFalseWeight);
2332   bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2333                                               SuccFalseWeight);
2334   if (PredHasWeights && SuccHasWeights) {
2335     uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2336     uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2337     uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2338     uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2339     // The weight to CommonDest should be PredCommon * SuccTotal +
2340     //                                    PredOther * SuccCommon.
2341     // The weight to OtherDest should be PredOther * SuccOther.
2342     SmallVector<uint64_t, 2> NewWeights;
2343     NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2344                          PredOther * SuccCommon);
2345     NewWeights.push_back(PredOther * SuccOther);
2346     // Halve the weights if any of them cannot fit in an uint32_t
2347     FitWeights(NewWeights);
2348
2349     SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2350     PBI->setMetadata(LLVMContext::MD_prof,
2351                      MDBuilder(BI->getContext()).
2352                      createBranchWeights(MDWeights));
2353   }
2354
2355   // OtherDest may have phi nodes.  If so, add an entry from PBI's
2356   // block that are identical to the entries for BI's block.
2357   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2358
2359   // We know that the CommonDest already had an edge from PBI to
2360   // it.  If it has PHIs though, the PHIs may have different
2361   // entries for BB and PBI's BB.  If so, insert a select to make
2362   // them agree.
2363   PHINode *PN;
2364   for (BasicBlock::iterator II = CommonDest->begin();
2365        (PN = dyn_cast<PHINode>(II)); ++II) {
2366     Value *BIV = PN->getIncomingValueForBlock(BB);
2367     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2368     Value *PBIV = PN->getIncomingValue(PBBIdx);
2369     if (BIV != PBIV) {
2370       // Insert a select in PBI to pick the right value.
2371       Value *NV = cast<SelectInst>
2372         (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2373       PN->setIncomingValue(PBBIdx, NV);
2374     }
2375   }
2376
2377   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2378   DEBUG(dbgs() << *PBI->getParent()->getParent());
2379
2380   // This basic block is probably dead.  We know it has at least
2381   // one fewer predecessor.
2382   return true;
2383 }
2384
2385 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2386 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2387 // Takes care of updating the successors and removing the old terminator.
2388 // Also makes sure not to introduce new successors by assuming that edges to
2389 // non-successor TrueBBs and FalseBBs aren't reachable.
2390 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2391                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
2392                                        uint32_t TrueWeight,
2393                                        uint32_t FalseWeight){
2394   // Remove any superfluous successor edges from the CFG.
2395   // First, figure out which successors to preserve.
2396   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2397   // successor.
2398   BasicBlock *KeepEdge1 = TrueBB;
2399   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
2400
2401   // Then remove the rest.
2402   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2403     BasicBlock *Succ = OldTerm->getSuccessor(I);
2404     // Make sure only to keep exactly one copy of each edge.
2405     if (Succ == KeepEdge1)
2406       KeepEdge1 = 0;
2407     else if (Succ == KeepEdge2)
2408       KeepEdge2 = 0;
2409     else
2410       Succ->removePredecessor(OldTerm->getParent());
2411   }
2412
2413   IRBuilder<> Builder(OldTerm);
2414   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2415
2416   // Insert an appropriate new terminator.
2417   if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
2418     if (TrueBB == FalseBB)
2419       // We were only looking for one successor, and it was present.
2420       // Create an unconditional branch to it.
2421       Builder.CreateBr(TrueBB);
2422     else {
2423       // We found both of the successors we were looking for.
2424       // Create a conditional branch sharing the condition of the select.
2425       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2426       if (TrueWeight != FalseWeight)
2427         NewBI->setMetadata(LLVMContext::MD_prof,
2428                            MDBuilder(OldTerm->getContext()).
2429                            createBranchWeights(TrueWeight, FalseWeight));
2430     }
2431   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2432     // Neither of the selected blocks were successors, so this
2433     // terminator must be unreachable.
2434     new UnreachableInst(OldTerm->getContext(), OldTerm);
2435   } else {
2436     // One of the selected values was a successor, but the other wasn't.
2437     // Insert an unconditional branch to the one that was found;
2438     // the edge to the one that wasn't must be unreachable.
2439     if (KeepEdge1 == 0)
2440       // Only TrueBB was found.
2441       Builder.CreateBr(TrueBB);
2442     else
2443       // Only FalseBB was found.
2444       Builder.CreateBr(FalseBB);
2445   }
2446
2447   EraseTerminatorInstAndDCECond(OldTerm);
2448   return true;
2449 }
2450
2451 // SimplifySwitchOnSelect - Replaces
2452 //   (switch (select cond, X, Y)) on constant X, Y
2453 // with a branch - conditional if X and Y lead to distinct BBs,
2454 // unconditional otherwise.
2455 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2456   // Check for constant integer values in the select.
2457   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2458   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2459   if (!TrueVal || !FalseVal)
2460     return false;
2461
2462   // Find the relevant condition and destinations.
2463   Value *Condition = Select->getCondition();
2464   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2465   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2466
2467   // Get weight for TrueBB and FalseBB.
2468   uint32_t TrueWeight = 0, FalseWeight = 0;
2469   SmallVector<uint64_t, 8> Weights;
2470   bool HasWeights = HasBranchWeights(SI);
2471   if (HasWeights) {
2472     GetBranchWeights(SI, Weights);
2473     if (Weights.size() == 1 + SI->getNumCases()) {
2474       TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2475                                      getSuccessorIndex()];
2476       FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2477                                       getSuccessorIndex()];
2478     }
2479   }
2480
2481   // Perform the actual simplification.
2482   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2483                                     TrueWeight, FalseWeight);
2484 }
2485
2486 // SimplifyIndirectBrOnSelect - Replaces
2487 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
2488 //                             blockaddress(@fn, BlockB)))
2489 // with
2490 //   (br cond, BlockA, BlockB).
2491 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2492   // Check that both operands of the select are block addresses.
2493   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2494   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2495   if (!TBA || !FBA)
2496     return false;
2497
2498   // Extract the actual blocks.
2499   BasicBlock *TrueBB = TBA->getBasicBlock();
2500   BasicBlock *FalseBB = FBA->getBasicBlock();
2501
2502   // Perform the actual simplification.
2503   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2504                                     0, 0);
2505 }
2506
2507 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2508 /// instruction (a seteq/setne with a constant) as the only instruction in a
2509 /// block that ends with an uncond branch.  We are looking for a very specific
2510 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
2511 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2512 /// default value goes to an uncond block with a seteq in it, we get something
2513 /// like:
2514 ///
2515 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
2516 /// DEFAULT:
2517 ///   %tmp = icmp eq i8 %A, 92
2518 ///   br label %end
2519 /// end:
2520 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2521 ///
2522 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2523 /// the PHI, merging the third icmp into the switch.
2524 static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
2525                                                   const DataLayout *TD,
2526                                                   IRBuilder<> &Builder) {
2527   BasicBlock *BB = ICI->getParent();
2528
2529   // If the block has any PHIs in it or the icmp has multiple uses, it is too
2530   // complex.
2531   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2532
2533   Value *V = ICI->getOperand(0);
2534   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2535
2536   // The pattern we're looking for is where our only predecessor is a switch on
2537   // 'V' and this block is the default case for the switch.  In this case we can
2538   // fold the compared value into the switch to simplify things.
2539   BasicBlock *Pred = BB->getSinglePredecessor();
2540   if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
2541
2542   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2543   if (SI->getCondition() != V)
2544     return false;
2545
2546   // If BB is reachable on a non-default case, then we simply know the value of
2547   // V in this block.  Substitute it and constant fold the icmp instruction
2548   // away.
2549   if (SI->getDefaultDest() != BB) {
2550     ConstantInt *VVal = SI->findCaseDest(BB);
2551     assert(VVal && "Should have a unique destination value");
2552     ICI->setOperand(0, VVal);
2553
2554     if (Value *V = SimplifyInstruction(ICI, TD)) {
2555       ICI->replaceAllUsesWith(V);
2556       ICI->eraseFromParent();
2557     }
2558     // BB is now empty, so it is likely to simplify away.
2559     return SimplifyCFG(BB) | true;
2560   }
2561
2562   // Ok, the block is reachable from the default dest.  If the constant we're
2563   // comparing exists in one of the other edges, then we can constant fold ICI
2564   // and zap it.
2565   if (SI->findCaseValue(Cst) != SI->case_default()) {
2566     Value *V;
2567     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2568       V = ConstantInt::getFalse(BB->getContext());
2569     else
2570       V = ConstantInt::getTrue(BB->getContext());
2571
2572     ICI->replaceAllUsesWith(V);
2573     ICI->eraseFromParent();
2574     // BB is now empty, so it is likely to simplify away.
2575     return SimplifyCFG(BB) | true;
2576   }
2577
2578   // The use of the icmp has to be in the 'end' block, by the only PHI node in
2579   // the block.
2580   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2581   PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
2582   if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
2583       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2584     return false;
2585
2586   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2587   // true in the PHI.
2588   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2589   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
2590
2591   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2592     std::swap(DefaultCst, NewCst);
2593
2594   // Replace ICI (which is used by the PHI for the default value) with true or
2595   // false depending on if it is EQ or NE.
2596   ICI->replaceAllUsesWith(DefaultCst);
2597   ICI->eraseFromParent();
2598
2599   // Okay, the switch goes to this block on a default value.  Add an edge from
2600   // the switch to the merge point on the compared value.
2601   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2602                                          BB->getParent(), BB);
2603   SmallVector<uint64_t, 8> Weights;
2604   bool HasWeights = HasBranchWeights(SI);
2605   if (HasWeights) {
2606     GetBranchWeights(SI, Weights);
2607     if (Weights.size() == 1 + SI->getNumCases()) {
2608       // Split weight for default case to case for "Cst".
2609       Weights[0] = (Weights[0]+1) >> 1;
2610       Weights.push_back(Weights[0]);
2611
2612       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2613       SI->setMetadata(LLVMContext::MD_prof,
2614                       MDBuilder(SI->getContext()).
2615                       createBranchWeights(MDWeights));
2616     }
2617   }
2618   SI->addCase(Cst, NewBB);
2619
2620   // NewBB branches to the phi block, add the uncond branch and the phi entry.
2621   Builder.SetInsertPoint(NewBB);
2622   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2623   Builder.CreateBr(SuccBlock);
2624   PHIUse->addIncoming(NewCst, NewBB);
2625   return true;
2626 }
2627
2628 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2629 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2630 /// fold it into a switch instruction if so.
2631 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *TD,
2632                                       IRBuilder<> &Builder) {
2633   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2634   if (Cond == 0) return false;
2635
2636
2637   // Change br (X == 0 | X == 1), T, F into a switch instruction.
2638   // If this is a bunch of seteq's or'd together, or if it's a bunch of
2639   // 'setne's and'ed together, collect them.
2640   Value *CompVal = 0;
2641   std::vector<ConstantInt*> Values;
2642   bool TrueWhenEqual = true;
2643   Value *ExtraCase = 0;
2644   unsigned UsedICmps = 0;
2645
2646   if (Cond->getOpcode() == Instruction::Or) {
2647     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
2648                                      UsedICmps);
2649   } else if (Cond->getOpcode() == Instruction::And) {
2650     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
2651                                      UsedICmps);
2652     TrueWhenEqual = false;
2653   }
2654
2655   // If we didn't have a multiply compared value, fail.
2656   if (CompVal == 0) return false;
2657
2658   // Avoid turning single icmps into a switch.
2659   if (UsedICmps <= 1)
2660     return false;
2661
2662   // There might be duplicate constants in the list, which the switch
2663   // instruction can't handle, remove them now.
2664   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2665   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2666
2667   // If Extra was used, we require at least two switch values to do the
2668   // transformation.  A switch with one value is just an cond branch.
2669   if (ExtraCase && Values.size() < 2) return false;
2670
2671   // TODO: Preserve branch weight metadata, similarly to how
2672   // FoldValueComparisonIntoPredecessors preserves it.
2673
2674   // Figure out which block is which destination.
2675   BasicBlock *DefaultBB = BI->getSuccessor(1);
2676   BasicBlock *EdgeBB    = BI->getSuccessor(0);
2677   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2678
2679   BasicBlock *BB = BI->getParent();
2680
2681   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2682                << " cases into SWITCH.  BB is:\n" << *BB);
2683
2684   // If there are any extra values that couldn't be folded into the switch
2685   // then we evaluate them with an explicit branch first.  Split the block
2686   // right before the condbr to handle it.
2687   if (ExtraCase) {
2688     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2689     // Remove the uncond branch added to the old block.
2690     TerminatorInst *OldTI = BB->getTerminator();
2691     Builder.SetInsertPoint(OldTI);
2692
2693     if (TrueWhenEqual)
2694       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2695     else
2696       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2697
2698     OldTI->eraseFromParent();
2699
2700     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2701     // for the edge we just added.
2702     AddPredecessorToBlock(EdgeBB, BB, NewBB);
2703
2704     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
2705           << "\nEXTRABB = " << *BB);
2706     BB = NewBB;
2707   }
2708
2709   Builder.SetInsertPoint(BI);
2710   // Convert pointer to int before we switch.
2711   if (CompVal->getType()->isPointerTy()) {
2712     assert(TD && "Cannot switch on pointer without DataLayout");
2713     CompVal = Builder.CreatePtrToInt(CompVal,
2714                                      TD->getIntPtrType(CompVal->getContext()),
2715                                      "magicptr");
2716   }
2717
2718   // Create the new switch instruction now.
2719   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2720
2721   // Add all of the 'cases' to the switch instruction.
2722   for (unsigned i = 0, e = Values.size(); i != e; ++i)
2723     New->addCase(Values[i], EdgeBB);
2724
2725   // We added edges from PI to the EdgeBB.  As such, if there were any
2726   // PHI nodes in EdgeBB, they need entries to be added corresponding to
2727   // the number of edges added.
2728   for (BasicBlock::iterator BBI = EdgeBB->begin();
2729        isa<PHINode>(BBI); ++BBI) {
2730     PHINode *PN = cast<PHINode>(BBI);
2731     Value *InVal = PN->getIncomingValueForBlock(BB);
2732     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2733       PN->addIncoming(InVal, BB);
2734   }
2735
2736   // Erase the old branch instruction.
2737   EraseTerminatorInstAndDCECond(BI);
2738
2739   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
2740   return true;
2741 }
2742
2743 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2744   // If this is a trivial landing pad that just continues unwinding the caught
2745   // exception then zap the landing pad, turning its invokes into calls.
2746   BasicBlock *BB = RI->getParent();
2747   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2748   if (RI->getValue() != LPInst)
2749     // Not a landing pad, or the resume is not unwinding the exception that
2750     // caused control to branch here.
2751     return false;
2752
2753   // Check that there are no other instructions except for debug intrinsics.
2754   BasicBlock::iterator I = LPInst, E = RI;
2755   while (++I != E)
2756     if (!isa<DbgInfoIntrinsic>(I))
2757       return false;
2758
2759   // Turn all invokes that unwind here into calls and delete the basic block.
2760   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2761     InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2762     SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2763     // Insert a call instruction before the invoke.
2764     CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2765     Call->takeName(II);
2766     Call->setCallingConv(II->getCallingConv());
2767     Call->setAttributes(II->getAttributes());
2768     Call->setDebugLoc(II->getDebugLoc());
2769
2770     // Anything that used the value produced by the invoke instruction now uses
2771     // the value produced by the call instruction.  Note that we do this even
2772     // for void functions and calls with no uses so that the callgraph edge is
2773     // updated.
2774     II->replaceAllUsesWith(Call);
2775     BB->removePredecessor(II->getParent());
2776
2777     // Insert a branch to the normal destination right before the invoke.
2778     BranchInst::Create(II->getNormalDest(), II);
2779
2780     // Finally, delete the invoke instruction!
2781     II->eraseFromParent();
2782   }
2783
2784   // The landingpad is now unreachable.  Zap it.
2785   BB->eraseFromParent();
2786   return true;
2787 }
2788
2789 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2790   BasicBlock *BB = RI->getParent();
2791   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2792
2793   // Find predecessors that end with branches.
2794   SmallVector<BasicBlock*, 8> UncondBranchPreds;
2795   SmallVector<BranchInst*, 8> CondBranchPreds;
2796   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2797     BasicBlock *P = *PI;
2798     TerminatorInst *PTI = P->getTerminator();
2799     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2800       if (BI->isUnconditional())
2801         UncondBranchPreds.push_back(P);
2802       else
2803         CondBranchPreds.push_back(BI);
2804     }
2805   }
2806
2807   // If we found some, do the transformation!
2808   if (!UncondBranchPreds.empty() && DupRet) {
2809     while (!UncondBranchPreds.empty()) {
2810       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2811       DEBUG(dbgs() << "FOLDING: " << *BB
2812             << "INTO UNCOND BRANCH PRED: " << *Pred);
2813       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2814     }
2815
2816     // If we eliminated all predecessors of the block, delete the block now.
2817     if (pred_begin(BB) == pred_end(BB))
2818       // We know there are no successors, so just nuke the block.
2819       BB->eraseFromParent();
2820
2821     return true;
2822   }
2823
2824   // Check out all of the conditional branches going to this return
2825   // instruction.  If any of them just select between returns, change the
2826   // branch itself into a select/return pair.
2827   while (!CondBranchPreds.empty()) {
2828     BranchInst *BI = CondBranchPreds.pop_back_val();
2829
2830     // Check to see if the non-BB successor is also a return block.
2831     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2832         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2833         SimplifyCondBranchToTwoReturns(BI, Builder))
2834       return true;
2835   }
2836   return false;
2837 }
2838
2839 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2840   BasicBlock *BB = UI->getParent();
2841
2842   bool Changed = false;
2843
2844   // If there are any instructions immediately before the unreachable that can
2845   // be removed, do so.
2846   while (UI != BB->begin()) {
2847     BasicBlock::iterator BBI = UI;
2848     --BBI;
2849     // Do not delete instructions that can have side effects which might cause
2850     // the unreachable to not be reachable; specifically, calls and volatile
2851     // operations may have this effect.
2852     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2853
2854     if (BBI->mayHaveSideEffects()) {
2855       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2856         if (SI->isVolatile())
2857           break;
2858       } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2859         if (LI->isVolatile())
2860           break;
2861       } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2862         if (RMWI->isVolatile())
2863           break;
2864       } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2865         if (CXI->isVolatile())
2866           break;
2867       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2868                  !isa<LandingPadInst>(BBI)) {
2869         break;
2870       }
2871       // Note that deleting LandingPad's here is in fact okay, although it
2872       // involves a bit of subtle reasoning. If this inst is a LandingPad,
2873       // all the predecessors of this block will be the unwind edges of Invokes,
2874       // and we can therefore guarantee this block will be erased.
2875     }
2876
2877     // Delete this instruction (any uses are guaranteed to be dead)
2878     if (!BBI->use_empty())
2879       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2880     BBI->eraseFromParent();
2881     Changed = true;
2882   }
2883
2884   // If the unreachable instruction is the first in the block, take a gander
2885   // at all of the predecessors of this instruction, and simplify them.
2886   if (&BB->front() != UI) return Changed;
2887
2888   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2889   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2890     TerminatorInst *TI = Preds[i]->getTerminator();
2891     IRBuilder<> Builder(TI);
2892     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2893       if (BI->isUnconditional()) {
2894         if (BI->getSuccessor(0) == BB) {
2895           new UnreachableInst(TI->getContext(), TI);
2896           TI->eraseFromParent();
2897           Changed = true;
2898         }
2899       } else {
2900         if (BI->getSuccessor(0) == BB) {
2901           Builder.CreateBr(BI->getSuccessor(1));
2902           EraseTerminatorInstAndDCECond(BI);
2903         } else if (BI->getSuccessor(1) == BB) {
2904           Builder.CreateBr(BI->getSuccessor(0));
2905           EraseTerminatorInstAndDCECond(BI);
2906           Changed = true;
2907         }
2908       }
2909     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2910       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2911            i != e; ++i)
2912         if (i.getCaseSuccessor() == BB) {
2913           BB->removePredecessor(SI->getParent());
2914           SI->removeCase(i);
2915           --i; --e;
2916           Changed = true;
2917         }
2918       // If the default value is unreachable, figure out the most popular
2919       // destination and make it the default.
2920       if (SI->getDefaultDest() == BB) {
2921         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
2922         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2923              i != e; ++i) {
2924           std::pair<unsigned, unsigned> &entry =
2925               Popularity[i.getCaseSuccessor()];
2926           if (entry.first == 0) {
2927             entry.first = 1;
2928             entry.second = i.getCaseIndex();
2929           } else {
2930             entry.first++;
2931           }
2932         }
2933
2934         // Find the most popular block.
2935         unsigned MaxPop = 0;
2936         unsigned MaxIndex = 0;
2937         BasicBlock *MaxBlock = 0;
2938         for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
2939              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2940           if (I->second.first > MaxPop ||
2941               (I->second.first == MaxPop && MaxIndex > I->second.second)) {
2942             MaxPop = I->second.first;
2943             MaxIndex = I->second.second;
2944             MaxBlock = I->first;
2945           }
2946         }
2947         if (MaxBlock) {
2948           // Make this the new default, allowing us to delete any explicit
2949           // edges to it.
2950           SI->setDefaultDest(MaxBlock);
2951           Changed = true;
2952
2953           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2954           // it.
2955           if (isa<PHINode>(MaxBlock->begin()))
2956             for (unsigned i = 0; i != MaxPop-1; ++i)
2957               MaxBlock->removePredecessor(SI->getParent());
2958
2959           for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2960                i != e; ++i)
2961             if (i.getCaseSuccessor() == MaxBlock) {
2962               SI->removeCase(i);
2963               --i; --e;
2964             }
2965         }
2966       }
2967     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2968       if (II->getUnwindDest() == BB) {
2969         // Convert the invoke to a call instruction.  This would be a good
2970         // place to note that the call does not throw though.
2971         BranchInst *BI = Builder.CreateBr(II->getNormalDest());
2972         II->removeFromParent();   // Take out of symbol table
2973
2974         // Insert the call now...
2975         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2976         Builder.SetInsertPoint(BI);
2977         CallInst *CI = Builder.CreateCall(II->getCalledValue(),
2978                                           Args, II->getName());
2979         CI->setCallingConv(II->getCallingConv());
2980         CI->setAttributes(II->getAttributes());
2981         // If the invoke produced a value, the call does now instead.
2982         II->replaceAllUsesWith(CI);
2983         delete II;
2984         Changed = true;
2985       }
2986     }
2987   }
2988
2989   // If this block is now dead, remove it.
2990   if (pred_begin(BB) == pred_end(BB) &&
2991       BB != &BB->getParent()->getEntryBlock()) {
2992     // We know there are no successors, so just nuke the block.
2993     BB->eraseFromParent();
2994     return true;
2995   }
2996
2997   return Changed;
2998 }
2999
3000 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3001 /// integer range comparison into a sub, an icmp and a branch.
3002 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3003   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3004
3005   // Make sure all cases point to the same destination and gather the values.
3006   SmallVector<ConstantInt *, 16> Cases;
3007   SwitchInst::CaseIt I = SI->case_begin();
3008   Cases.push_back(I.getCaseValue());
3009   SwitchInst::CaseIt PrevI = I++;
3010   for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3011     if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3012       return false;
3013     Cases.push_back(I.getCaseValue());
3014   }
3015   assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3016
3017   // Sort the case values, then check if they form a range we can transform.
3018   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3019   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3020     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3021       return false;
3022   }
3023
3024   Constant *Offset = ConstantExpr::getNeg(Cases.back());
3025   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3026
3027   Value *Sub = SI->getCondition();
3028   if (!Offset->isNullValue())
3029     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3030   Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3031   BranchInst *NewBI = Builder.CreateCondBr(
3032       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3033
3034   // Update weight for the newly-created conditional branch.
3035   SmallVector<uint64_t, 8> Weights;
3036   bool HasWeights = HasBranchWeights(SI);
3037   if (HasWeights) {
3038     GetBranchWeights(SI, Weights);
3039     if (Weights.size() == 1 + SI->getNumCases()) {
3040       // Combine all weights for the cases to be the true weight of NewBI.
3041       // We assume that the sum of all weights for a Terminator can fit into 32
3042       // bits.
3043       uint32_t NewTrueWeight = 0;
3044       for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3045         NewTrueWeight += (uint32_t)Weights[I];
3046       NewBI->setMetadata(LLVMContext::MD_prof,
3047                          MDBuilder(SI->getContext()).
3048                          createBranchWeights(NewTrueWeight,
3049                                              (uint32_t)Weights[0]));
3050     }
3051   }
3052
3053   // Prune obsolete incoming values off the successor's PHI nodes.
3054   for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3055        isa<PHINode>(BBI); ++BBI) {
3056     for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3057       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3058   }
3059   SI->eraseFromParent();
3060
3061   return true;
3062 }
3063
3064 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3065 /// and use it to remove dead cases.
3066 static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3067   Value *Cond = SI->getCondition();
3068   unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
3069   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3070   ComputeMaskedBits(Cond, KnownZero, KnownOne);
3071
3072   // Gather dead cases.
3073   SmallVector<ConstantInt*, 8> DeadCases;
3074   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3075     if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3076         (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3077       DeadCases.push_back(I.getCaseValue());
3078       DEBUG(dbgs() << "SimplifyCFG: switch case '"
3079                    << I.getCaseValue() << "' is dead.\n");
3080     }
3081   }
3082
3083   SmallVector<uint64_t, 8> Weights;
3084   bool HasWeight = HasBranchWeights(SI);
3085   if (HasWeight) {
3086     GetBranchWeights(SI, Weights);
3087     HasWeight = (Weights.size() == 1 + SI->getNumCases());
3088   }
3089
3090   // Remove dead cases from the switch.
3091   for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3092     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3093     assert(Case != SI->case_default() &&
3094            "Case was not found. Probably mistake in DeadCases forming.");
3095     if (HasWeight) {
3096       std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3097       Weights.pop_back();
3098     }
3099
3100     // Prune unused values from PHI nodes.
3101     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3102     SI->removeCase(Case);
3103   }
3104   if (HasWeight) {
3105     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3106     SI->setMetadata(LLVMContext::MD_prof,
3107                     MDBuilder(SI->getParent()->getContext()).
3108                     createBranchWeights(MDWeights));
3109   }
3110
3111   return !DeadCases.empty();
3112 }
3113
3114 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3115 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3116 /// by an unconditional branch), look at the phi node for BB in the successor
3117 /// block and see if the incoming value is equal to CaseValue. If so, return
3118 /// the phi node, and set PhiIndex to BB's index in the phi node.
3119 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3120                                               BasicBlock *BB,
3121                                               int *PhiIndex) {
3122   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3123     return NULL; // BB must be empty to be a candidate for simplification.
3124   if (!BB->getSinglePredecessor())
3125     return NULL; // BB must be dominated by the switch.
3126
3127   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3128   if (!Branch || !Branch->isUnconditional())
3129     return NULL; // Terminator must be unconditional branch.
3130
3131   BasicBlock *Succ = Branch->getSuccessor(0);
3132
3133   BasicBlock::iterator I = Succ->begin();
3134   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3135     int Idx = PHI->getBasicBlockIndex(BB);
3136     assert(Idx >= 0 && "PHI has no entry for predecessor?");
3137
3138     Value *InValue = PHI->getIncomingValue(Idx);
3139     if (InValue != CaseValue) continue;
3140
3141     *PhiIndex = Idx;
3142     return PHI;
3143   }
3144
3145   return NULL;
3146 }
3147
3148 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3149 /// instruction to a phi node dominated by the switch, if that would mean that
3150 /// some of the destination blocks of the switch can be folded away.
3151 /// Returns true if a change is made.
3152 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3153   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3154   ForwardingNodesMap ForwardingNodes;
3155
3156   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3157     ConstantInt *CaseValue = I.getCaseValue();
3158     BasicBlock *CaseDest = I.getCaseSuccessor();
3159
3160     int PhiIndex;
3161     PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3162                                                  &PhiIndex);
3163     if (!PHI) continue;
3164
3165     ForwardingNodes[PHI].push_back(PhiIndex);
3166   }
3167
3168   bool Changed = false;
3169
3170   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3171        E = ForwardingNodes.end(); I != E; ++I) {
3172     PHINode *Phi = I->first;
3173     SmallVector<int,4> &Indexes = I->second;
3174
3175     if (Indexes.size() < 2) continue;
3176
3177     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3178       Phi->setIncomingValue(Indexes[I], SI->getCondition());
3179     Changed = true;
3180   }
3181
3182   return Changed;
3183 }
3184
3185 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3186 /// initializing an array of constants like C.
3187 static bool ValidLookupTableConstant(Constant *C) {
3188   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3189     return CE->isGEPWithNoNotionalOverIndexing();
3190
3191   return isa<ConstantFP>(C) ||
3192       isa<ConstantInt>(C) ||
3193       isa<ConstantPointerNull>(C) ||
3194       isa<GlobalValue>(C) ||
3195       isa<UndefValue>(C);
3196 }
3197
3198 /// GetCaseResulsts - Try to determine the resulting constant values in phi
3199 /// nodes at the common destination basic block for one of the case
3200 /// destinations of a switch instruction.
3201 static bool GetCaseResults(SwitchInst *SI,
3202                            BasicBlock *CaseDest,
3203                            BasicBlock **CommonDest,
3204                            SmallVector<std::pair<PHINode*,Constant*>, 4> &Res) {
3205   // The block from which we enter the common destination.
3206   BasicBlock *Pred = SI->getParent();
3207
3208   // If CaseDest is empty, continue to its successor.
3209   if (CaseDest->getFirstNonPHIOrDbg() == CaseDest->getTerminator() &&
3210       !isa<PHINode>(CaseDest->begin())) {
3211
3212     TerminatorInst *Terminator = CaseDest->getTerminator();
3213     if (Terminator->getNumSuccessors() != 1)
3214       return false;
3215
3216     Pred = CaseDest;
3217     CaseDest = Terminator->getSuccessor(0);
3218   }
3219
3220   // If we did not have a CommonDest before, use the current one.
3221   if (!*CommonDest)
3222     *CommonDest = CaseDest;
3223   // If the destination isn't the common one, abort.
3224   if (CaseDest != *CommonDest)
3225     return false;
3226
3227   // Get the values for this case from phi nodes in the destination block.
3228   BasicBlock::iterator I = (*CommonDest)->begin();
3229   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3230     int Idx = PHI->getBasicBlockIndex(Pred);
3231     if (Idx == -1)
3232       continue;
3233
3234     Constant *ConstVal = dyn_cast<Constant>(PHI->getIncomingValue(Idx));
3235     if (!ConstVal)
3236       return false;
3237
3238     // Be conservative about which kinds of constants we support.
3239     if (!ValidLookupTableConstant(ConstVal))
3240       return false;
3241
3242     Res.push_back(std::make_pair(PHI, ConstVal));
3243   }
3244
3245   return true;
3246 }
3247
3248 namespace {
3249   /// SwitchLookupTable - This class represents a lookup table that can be used
3250   /// to replace a switch.
3251   class SwitchLookupTable {
3252   public:
3253     /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3254     /// with the contents of Values, using DefaultValue to fill any holes in the
3255     /// table.
3256     SwitchLookupTable(Module &M,
3257                       uint64_t TableSize,
3258                       ConstantInt *Offset,
3259                const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
3260                       Constant *DefaultValue,
3261                       const DataLayout *TD);
3262
3263     /// BuildLookup - Build instructions with Builder to retrieve the value at
3264     /// the position given by Index in the lookup table.
3265     Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3266
3267     /// WouldFitInRegister - Return true if a table with TableSize elements of
3268     /// type ElementType would fit in a target-legal register.
3269     static bool WouldFitInRegister(const DataLayout *TD,
3270                                    uint64_t TableSize,
3271                                    const Type *ElementType);
3272
3273   private:
3274     // Depending on the contents of the table, it can be represented in
3275     // different ways.
3276     enum {
3277       // For tables where each element contains the same value, we just have to
3278       // store that single value and return it for each lookup.
3279       SingleValueKind,
3280
3281       // For small tables with integer elements, we can pack them into a bitmap
3282       // that fits into a target-legal register. Values are retrieved by
3283       // shift and mask operations.
3284       BitMapKind,
3285
3286       // The table is stored as an array of values. Values are retrieved by load
3287       // instructions from the table.
3288       ArrayKind
3289     } Kind;
3290
3291     // For SingleValueKind, this is the single value.
3292     Constant *SingleValue;
3293
3294     // For BitMapKind, this is the bitmap.
3295     ConstantInt *BitMap;
3296     IntegerType *BitMapElementTy;
3297
3298     // For ArrayKind, this is the array.
3299     GlobalVariable *Array;
3300   };
3301 }
3302
3303 SwitchLookupTable::SwitchLookupTable(Module &M,
3304                                      uint64_t TableSize,
3305                                      ConstantInt *Offset,
3306                const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
3307                                      Constant *DefaultValue,
3308                                      const DataLayout *TD) {
3309   assert(Values.size() && "Can't build lookup table without values!");
3310   assert(TableSize >= Values.size() && "Can't fit values in table!");
3311
3312   // If all values in the table are equal, this is that value.
3313   SingleValue = Values.begin()->second;
3314
3315   // Build up the table contents.
3316   SmallVector<Constant*, 64> TableContents(TableSize);
3317   for (size_t I = 0, E = Values.size(); I != E; ++I) {
3318     ConstantInt *CaseVal = Values[I].first;
3319     Constant *CaseRes = Values[I].second;
3320     assert(CaseRes->getType() == DefaultValue->getType());
3321
3322     uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3323                    .getLimitedValue();
3324     TableContents[Idx] = CaseRes;
3325
3326     if (CaseRes != SingleValue)
3327       SingleValue = NULL;
3328   }
3329
3330   // Fill in any holes in the table with the default result.
3331   if (Values.size() < TableSize) {
3332     for (uint64_t I = 0; I < TableSize; ++I) {
3333       if (!TableContents[I])
3334         TableContents[I] = DefaultValue;
3335     }
3336
3337     if (DefaultValue != SingleValue)
3338       SingleValue = NULL;
3339   }
3340
3341   // If each element in the table contains the same value, we only need to store
3342   // that single value.
3343   if (SingleValue) {
3344     Kind = SingleValueKind;
3345     return;
3346   }
3347
3348   // If the type is integer and the table fits in a register, build a bitmap.
3349   if (WouldFitInRegister(TD, TableSize, DefaultValue->getType())) {
3350     IntegerType *IT = cast<IntegerType>(DefaultValue->getType());
3351     APInt TableInt(TableSize * IT->getBitWidth(), 0);
3352     for (uint64_t I = TableSize; I > 0; --I) {
3353       TableInt <<= IT->getBitWidth();
3354       // Insert values into the bitmap. Undef values are set to zero.
3355       if (!isa<UndefValue>(TableContents[I - 1])) {
3356         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3357         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3358       }
3359     }
3360     BitMap = ConstantInt::get(M.getContext(), TableInt);
3361     BitMapElementTy = IT;
3362     Kind = BitMapKind;
3363     ++NumBitMaps;
3364     return;
3365   }
3366
3367   // Store the table in an array.
3368   ArrayType *ArrayTy = ArrayType::get(DefaultValue->getType(), TableSize);
3369   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3370
3371   Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3372                              GlobalVariable::PrivateLinkage,
3373                              Initializer,
3374                              "switch.table");
3375   Array->setUnnamedAddr(true);
3376   Kind = ArrayKind;
3377 }
3378
3379 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3380   switch (Kind) {
3381     case SingleValueKind:
3382       return SingleValue;
3383     case BitMapKind: {
3384       // Type of the bitmap (e.g. i59).
3385       IntegerType *MapTy = BitMap->getType();
3386
3387       // Cast Index to the same type as the bitmap.
3388       // Note: The Index is <= the number of elements in the table, so
3389       // truncating it to the width of the bitmask is safe.
3390       Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3391
3392       // Multiply the shift amount by the element width.
3393       ShiftAmt = Builder.CreateMul(ShiftAmt,
3394                       ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3395                                    "switch.shiftamt");
3396
3397       // Shift down.
3398       Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3399                                               "switch.downshift");
3400       // Mask off.
3401       return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3402                                  "switch.masked");
3403     }
3404     case ArrayKind: {
3405       Value *GEPIndices[] = { Builder.getInt32(0), Index };
3406       Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3407                                              "switch.gep");
3408       return Builder.CreateLoad(GEP, "switch.load");
3409     }
3410   }
3411   llvm_unreachable("Unknown lookup table kind!");
3412 }
3413
3414 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *TD,
3415                                            uint64_t TableSize,
3416                                            const Type *ElementType) {
3417   if (!TD)
3418     return false;
3419   const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3420   if (!IT)
3421     return false;
3422   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3423   // are <= 15, we could try to narrow the type.
3424
3425   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3426   if (TableSize >= UINT_MAX/IT->getBitWidth())
3427     return false;
3428   return TD->fitsInLegalInteger(TableSize * IT->getBitWidth());
3429 }
3430
3431 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3432 /// for this switch, based on the number of caes, size of the table and the
3433 /// types of the results.
3434 static bool ShouldBuildLookupTable(SwitchInst *SI,
3435                                    uint64_t TableSize,
3436                                    const DataLayout *TD,
3437                             const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3438   // The table density should be at least 40%. This is the same criterion as for
3439   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3440   // FIXME: Find the best cut-off.
3441   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3442     return false; // TableSize overflowed, or mul below might overflow.
3443   if (SI->getNumCases() * 10 >= TableSize * 4)
3444     return true;
3445
3446   // If each table would fit in a register, we should build it anyway.
3447   for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3448        E = ResultTypes.end(); I != E; ++I) {
3449     if (!SwitchLookupTable::WouldFitInRegister(TD, TableSize, I->second))
3450       return false;
3451   }
3452   return true;
3453 }
3454
3455 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3456 /// phi nodes in a common successor block with different constant values,
3457 /// replace the switch with lookup tables.
3458 static bool SwitchToLookupTable(SwitchInst *SI,
3459                                 IRBuilder<> &Builder,
3460                                 const DataLayout* TD) {
3461   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3462   // FIXME: Handle unreachable cases.
3463
3464   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3465   // split off a dense part and build a lookup table for that.
3466
3467   // FIXME: This creates arrays of GEPs to constant strings, which means each
3468   // GEP needs a runtime relocation in PIC code. We should just build one big
3469   // string and lookup indices into that.
3470
3471   // Ignore the switch if the number of cases is too small.
3472   // This is similar to the check when building jump tables in
3473   // SelectionDAGBuilder::handleJTSwitchCase.
3474   // FIXME: Determine the best cut-off.
3475   if (SI->getNumCases() < 4)
3476     return false;
3477
3478   // Figure out the corresponding result for each case value and phi node in the
3479   // common destination, as well as the the min and max case values.
3480   assert(SI->case_begin() != SI->case_end());
3481   SwitchInst::CaseIt CI = SI->case_begin();
3482   ConstantInt *MinCaseVal = CI.getCaseValue();
3483   ConstantInt *MaxCaseVal = CI.getCaseValue();
3484
3485   BasicBlock *CommonDest = NULL;
3486   typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3487   SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3488   SmallDenseMap<PHINode*, Constant*> DefaultResults;
3489   SmallDenseMap<PHINode*, Type*> ResultTypes;
3490   SmallVector<PHINode*, 4> PHIs;
3491
3492   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3493     ConstantInt *CaseVal = CI.getCaseValue();
3494     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3495       MinCaseVal = CaseVal;
3496     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3497       MaxCaseVal = CaseVal;
3498
3499     // Resulting value at phi nodes for this case value.
3500     typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3501     ResultsTy Results;
3502     if (!GetCaseResults(SI, CI.getCaseSuccessor(), &CommonDest, Results))
3503       return false;
3504
3505     // Append the result from this case to the list for each phi.
3506     for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3507       if (!ResultLists.count(I->first))
3508         PHIs.push_back(I->first);
3509       ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3510     }
3511   }
3512
3513   // Get the resulting values for the default case.
3514   SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3515   if (!GetCaseResults(SI, SI->getDefaultDest(), &CommonDest, DefaultResultsList))
3516     return false;
3517   for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3518     PHINode *PHI = DefaultResultsList[I].first;
3519     Constant *Result = DefaultResultsList[I].second;
3520     DefaultResults[PHI] = Result;
3521     ResultTypes[PHI] = Result->getType();
3522   }
3523
3524   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3525   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3526   if (!ShouldBuildLookupTable(SI, TableSize, TD, ResultTypes))
3527     return false;
3528
3529   // Create the BB that does the lookups.
3530   Module &Mod = *CommonDest->getParent()->getParent();
3531   BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3532                                             "switch.lookup",
3533                                             CommonDest->getParent(),
3534                                             CommonDest);
3535
3536   // Check whether the condition value is within the case range, and branch to
3537   // the new BB.
3538   Builder.SetInsertPoint(SI);
3539   Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3540                                         "switch.tableidx");
3541   Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3542       MinCaseVal->getType(), TableSize));
3543   Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3544
3545   // Populate the BB that does the lookups.
3546   Builder.SetInsertPoint(LookupBB);
3547   bool ReturnedEarly = false;
3548   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3549     PHINode *PHI = PHIs[I];
3550
3551     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3552                             DefaultResults[PHI], TD);
3553
3554     Value *Result = Table.BuildLookup(TableIndex, Builder);
3555
3556     // If the result is used to return immediately from the function, we want to
3557     // do that right here.
3558     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->use_begin()) &&
3559         *PHI->use_begin() == CommonDest->getFirstNonPHIOrDbg()) {
3560       Builder.CreateRet(Result);
3561       ReturnedEarly = true;
3562       break;
3563     }
3564
3565     PHI->addIncoming(Result, LookupBB);
3566   }
3567
3568   if (!ReturnedEarly)
3569     Builder.CreateBr(CommonDest);
3570
3571   // Remove the switch.
3572   for (unsigned i = 0; i < SI->getNumSuccessors(); ++i) {
3573     BasicBlock *Succ = SI->getSuccessor(i);
3574     if (Succ == SI->getDefaultDest()) continue;
3575     Succ->removePredecessor(SI->getParent());
3576   }
3577   SI->eraseFromParent();
3578
3579   ++NumLookupTables;
3580   return true;
3581 }
3582
3583 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3584   // If this switch is too complex to want to look at, ignore it.
3585   if (!isValueEqualityComparison(SI))
3586     return false;
3587
3588   BasicBlock *BB = SI->getParent();
3589
3590   // If we only have one predecessor, and if it is a branch on this value,
3591   // see if that predecessor totally determines the outcome of this switch.
3592   if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3593     if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3594       return SimplifyCFG(BB) | true;
3595
3596   Value *Cond = SI->getCondition();
3597   if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3598     if (SimplifySwitchOnSelect(SI, Select))
3599       return SimplifyCFG(BB) | true;
3600
3601   // If the block only contains the switch, see if we can fold the block
3602   // away into any preds.
3603   BasicBlock::iterator BBI = BB->begin();
3604   // Ignore dbg intrinsics.
3605   while (isa<DbgInfoIntrinsic>(BBI))
3606     ++BBI;
3607   if (SI == &*BBI)
3608     if (FoldValueComparisonIntoPredecessors(SI, Builder))
3609       return SimplifyCFG(BB) | true;
3610
3611   // Try to transform the switch into an icmp and a branch.
3612   if (TurnSwitchRangeIntoICmp(SI, Builder))
3613     return SimplifyCFG(BB) | true;
3614
3615   // Remove unreachable cases.
3616   if (EliminateDeadSwitchCases(SI))
3617     return SimplifyCFG(BB) | true;
3618
3619   if (ForwardSwitchConditionToPHI(SI))
3620     return SimplifyCFG(BB) | true;
3621
3622   if (SwitchToLookupTable(SI, Builder, TD))
3623     return SimplifyCFG(BB) | true;
3624
3625   return false;
3626 }
3627
3628 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3629   BasicBlock *BB = IBI->getParent();
3630   bool Changed = false;
3631
3632   // Eliminate redundant destinations.
3633   SmallPtrSet<Value *, 8> Succs;
3634   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3635     BasicBlock *Dest = IBI->getDestination(i);
3636     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3637       Dest->removePredecessor(BB);
3638       IBI->removeDestination(i);
3639       --i; --e;
3640       Changed = true;
3641     }
3642   }
3643
3644   if (IBI->getNumDestinations() == 0) {
3645     // If the indirectbr has no successors, change it to unreachable.
3646     new UnreachableInst(IBI->getContext(), IBI);
3647     EraseTerminatorInstAndDCECond(IBI);
3648     return true;
3649   }
3650
3651   if (IBI->getNumDestinations() == 1) {
3652     // If the indirectbr has one successor, change it to a direct branch.
3653     BranchInst::Create(IBI->getDestination(0), IBI);
3654     EraseTerminatorInstAndDCECond(IBI);
3655     return true;
3656   }
3657
3658   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3659     if (SimplifyIndirectBrOnSelect(IBI, SI))
3660       return SimplifyCFG(BB) | true;
3661   }
3662   return Changed;
3663 }
3664
3665 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
3666   BasicBlock *BB = BI->getParent();
3667
3668   if (SinkCommon && SinkThenElseCodeToEnd(BI))
3669     return true;
3670
3671   // If the Terminator is the only non-phi instruction, simplify the block.
3672   BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
3673   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3674       TryToSimplifyUncondBranchFromEmptyBlock(BB))
3675     return true;
3676
3677   // If the only instruction in the block is a seteq/setne comparison
3678   // against a constant, try to simplify the block.
3679   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3680     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3681       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3682         ;
3683       if (I->isTerminator() &&
3684           TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
3685         return true;
3686     }
3687
3688   // If this basic block is ONLY a compare and a branch, and if a predecessor
3689   // branches to us and our successor, fold the comparison into the
3690   // predecessor and use logical operations to update the incoming value
3691   // for PHI nodes in common successor.
3692   if (FoldBranchToCommonDest(BI))
3693     return SimplifyCFG(BB) | true;
3694   return false;
3695 }
3696
3697
3698 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
3699   BasicBlock *BB = BI->getParent();
3700
3701   // Conditional branch
3702   if (isValueEqualityComparison(BI)) {
3703     // If we only have one predecessor, and if it is a branch on this value,
3704     // see if that predecessor totally determines the outcome of this
3705     // switch.
3706     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3707       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
3708         return SimplifyCFG(BB) | true;
3709
3710     // This block must be empty, except for the setcond inst, if it exists.
3711     // Ignore dbg intrinsics.
3712     BasicBlock::iterator I = BB->begin();
3713     // Ignore dbg intrinsics.
3714     while (isa<DbgInfoIntrinsic>(I))
3715       ++I;
3716     if (&*I == BI) {
3717       if (FoldValueComparisonIntoPredecessors(BI, Builder))
3718         return SimplifyCFG(BB) | true;
3719     } else if (&*I == cast<Instruction>(BI->getCondition())){
3720       ++I;
3721       // Ignore dbg intrinsics.
3722       while (isa<DbgInfoIntrinsic>(I))
3723         ++I;
3724       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
3725         return SimplifyCFG(BB) | true;
3726     }
3727   }
3728
3729   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
3730   if (SimplifyBranchOnICmpChain(BI, TD, Builder))
3731     return true;
3732
3733   // If this basic block is ONLY a compare and a branch, and if a predecessor
3734   // branches to us and one of our successors, fold the comparison into the
3735   // predecessor and use logical operations to pick the right destination.
3736   if (FoldBranchToCommonDest(BI))
3737     return SimplifyCFG(BB) | true;
3738
3739   // We have a conditional branch to two blocks that are only reachable
3740   // from BI.  We know that the condbr dominates the two blocks, so see if
3741   // there is any identical code in the "then" and "else" blocks.  If so, we
3742   // can hoist it up to the branching block.
3743   if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
3744     if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
3745       if (HoistThenElseCodeToIf(BI))
3746         return SimplifyCFG(BB) | true;
3747     } else {
3748       // If Successor #1 has multiple preds, we may be able to conditionally
3749       // execute Successor #0 if it branches to successor #1.
3750       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
3751       if (Succ0TI->getNumSuccessors() == 1 &&
3752           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
3753         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
3754           return SimplifyCFG(BB) | true;
3755     }
3756   } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
3757     // If Successor #0 has multiple preds, we may be able to conditionally
3758     // execute Successor #1 if it branches to successor #0.
3759     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
3760     if (Succ1TI->getNumSuccessors() == 1 &&
3761         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
3762       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
3763         return SimplifyCFG(BB) | true;
3764   }
3765
3766   // If this is a branch on a phi node in the current block, thread control
3767   // through this block if any PHI node entries are constants.
3768   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
3769     if (PN->getParent() == BI->getParent())
3770       if (FoldCondBranchOnPHI(BI, TD))
3771         return SimplifyCFG(BB) | true;
3772
3773   // Scan predecessor blocks for conditional branches.
3774   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
3775     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
3776       if (PBI != BI && PBI->isConditional())
3777         if (SimplifyCondBranchToCondBranch(PBI, BI))
3778           return SimplifyCFG(BB) | true;
3779
3780   return false;
3781 }
3782
3783 /// Check if passing a value to an instruction will cause undefined behavior.
3784 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
3785   Constant *C = dyn_cast<Constant>(V);
3786   if (!C)
3787     return false;
3788
3789   if (I->use_empty())
3790     return false;
3791
3792   if (C->isNullValue()) {
3793     // Only look at the first use, avoid hurting compile time with long uselists
3794     User *Use = *I->use_begin();
3795
3796     // Now make sure that there are no instructions in between that can alter
3797     // control flow (eg. calls)
3798     for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
3799       if (i == I->getParent()->end() || i->mayHaveSideEffects())
3800         return false;
3801
3802     // Look through GEPs. A load from a GEP derived from NULL is still undefined
3803     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
3804       if (GEP->getPointerOperand() == I)
3805         return passingValueIsAlwaysUndefined(V, GEP);
3806
3807     // Look through bitcasts.
3808     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
3809       return passingValueIsAlwaysUndefined(V, BC);
3810
3811     // Load from null is undefined.
3812     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
3813       return LI->getPointerAddressSpace() == 0;
3814
3815     // Store to null is undefined.
3816     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
3817       return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
3818   }
3819   return false;
3820 }
3821
3822 /// If BB has an incoming value that will always trigger undefined behavior
3823 /// (eg. null pointer dereference), remove the branch leading here.
3824 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
3825   for (BasicBlock::iterator i = BB->begin();
3826        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
3827     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
3828       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
3829         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
3830         IRBuilder<> Builder(T);
3831         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
3832           BB->removePredecessor(PHI->getIncomingBlock(i));
3833           // Turn uncoditional branches into unreachables and remove the dead
3834           // destination from conditional branches.
3835           if (BI->isUnconditional())
3836             Builder.CreateUnreachable();
3837           else
3838             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
3839                                                          BI->getSuccessor(0));
3840           BI->eraseFromParent();
3841           return true;
3842         }
3843         // TODO: SwitchInst.
3844       }
3845
3846   return false;
3847 }
3848
3849 bool SimplifyCFGOpt::run(BasicBlock *BB) {
3850   bool Changed = false;
3851
3852   assert(BB && BB->getParent() && "Block not embedded in function!");
3853   assert(BB->getTerminator() && "Degenerate basic block encountered!");
3854
3855   // Remove basic blocks that have no predecessors (except the entry block)...
3856   // or that just have themself as a predecessor.  These are unreachable.
3857   if ((pred_begin(BB) == pred_end(BB) &&
3858        BB != &BB->getParent()->getEntryBlock()) ||
3859       BB->getSinglePredecessor() == BB) {
3860     DEBUG(dbgs() << "Removing BB: \n" << *BB);
3861     DeleteDeadBlock(BB);
3862     return true;
3863   }
3864
3865   // Check to see if we can constant propagate this terminator instruction
3866   // away...
3867   Changed |= ConstantFoldTerminator(BB, true);
3868
3869   // Check for and eliminate duplicate PHI nodes in this block.
3870   Changed |= EliminateDuplicatePHINodes(BB);
3871
3872   // Check for and remove branches that will always cause undefined behavior.
3873   Changed |= removeUndefIntroducingPredecessor(BB);
3874
3875   // Merge basic blocks into their predecessor if there is only one distinct
3876   // pred, and if there is only one distinct successor of the predecessor, and
3877   // if there are no PHI nodes.
3878   //
3879   if (MergeBlockIntoPredecessor(BB))
3880     return true;
3881
3882   IRBuilder<> Builder(BB);
3883
3884   // If there is a trivial two-entry PHI node in this basic block, and we can
3885   // eliminate it, do so now.
3886   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
3887     if (PN->getNumIncomingValues() == 2)
3888       Changed |= FoldTwoEntryPHINode(PN, TD);
3889
3890   Builder.SetInsertPoint(BB->getTerminator());
3891   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
3892     if (BI->isUnconditional()) {
3893       if (SimplifyUncondBranch(BI, Builder)) return true;
3894     } else {
3895       if (SimplifyCondBranch(BI, Builder)) return true;
3896     }
3897   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
3898     if (SimplifyReturn(RI, Builder)) return true;
3899   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
3900     if (SimplifyResume(RI, Builder)) return true;
3901   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
3902     if (SimplifySwitch(SI, Builder)) return true;
3903   } else if (UnreachableInst *UI =
3904                dyn_cast<UnreachableInst>(BB->getTerminator())) {
3905     if (SimplifyUnreachable(UI)) return true;
3906   } else if (IndirectBrInst *IBI =
3907                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
3908     if (SimplifyIndirectBr(IBI)) return true;
3909   }
3910
3911   return Changed;
3912 }
3913
3914 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
3915 /// example, it adjusts branches to branches to eliminate the extra hop, it
3916 /// eliminates unreachable basic blocks, and does other "peephole" optimization
3917 /// of the CFG.  It returns true if a modification was made.
3918 ///
3919 bool llvm::SimplifyCFG(BasicBlock *BB, const DataLayout *TD) {
3920   return SimplifyCFGOpt(TD).run(BB);
3921 }