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