Fix PR8247: JumpThreading can cause a block to become unreachable while still having...
[oota-llvm.git] / lib / Transforms / Scalar / JumpThreading.cpp
1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 // This file implements the Jump Threading pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jump-threading"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LazyValueInfo.h"
21 #include "llvm/Analysis/Loads.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/SSAUpdater.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ValueHandle.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37
38 STATISTIC(NumThreads, "Number of jumps threaded");
39 STATISTIC(NumFolds,   "Number of terminators folded");
40 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
41
42 static cl::opt<unsigned>
43 Threshold("jump-threading-threshold", 
44           cl::desc("Max block size to duplicate for jump threading"),
45           cl::init(6), cl::Hidden);
46
47 namespace {
48   /// This pass performs 'jump threading', which looks at blocks that have
49   /// multiple predecessors and multiple successors.  If one or more of the
50   /// predecessors of the block can be proven to always jump to one of the
51   /// successors, we forward the edge from the predecessor to the successor by
52   /// duplicating the contents of this block.
53   ///
54   /// An example of when this can occur is code like this:
55   ///
56   ///   if () { ...
57   ///     X = 4;
58   ///   }
59   ///   if (X < 3) {
60   ///
61   /// In this case, the unconditional branch at the end of the first if can be
62   /// revectored to the false side of the second if.
63   ///
64   class JumpThreading : public FunctionPass {
65     TargetData *TD;
66     LazyValueInfo *LVI;
67 #ifdef NDEBUG
68     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
69 #else
70     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
71 #endif
72     DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
73     
74     // RAII helper for updating the recursion stack.
75     struct RecursionSetRemover {
76       DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
77       std::pair<Value*, BasicBlock*> ThePair;
78       
79       RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
80                           std::pair<Value*, BasicBlock*> P)
81         : TheSet(S), ThePair(P) { }
82       
83       ~RecursionSetRemover() {
84         TheSet.erase(ThePair);
85       }
86     };
87   public:
88     static char ID; // Pass identification
89     JumpThreading() : FunctionPass(ID) {}
90
91     bool runOnFunction(Function &F);
92     
93     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94       AU.addRequired<LazyValueInfo>();
95       AU.addPreserved<LazyValueInfo>();
96     }
97     
98     void FindLoopHeaders(Function &F);
99     bool ProcessBlock(BasicBlock *BB);
100     bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
101                     BasicBlock *SuccBB);
102     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
103                                   const SmallVectorImpl<BasicBlock *> &PredBBs);
104     
105     typedef SmallVectorImpl<std::pair<ConstantInt*,
106                                       BasicBlock*> > PredValueInfo;
107     
108     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
109                                          PredValueInfo &Result);
110     bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB);
111     
112     
113     bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
114     bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
115
116     bool ProcessBranchOnPHI(PHINode *PN);
117     bool ProcessBranchOnXOR(BinaryOperator *BO);
118     
119     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
120   };
121 }
122
123 char JumpThreading::ID = 0;
124 INITIALIZE_PASS(JumpThreading, "jump-threading",
125                 "Jump Threading", false, false);
126
127 // Public interface to the Jump Threading pass
128 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
129
130 /// runOnFunction - Top level algorithm.
131 ///
132 bool JumpThreading::runOnFunction(Function &F) {
133   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
134   TD = getAnalysisIfAvailable<TargetData>();
135   LVI = &getAnalysis<LazyValueInfo>();
136   
137   FindLoopHeaders(F);
138   
139   bool Changed, EverChanged = false;
140   do {
141     Changed = false;
142     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
143       BasicBlock *BB = I;
144       // Thread all of the branches we can over this block. 
145       while (ProcessBlock(BB))
146         Changed = true;
147       
148       ++I;
149       
150       // If the block is trivially dead, zap it.  This eliminates the successor
151       // edges which simplifies the CFG.
152       if (pred_begin(BB) == pred_end(BB) &&
153           BB != &BB->getParent()->getEntryBlock()) {
154         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
155               << "' with terminator: " << *BB->getTerminator() << '\n');
156         LoopHeaders.erase(BB);
157         LVI->eraseBlock(BB);
158         DeleteDeadBlock(BB);
159         Changed = true;
160       } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
161         // Can't thread an unconditional jump, but if the block is "almost
162         // empty", we can replace uses of it with uses of the successor and make
163         // this dead.
164         if (BI->isUnconditional() && 
165             BB != &BB->getParent()->getEntryBlock()) {
166           BasicBlock::iterator BBI = BB->getFirstNonPHI();
167           // Ignore dbg intrinsics.
168           while (isa<DbgInfoIntrinsic>(BBI))
169             ++BBI;
170           // If the terminator is the only non-phi instruction, try to nuke it.
171           if (BBI->isTerminator()) {
172             // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
173             // block, we have to make sure it isn't in the LoopHeaders set.  We
174             // reinsert afterward if needed.
175             bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
176             BasicBlock *Succ = BI->getSuccessor(0);
177             
178             // FIXME: It is always conservatively correct to drop the info
179             // for a block even if it doesn't get erased.  This isn't totally
180             // awesome, but it allows us to use AssertingVH to prevent nasty
181             // dangling pointer issues within LazyValueInfo.
182             LVI->eraseBlock(BB);
183             if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
184               Changed = true;
185               // If we deleted BB and BB was the header of a loop, then the
186               // successor is now the header of the loop.
187               BB = Succ;
188             }
189             
190             if (ErasedFromLoopHeaders)
191               LoopHeaders.insert(BB);
192           }
193         }
194       }
195     }
196     EverChanged |= Changed;
197   } while (Changed);
198   
199   LoopHeaders.clear();
200   return EverChanged;
201 }
202
203 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
204 /// thread across it.
205 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
206   /// Ignore PHI nodes, these will be flattened when duplication happens.
207   BasicBlock::const_iterator I = BB->getFirstNonPHI();
208   
209   // FIXME: THREADING will delete values that are just used to compute the
210   // branch, so they shouldn't count against the duplication cost.
211   
212   
213   // Sum up the cost of each instruction until we get to the terminator.  Don't
214   // include the terminator because the copy won't include it.
215   unsigned Size = 0;
216   for (; !isa<TerminatorInst>(I); ++I) {
217     // Debugger intrinsics don't incur code size.
218     if (isa<DbgInfoIntrinsic>(I)) continue;
219     
220     // If this is a pointer->pointer bitcast, it is free.
221     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
222       continue;
223     
224     // All other instructions count for at least one unit.
225     ++Size;
226     
227     // Calls are more expensive.  If they are non-intrinsic calls, we model them
228     // as having cost of 4.  If they are a non-vector intrinsic, we model them
229     // as having cost of 2 total, and if they are a vector intrinsic, we model
230     // them as having cost 1.
231     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
232       if (!isa<IntrinsicInst>(CI))
233         Size += 3;
234       else if (!CI->getType()->isVectorTy())
235         Size += 1;
236     }
237   }
238   
239   // Threading through a switch statement is particularly profitable.  If this
240   // block ends in a switch, decrease its cost to make it more likely to happen.
241   if (isa<SwitchInst>(I))
242     Size = Size > 6 ? Size-6 : 0;
243   
244   return Size;
245 }
246
247 /// FindLoopHeaders - We do not want jump threading to turn proper loop
248 /// structures into irreducible loops.  Doing this breaks up the loop nesting
249 /// hierarchy and pessimizes later transformations.  To prevent this from
250 /// happening, we first have to find the loop headers.  Here we approximate this
251 /// by finding targets of backedges in the CFG.
252 ///
253 /// Note that there definitely are cases when we want to allow threading of
254 /// edges across a loop header.  For example, threading a jump from outside the
255 /// loop (the preheader) to an exit block of the loop is definitely profitable.
256 /// It is also almost always profitable to thread backedges from within the loop
257 /// to exit blocks, and is often profitable to thread backedges to other blocks
258 /// within the loop (forming a nested loop).  This simple analysis is not rich
259 /// enough to track all of these properties and keep it up-to-date as the CFG
260 /// mutates, so we don't allow any of these transformations.
261 ///
262 void JumpThreading::FindLoopHeaders(Function &F) {
263   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
264   FindFunctionBackedges(F, Edges);
265   
266   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
267     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
268 }
269
270 // Helper method for ComputeValueKnownInPredecessors.  If Value is a
271 // ConstantInt, push it.  If it's an undef, push 0.  Otherwise, do nothing.
272 static void PushConstantIntOrUndef(SmallVectorImpl<std::pair<ConstantInt*,
273                                                         BasicBlock*> > &Result,
274                               Constant *Value, BasicBlock* BB){
275   if (ConstantInt *FoldedCInt = dyn_cast<ConstantInt>(Value))
276     Result.push_back(std::make_pair(FoldedCInt, BB));
277   else if (isa<UndefValue>(Value))
278     Result.push_back(std::make_pair((ConstantInt*)0, BB));
279 }
280
281 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
282 /// if we can infer that the value is a known ConstantInt in any of our
283 /// predecessors.  If so, return the known list of value and pred BB in the
284 /// result vector.  If a value is known to be undef, it is returned as null.
285 ///
286 /// This returns true if there were any known values.
287 ///
288 bool JumpThreading::
289 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
290   // This method walks up use-def chains recursively.  Because of this, we could
291   // get into an infinite loop going around loops in the use-def chain.  To
292   // prevent this, keep track of what (value, block) pairs we've already visited
293   // and terminate the search if we loop back to them
294   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
295     return false;
296   
297   // An RAII help to remove this pair from the recursion set once the recursion
298   // stack pops back out again.
299   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
300   
301   // If V is a constantint, then it is known in all predecessors.
302   if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
303     ConstantInt *CI = dyn_cast<ConstantInt>(V);
304     
305     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
306       Result.push_back(std::make_pair(CI, *PI));
307     
308     return true;
309   }
310   
311   // If V is a non-instruction value, or an instruction in a different block,
312   // then it can't be derived from a PHI.
313   Instruction *I = dyn_cast<Instruction>(V);
314   if (I == 0 || I->getParent() != BB) {
315     
316     // Okay, if this is a live-in value, see if it has a known value at the end
317     // of any of our predecessors.
318     //
319     // FIXME: This should be an edge property, not a block end property.
320     /// TODO: Per PR2563, we could infer value range information about a
321     /// predecessor based on its terminator.
322     //
323     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
324     // "I" is a non-local compare-with-a-constant instruction.  This would be
325     // able to handle value inequalities better, for example if the compare is
326     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
327     // Perhaps getConstantOnEdge should be smart enough to do this?
328     
329     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
330       BasicBlock *P = *PI;
331       // If the value is known by LazyValueInfo to be a constant in a
332       // predecessor, use that information to try to thread this block.
333       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
334       if (PredCst == 0 ||
335           (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
336         continue;
337         
338       Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), P));
339     }
340       
341     return !Result.empty();
342   }
343   
344   /// If I is a PHI node, then we know the incoming values for any constants.
345   if (PHINode *PN = dyn_cast<PHINode>(I)) {
346     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
347       Value *InVal = PN->getIncomingValue(i);
348       if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
349         ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
350         Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
351       } else {
352         Constant *CI = LVI->getConstantOnEdge(InVal,
353                                               PN->getIncomingBlock(i), BB);
354         // LVI returns null is no value could be determined.
355         if (!CI) continue;
356         PushConstantIntOrUndef(Result, CI, PN->getIncomingBlock(i));
357       }
358     }
359     
360     return !Result.empty();
361   }
362   
363   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
364
365   // Handle some boolean conditions.
366   if (I->getType()->getPrimitiveSizeInBits() == 1) { 
367     // X | true -> true
368     // X & false -> false
369     if (I->getOpcode() == Instruction::Or ||
370         I->getOpcode() == Instruction::And) {
371       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
372       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
373       
374       if (LHSVals.empty() && RHSVals.empty())
375         return false;
376       
377       ConstantInt *InterestingVal;
378       if (I->getOpcode() == Instruction::Or)
379         InterestingVal = ConstantInt::getTrue(I->getContext());
380       else
381         InterestingVal = ConstantInt::getFalse(I->getContext());
382       
383       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
384       
385       // Scan for the sentinel.  If we find an undef, force it to the
386       // interesting value: x|undef -> true and x&undef -> false.
387       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
388         if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) {
389           Result.push_back(LHSVals[i]);
390           Result.back().first = InterestingVal;
391           LHSKnownBBs.insert(LHSVals[i].second);
392         }
393       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
394         if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) {
395           // If we already inferred a value for this block on the LHS, don't
396           // re-add it.
397           if (!LHSKnownBBs.count(RHSVals[i].second)) {
398             Result.push_back(RHSVals[i]);
399             Result.back().first = InterestingVal;
400           }
401         }
402       
403       return !Result.empty();
404     }
405     
406     // Handle the NOT form of XOR.
407     if (I->getOpcode() == Instruction::Xor &&
408         isa<ConstantInt>(I->getOperand(1)) &&
409         cast<ConstantInt>(I->getOperand(1))->isOne()) {
410       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result);
411       if (Result.empty())
412         return false;
413
414       // Invert the known values.
415       for (unsigned i = 0, e = Result.size(); i != e; ++i)
416         if (Result[i].first)
417           Result[i].first =
418             cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
419       
420       return true;
421     }
422   
423   // Try to simplify some other binary operator values.
424   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
425     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
426       SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
427       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals);
428     
429       // Try to use constant folding to simplify the binary operator.
430       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
431         Constant *V = LHSVals[i].first;
432         if (V == 0) V = UndefValue::get(BO->getType());
433         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
434         
435         PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
436       }
437     }
438       
439     return !Result.empty();
440   }
441   
442   // Handle compare with phi operand, where the PHI is defined in this block.
443   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
444     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
445     if (PN && PN->getParent() == BB) {
446       // We can do this simplification if any comparisons fold to true or false.
447       // See if any do.
448       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
449         BasicBlock *PredBB = PN->getIncomingBlock(i);
450         Value *LHS = PN->getIncomingValue(i);
451         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
452         
453         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
454         if (Res == 0) {
455           if (!isa<Constant>(RHS))
456             continue;
457           
458           LazyValueInfo::Tristate 
459             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
460                                            cast<Constant>(RHS), PredBB, BB);
461           if (ResT == LazyValueInfo::Unknown)
462             continue;
463           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
464         }
465         
466         if (Constant *ConstRes = dyn_cast<Constant>(Res))
467           PushConstantIntOrUndef(Result, ConstRes, PredBB);
468       }
469       
470       return !Result.empty();
471     }
472     
473     
474     // If comparing a live-in value against a constant, see if we know the
475     // live-in value on any predecessors.
476     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
477       if (!isa<Instruction>(Cmp->getOperand(0)) ||
478           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
479         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
480
481         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
482           BasicBlock *P = *PI;
483           // If the value is known by LazyValueInfo to be a constant in a
484           // predecessor, use that information to try to thread this block.
485           LazyValueInfo::Tristate Res =
486             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
487                                     RHSCst, P, BB);
488           if (Res == LazyValueInfo::Unknown)
489             continue;
490
491           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
492           Result.push_back(std::make_pair(cast<ConstantInt>(ResC), P));
493         }
494
495         return !Result.empty();
496       }
497       
498       // Try to find a constant value for the LHS of a comparison,
499       // and evaluate it statically if we can.
500       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
501         SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
502         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
503         
504         for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
505           Constant *V = LHSVals[i].first;
506           if (V == 0) V = UndefValue::get(CmpConst->getType());
507           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
508                                                       V, CmpConst);
509           PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
510         }
511         
512         return !Result.empty();
513       }
514     }
515   }
516   
517   // If all else fails, see if LVI can figure out a constant value for us.
518   Constant *CI = LVI->getConstant(V, BB);
519   ConstantInt *CInt = dyn_cast_or_null<ConstantInt>(CI);
520   if (CInt) {
521     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
522       Result.push_back(std::make_pair(CInt, *PI));
523   }
524     
525   return !Result.empty();
526 }
527
528
529
530 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
531 /// in an undefined jump, decide which block is best to revector to.
532 ///
533 /// Since we can pick an arbitrary destination, we pick the successor with the
534 /// fewest predecessors.  This should reduce the in-degree of the others.
535 ///
536 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
537   TerminatorInst *BBTerm = BB->getTerminator();
538   unsigned MinSucc = 0;
539   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
540   // Compute the successor with the minimum number of predecessors.
541   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
542   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
543     TestBB = BBTerm->getSuccessor(i);
544     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
545     if (NumPreds < MinNumPreds)
546       MinSucc = i;
547   }
548   
549   return MinSucc;
550 }
551
552 /// ProcessBlock - If there are any predecessors whose control can be threaded
553 /// through to a successor, transform them now.
554 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
555   // If the block is trivially dead, just return and let the caller nuke it.
556   // This simplifies other transformations.
557   if (pred_begin(BB) == pred_end(BB) &&
558       BB != &BB->getParent()->getEntryBlock())
559     return false;
560   
561   // If this block has a single predecessor, and if that pred has a single
562   // successor, merge the blocks.  This encourages recursive jump threading
563   // because now the condition in this block can be threaded through
564   // predecessors of our predecessor block.
565   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
566     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
567         SinglePred != BB) {
568       // If SinglePred was a loop header, BB becomes one.
569       if (LoopHeaders.erase(SinglePred))
570         LoopHeaders.insert(BB);
571       
572       // Remember if SinglePred was the entry block of the function.  If so, we
573       // will need to move BB back to the entry position.
574       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
575       LVI->eraseBlock(SinglePred);
576       MergeBasicBlockIntoOnlyPred(BB);
577       
578       if (isEntry && BB != &BB->getParent()->getEntryBlock())
579         BB->moveBefore(&BB->getParent()->getEntryBlock());
580       return true;
581     }
582   }
583
584   // Look to see if the terminator is a branch of switch, if not we can't thread
585   // it.
586   Value *Condition;
587   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
588     // Can't thread an unconditional jump.
589     if (BI->isUnconditional()) return false;
590     Condition = BI->getCondition();
591   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
592     Condition = SI->getCondition();
593   else
594     return false; // Must be an invoke.
595   
596   // If the terminator of this block is branching on a constant, simplify the
597   // terminator to an unconditional branch.  This can occur due to threading in
598   // other blocks.
599   if (isa<ConstantInt>(Condition)) {
600     DEBUG(dbgs() << "  In block '" << BB->getName()
601           << "' folding terminator: " << *BB->getTerminator() << '\n');
602     ++NumFolds;
603     ConstantFoldTerminator(BB);
604     return true;
605   }
606   
607   // If the terminator is branching on an undef, we can pick any of the
608   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
609   if (isa<UndefValue>(Condition)) {
610     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
611     
612     // Fold the branch/switch.
613     TerminatorInst *BBTerm = BB->getTerminator();
614     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
615       if (i == BestSucc) continue;
616       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
617     }
618     
619     DEBUG(dbgs() << "  In block '" << BB->getName()
620           << "' folding undef terminator: " << *BBTerm << '\n');
621     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
622     BBTerm->eraseFromParent();
623     return true;
624   }
625   
626   Instruction *CondInst = dyn_cast<Instruction>(Condition);
627
628   // All the rest of our checks depend on the condition being an instruction.
629   if (CondInst == 0) {
630     // FIXME: Unify this with code below.
631     if (ProcessThreadableEdges(Condition, BB))
632       return true;
633     return false;
634   }  
635     
636   
637   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
638     // For a comparison where the LHS is outside this block, it's possible
639     // that we've branched on it before.  Used LVI to see if we can simplify
640     // the branch based on that.
641     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
642     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
643     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
644     if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
645         (!isa<Instruction>(CondCmp->getOperand(0)) ||
646          cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
647       // For predecessor edge, determine if the comparison is true or false
648       // on that edge.  If they're all true or all false, we can simplify the
649       // branch.
650       // FIXME: We could handle mixed true/false by duplicating code.
651       LazyValueInfo::Tristate Baseline =      
652         LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
653                                 CondConst, *PI, BB);
654       if (Baseline != LazyValueInfo::Unknown) {
655         // Check that all remaining incoming values match the first one.
656         while (++PI != PE) {
657           LazyValueInfo::Tristate Ret =
658             LVI->getPredicateOnEdge(CondCmp->getPredicate(),
659                                     CondCmp->getOperand(0), CondConst, *PI, BB);
660           if (Ret != Baseline) break;
661         }
662         
663         // If we terminated early, then one of the values didn't match.
664         if (PI == PE) {
665           unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
666           unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
667           CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
668           BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
669           CondBr->eraseFromParent();
670           return true;
671         }
672       }
673     }
674   }
675
676   // Check for some cases that are worth simplifying.  Right now we want to look
677   // for loads that are used by a switch or by the condition for the branch.  If
678   // we see one, check to see if it's partially redundant.  If so, insert a PHI
679   // which can then be used to thread the values.
680   //
681   Value *SimplifyValue = CondInst;
682   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
683     if (isa<Constant>(CondCmp->getOperand(1)))
684       SimplifyValue = CondCmp->getOperand(0);
685   
686   // TODO: There are other places where load PRE would be profitable, such as
687   // more complex comparisons.
688   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
689     if (SimplifyPartiallyRedundantLoad(LI))
690       return true;
691   
692   
693   // Handle a variety of cases where we are branching on something derived from
694   // a PHI node in the current block.  If we can prove that any predecessors
695   // compute a predictable value based on a PHI node, thread those predecessors.
696   //
697   if (ProcessThreadableEdges(CondInst, BB))
698     return true;
699   
700   // If this is an otherwise-unfoldable branch on a phi node in the current
701   // block, see if we can simplify.
702   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
703     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
704       return ProcessBranchOnPHI(PN);
705   
706   
707   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
708   if (CondInst->getOpcode() == Instruction::Xor &&
709       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
710     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
711   
712   
713   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
714   // "(X == 4)", thread through this block.
715   
716   return false;
717 }
718
719 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
720 /// block that jump on exactly the same condition.  This means that we almost
721 /// always know the direction of the edge in the DESTBB:
722 ///  PREDBB:
723 ///     br COND, DESTBB, BBY
724 ///  DESTBB:
725 ///     br COND, BBZ, BBW
726 ///
727 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
728 /// in DESTBB, we have to thread over it.
729 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
730                                                  BasicBlock *BB) {
731   BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
732   
733   // If both successors of PredBB go to DESTBB, we don't know anything.  We can
734   // fold the branch to an unconditional one, which allows other recursive
735   // simplifications.
736   bool BranchDir;
737   if (PredBI->getSuccessor(1) != BB)
738     BranchDir = true;
739   else if (PredBI->getSuccessor(0) != BB)
740     BranchDir = false;
741   else {
742     DEBUG(dbgs() << "  In block '" << PredBB->getName()
743           << "' folding terminator: " << *PredBB->getTerminator() << '\n');
744     ++NumFolds;
745     ConstantFoldTerminator(PredBB);
746     return true;
747   }
748    
749   BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
750
751   // If the dest block has one predecessor, just fix the branch condition to a
752   // constant and fold it.
753   if (BB->getSinglePredecessor()) {
754     DEBUG(dbgs() << "  In block '" << BB->getName()
755           << "' folding condition to '" << BranchDir << "': "
756           << *BB->getTerminator() << '\n');
757     ++NumFolds;
758     Value *OldCond = DestBI->getCondition();
759     DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
760                                           BranchDir));
761     // Delete dead instructions before we fold the branch.  Folding the branch
762     // can eliminate edges from the CFG which can end up deleting OldCond.
763     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
764     ConstantFoldTerminator(BB);
765     return true;
766   }
767  
768   
769   // Next, figure out which successor we are threading to.
770   BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
771   
772   SmallVector<BasicBlock*, 2> Preds;
773   Preds.push_back(PredBB);
774   
775   // Ok, try to thread it!
776   return ThreadEdge(BB, Preds, SuccBB);
777 }
778
779 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
780 /// block that switch on exactly the same condition.  This means that we almost
781 /// always know the direction of the edge in the DESTBB:
782 ///  PREDBB:
783 ///     switch COND [... DESTBB, BBY ... ]
784 ///  DESTBB:
785 ///     switch COND [... BBZ, BBW ]
786 ///
787 /// Optimizing switches like this is very important, because simplifycfg builds
788 /// switches out of repeated 'if' conditions.
789 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
790                                                  BasicBlock *DestBB) {
791   // Can't thread edge to self.
792   if (PredBB == DestBB)
793     return false;
794   
795   SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
796   SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
797
798   // There are a variety of optimizations that we can potentially do on these
799   // blocks: we order them from most to least preferable.
800   
801   // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
802   // directly to their destination.  This does not introduce *any* code size
803   // growth.  Skip debug info first.
804   BasicBlock::iterator BBI = DestBB->begin();
805   while (isa<DbgInfoIntrinsic>(BBI))
806     BBI++;
807   
808   // FIXME: Thread if it just contains a PHI.
809   if (isa<SwitchInst>(BBI)) {
810     bool MadeChange = false;
811     // Ignore the default edge for now.
812     for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
813       ConstantInt *DestVal = DestSI->getCaseValue(i);
814       BasicBlock *DestSucc = DestSI->getSuccessor(i);
815       
816       // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
817       // PredSI has an explicit case for it.  If so, forward.  If it is covered
818       // by the default case, we can't update PredSI.
819       unsigned PredCase = PredSI->findCaseValue(DestVal);
820       if (PredCase == 0) continue;
821       
822       // If PredSI doesn't go to DestBB on this value, then it won't reach the
823       // case on this condition.
824       if (PredSI->getSuccessor(PredCase) != DestBB &&
825           DestSI->getSuccessor(i) != DestBB)
826         continue;
827       
828       // Do not forward this if it already goes to this destination, this would
829       // be an infinite loop.
830       if (PredSI->getSuccessor(PredCase) == DestSucc)
831         continue;
832
833       // Otherwise, we're safe to make the change.  Make sure that the edge from
834       // DestSI to DestSucc is not critical and has no PHI nodes.
835       DEBUG(dbgs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
836       DEBUG(dbgs() << "THROUGH: " << *DestSI);
837
838       // If the destination has PHI nodes, just split the edge for updating
839       // simplicity.
840       if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
841         SplitCriticalEdge(DestSI, i, this);
842         DestSucc = DestSI->getSuccessor(i);
843       }
844       FoldSingleEntryPHINodes(DestSucc);
845       PredSI->setSuccessor(PredCase, DestSucc);
846       MadeChange = true;
847     }
848     
849     if (MadeChange)
850       return true;
851   }
852   
853   return false;
854 }
855
856
857 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
858 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
859 /// important optimization that encourages jump threading, and needs to be run
860 /// interlaced with other jump threading tasks.
861 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
862   // Don't hack volatile loads.
863   if (LI->isVolatile()) return false;
864   
865   // If the load is defined in a block with exactly one predecessor, it can't be
866   // partially redundant.
867   BasicBlock *LoadBB = LI->getParent();
868   if (LoadBB->getSinglePredecessor())
869     return false;
870   
871   Value *LoadedPtr = LI->getOperand(0);
872
873   // If the loaded operand is defined in the LoadBB, it can't be available.
874   // TODO: Could do simple PHI translation, that would be fun :)
875   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
876     if (PtrOp->getParent() == LoadBB)
877       return false;
878   
879   // Scan a few instructions up from the load, to see if it is obviously live at
880   // the entry to its block.
881   BasicBlock::iterator BBIt = LI;
882
883   if (Value *AvailableVal = 
884         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
885     // If the value if the load is locally available within the block, just use
886     // it.  This frequently occurs for reg2mem'd allocas.
887     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
888     
889     // If the returned value is the load itself, replace with an undef. This can
890     // only happen in dead loops.
891     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
892     LI->replaceAllUsesWith(AvailableVal);
893     LI->eraseFromParent();
894     return true;
895   }
896
897   // Otherwise, if we scanned the whole block and got to the top of the block,
898   // we know the block is locally transparent to the load.  If not, something
899   // might clobber its value.
900   if (BBIt != LoadBB->begin())
901     return false;
902   
903   
904   SmallPtrSet<BasicBlock*, 8> PredsScanned;
905   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
906   AvailablePredsTy AvailablePreds;
907   BasicBlock *OneUnavailablePred = 0;
908   
909   // If we got here, the loaded value is transparent through to the start of the
910   // block.  Check to see if it is available in any of the predecessor blocks.
911   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
912        PI != PE; ++PI) {
913     BasicBlock *PredBB = *PI;
914
915     // If we already scanned this predecessor, skip it.
916     if (!PredsScanned.insert(PredBB))
917       continue;
918
919     // Scan the predecessor to see if the value is available in the pred.
920     BBIt = PredBB->end();
921     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
922     if (!PredAvailable) {
923       OneUnavailablePred = PredBB;
924       continue;
925     }
926     
927     // If so, this load is partially redundant.  Remember this info so that we
928     // can create a PHI node.
929     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
930   }
931   
932   // If the loaded value isn't available in any predecessor, it isn't partially
933   // redundant.
934   if (AvailablePreds.empty()) return false;
935   
936   // Okay, the loaded value is available in at least one (and maybe all!)
937   // predecessors.  If the value is unavailable in more than one unique
938   // predecessor, we want to insert a merge block for those common predecessors.
939   // This ensures that we only have to insert one reload, thus not increasing
940   // code size.
941   BasicBlock *UnavailablePred = 0;
942   
943   // If there is exactly one predecessor where the value is unavailable, the
944   // already computed 'OneUnavailablePred' block is it.  If it ends in an
945   // unconditional branch, we know that it isn't a critical edge.
946   if (PredsScanned.size() == AvailablePreds.size()+1 &&
947       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
948     UnavailablePred = OneUnavailablePred;
949   } else if (PredsScanned.size() != AvailablePreds.size()) {
950     // Otherwise, we had multiple unavailable predecessors or we had a critical
951     // edge from the one.
952     SmallVector<BasicBlock*, 8> PredsToSplit;
953     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
954
955     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
956       AvailablePredSet.insert(AvailablePreds[i].first);
957
958     // Add all the unavailable predecessors to the PredsToSplit list.
959     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
960          PI != PE; ++PI) {
961       BasicBlock *P = *PI;
962       // If the predecessor is an indirect goto, we can't split the edge.
963       if (isa<IndirectBrInst>(P->getTerminator()))
964         return false;
965       
966       if (!AvailablePredSet.count(P))
967         PredsToSplit.push_back(P);
968     }
969     
970     // Split them out to their own block.
971     UnavailablePred =
972       SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
973                              "thread-pre-split", this);
974   }
975   
976   // If the value isn't available in all predecessors, then there will be
977   // exactly one where it isn't available.  Insert a load on that edge and add
978   // it to the AvailablePreds list.
979   if (UnavailablePred) {
980     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
981            "Can't handle critical edge here!");
982     Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
983                                  LI->getAlignment(),
984                                  UnavailablePred->getTerminator());
985     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
986   }
987   
988   // Now we know that each predecessor of this block has a value in
989   // AvailablePreds, sort them for efficient access as we're walking the preds.
990   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
991   
992   // Create a PHI node at the start of the block for the PRE'd load value.
993   PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
994   PN->takeName(LI);
995   
996   // Insert new entries into the PHI for each predecessor.  A single block may
997   // have multiple entries here.
998   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
999        ++PI) {
1000     BasicBlock *P = *PI;
1001     AvailablePredsTy::iterator I = 
1002       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
1003                        std::make_pair(P, (Value*)0));
1004     
1005     assert(I != AvailablePreds.end() && I->first == P &&
1006            "Didn't find entry for predecessor!");
1007     
1008     PN->addIncoming(I->second, I->first);
1009   }
1010   
1011   //cerr << "PRE: " << *LI << *PN << "\n";
1012   
1013   LI->replaceAllUsesWith(PN);
1014   LI->eraseFromParent();
1015   
1016   return true;
1017 }
1018
1019 /// FindMostPopularDest - The specified list contains multiple possible
1020 /// threadable destinations.  Pick the one that occurs the most frequently in
1021 /// the list.
1022 static BasicBlock *
1023 FindMostPopularDest(BasicBlock *BB,
1024                     const SmallVectorImpl<std::pair<BasicBlock*,
1025                                   BasicBlock*> > &PredToDestList) {
1026   assert(!PredToDestList.empty());
1027   
1028   // Determine popularity.  If there are multiple possible destinations, we
1029   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
1030   // blocks with known and real destinations to threading undef.  We'll handle
1031   // them later if interesting.
1032   DenseMap<BasicBlock*, unsigned> DestPopularity;
1033   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1034     if (PredToDestList[i].second)
1035       DestPopularity[PredToDestList[i].second]++;
1036   
1037   // Find the most popular dest.
1038   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1039   BasicBlock *MostPopularDest = DPI->first;
1040   unsigned Popularity = DPI->second;
1041   SmallVector<BasicBlock*, 4> SamePopularity;
1042   
1043   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1044     // If the popularity of this entry isn't higher than the popularity we've
1045     // seen so far, ignore it.
1046     if (DPI->second < Popularity)
1047       ; // ignore.
1048     else if (DPI->second == Popularity) {
1049       // If it is the same as what we've seen so far, keep track of it.
1050       SamePopularity.push_back(DPI->first);
1051     } else {
1052       // If it is more popular, remember it.
1053       SamePopularity.clear();
1054       MostPopularDest = DPI->first;
1055       Popularity = DPI->second;
1056     }      
1057   }
1058   
1059   // Okay, now we know the most popular destination.  If there is more than
1060   // destination, we need to determine one.  This is arbitrary, but we need
1061   // to make a deterministic decision.  Pick the first one that appears in the
1062   // successor list.
1063   if (!SamePopularity.empty()) {
1064     SamePopularity.push_back(MostPopularDest);
1065     TerminatorInst *TI = BB->getTerminator();
1066     for (unsigned i = 0; ; ++i) {
1067       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1068       
1069       if (std::find(SamePopularity.begin(), SamePopularity.end(),
1070                     TI->getSuccessor(i)) == SamePopularity.end())
1071         continue;
1072       
1073       MostPopularDest = TI->getSuccessor(i);
1074       break;
1075     }
1076   }
1077   
1078   // Okay, we have finally picked the most popular destination.
1079   return MostPopularDest;
1080 }
1081
1082 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB) {
1083   // If threading this would thread across a loop header, don't even try to
1084   // thread the edge.
1085   if (LoopHeaders.count(BB))
1086     return false;
1087   
1088   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
1089   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
1090     return false;
1091   
1092   assert(!PredValues.empty() &&
1093          "ComputeValueKnownInPredecessors returned true with no values");
1094
1095   DEBUG(dbgs() << "IN BB: " << *BB;
1096         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1097           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = ";
1098           if (PredValues[i].first)
1099             dbgs() << *PredValues[i].first;
1100           else
1101             dbgs() << "UNDEF";
1102           dbgs() << " for pred '" << PredValues[i].second->getName()
1103           << "'.\n";
1104         });
1105   
1106   // Decide what we want to thread through.  Convert our list of known values to
1107   // a list of known destinations for each pred.  This also discards duplicate
1108   // predecessors and keeps track of the undefined inputs (which are represented
1109   // as a null dest in the PredToDestList).
1110   SmallPtrSet<BasicBlock*, 16> SeenPreds;
1111   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1112   
1113   BasicBlock *OnlyDest = 0;
1114   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1115   
1116   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1117     BasicBlock *Pred = PredValues[i].second;
1118     if (!SeenPreds.insert(Pred))
1119       continue;  // Duplicate predecessor entry.
1120     
1121     // If the predecessor ends with an indirect goto, we can't change its
1122     // destination.
1123     if (isa<IndirectBrInst>(Pred->getTerminator()))
1124       continue;
1125     
1126     ConstantInt *Val = PredValues[i].first;
1127     
1128     BasicBlock *DestBB;
1129     if (Val == 0)      // Undef.
1130       DestBB = 0;
1131     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1132       DestBB = BI->getSuccessor(Val->isZero());
1133     else {
1134       SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
1135       DestBB = SI->getSuccessor(SI->findCaseValue(Val));
1136     }
1137
1138     // If we have exactly one destination, remember it for efficiency below.
1139     if (i == 0)
1140       OnlyDest = DestBB;
1141     else if (OnlyDest != DestBB)
1142       OnlyDest = MultipleDestSentinel;
1143     
1144     PredToDestList.push_back(std::make_pair(Pred, DestBB));
1145   }
1146   
1147   // If all edges were unthreadable, we fail.
1148   if (PredToDestList.empty())
1149     return false;
1150   
1151   // Determine which is the most common successor.  If we have many inputs and
1152   // this block is a switch, we want to start by threading the batch that goes
1153   // to the most popular destination first.  If we only know about one
1154   // threadable destination (the common case) we can avoid this.
1155   BasicBlock *MostPopularDest = OnlyDest;
1156   
1157   if (MostPopularDest == MultipleDestSentinel)
1158     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1159   
1160   // Now that we know what the most popular destination is, factor all
1161   // predecessors that will jump to it into a single predecessor.
1162   SmallVector<BasicBlock*, 16> PredsToFactor;
1163   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1164     if (PredToDestList[i].second == MostPopularDest) {
1165       BasicBlock *Pred = PredToDestList[i].first;
1166       
1167       // This predecessor may be a switch or something else that has multiple
1168       // edges to the block.  Factor each of these edges by listing them
1169       // according to # occurrences in PredsToFactor.
1170       TerminatorInst *PredTI = Pred->getTerminator();
1171       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1172         if (PredTI->getSuccessor(i) == BB)
1173           PredsToFactor.push_back(Pred);
1174     }
1175
1176   // If the threadable edges are branching on an undefined value, we get to pick
1177   // the destination that these predecessors should get to.
1178   if (MostPopularDest == 0)
1179     MostPopularDest = BB->getTerminator()->
1180                             getSuccessor(GetBestDestForJumpOnUndef(BB));
1181         
1182   // Ok, try to thread it!
1183   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1184 }
1185
1186 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1187 /// a PHI node in the current block.  See if there are any simplifications we
1188 /// can do based on inputs to the phi node.
1189 /// 
1190 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
1191   BasicBlock *BB = PN->getParent();
1192   
1193   // TODO: We could make use of this to do it once for blocks with common PHI
1194   // values.
1195   SmallVector<BasicBlock*, 1> PredBBs;
1196   PredBBs.resize(1);
1197   
1198   // If any of the predecessor blocks end in an unconditional branch, we can
1199   // *duplicate* the conditional branch into that block in order to further
1200   // encourage jump threading and to eliminate cases where we have branch on a
1201   // phi of an icmp (branch on icmp is much better).
1202   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1203     BasicBlock *PredBB = PN->getIncomingBlock(i);
1204     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1205       if (PredBr->isUnconditional()) {
1206         PredBBs[0] = PredBB;
1207         // Try to duplicate BB into PredBB.
1208         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1209           return true;
1210       }
1211   }
1212
1213   return false;
1214 }
1215
1216 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1217 /// a xor instruction in the current block.  See if there are any
1218 /// simplifications we can do based on inputs to the xor.
1219 /// 
1220 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
1221   BasicBlock *BB = BO->getParent();
1222   
1223   // If either the LHS or RHS of the xor is a constant, don't do this
1224   // optimization.
1225   if (isa<ConstantInt>(BO->getOperand(0)) ||
1226       isa<ConstantInt>(BO->getOperand(1)))
1227     return false;
1228   
1229   // If the first instruction in BB isn't a phi, we won't be able to infer
1230   // anything special about any particular predecessor.
1231   if (!isa<PHINode>(BB->front()))
1232     return false;
1233   
1234   // If we have a xor as the branch input to this block, and we know that the
1235   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1236   // the condition into the predecessor and fix that value to true, saving some
1237   // logical ops on that path and encouraging other paths to simplify.
1238   //
1239   // This copies something like this:
1240   //
1241   //  BB:
1242   //    %X = phi i1 [1],  [%X']
1243   //    %Y = icmp eq i32 %A, %B
1244   //    %Z = xor i1 %X, %Y
1245   //    br i1 %Z, ...
1246   //
1247   // Into:
1248   //  BB':
1249   //    %Y = icmp ne i32 %A, %B
1250   //    br i1 %Z, ...
1251
1252   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> XorOpValues;
1253   bool isLHS = true;
1254   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues)) {
1255     assert(XorOpValues.empty());
1256     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues))
1257       return false;
1258     isLHS = false;
1259   }
1260   
1261   assert(!XorOpValues.empty() &&
1262          "ComputeValueKnownInPredecessors returned true with no values");
1263
1264   // Scan the information to see which is most popular: true or false.  The
1265   // predecessors can be of the set true, false, or undef.
1266   unsigned NumTrue = 0, NumFalse = 0;
1267   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1268     if (!XorOpValues[i].first) continue;  // Ignore undefs for the count.
1269     if (XorOpValues[i].first->isZero())
1270       ++NumFalse;
1271     else
1272       ++NumTrue;
1273   }
1274   
1275   // Determine which value to split on, true, false, or undef if neither.
1276   ConstantInt *SplitVal = 0;
1277   if (NumTrue > NumFalse)
1278     SplitVal = ConstantInt::getTrue(BB->getContext());
1279   else if (NumTrue != 0 || NumFalse != 0)
1280     SplitVal = ConstantInt::getFalse(BB->getContext());
1281   
1282   // Collect all of the blocks that this can be folded into so that we can
1283   // factor this once and clone it once.
1284   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1285   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1286     if (XorOpValues[i].first != SplitVal && XorOpValues[i].first != 0) continue;
1287
1288     BlocksToFoldInto.push_back(XorOpValues[i].second);
1289   }
1290   
1291   // If we inferred a value for all of the predecessors, then duplication won't
1292   // help us.  However, we can just replace the LHS or RHS with the constant.
1293   if (BlocksToFoldInto.size() ==
1294       cast<PHINode>(BB->front()).getNumIncomingValues()) {
1295     if (SplitVal == 0) {
1296       // If all preds provide undef, just nuke the xor, because it is undef too.
1297       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1298       BO->eraseFromParent();
1299     } else if (SplitVal->isZero()) {
1300       // If all preds provide 0, replace the xor with the other input.
1301       BO->replaceAllUsesWith(BO->getOperand(isLHS));
1302       BO->eraseFromParent();
1303     } else {
1304       // If all preds provide 1, set the computed value to 1.
1305       BO->setOperand(!isLHS, SplitVal);
1306     }
1307     
1308     return true;
1309   }
1310   
1311   // Try to duplicate BB into PredBB.
1312   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1313 }
1314
1315
1316 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1317 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
1318 /// NewPred using the entries from OldPred (suitably mapped).
1319 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1320                                             BasicBlock *OldPred,
1321                                             BasicBlock *NewPred,
1322                                      DenseMap<Instruction*, Value*> &ValueMap) {
1323   for (BasicBlock::iterator PNI = PHIBB->begin();
1324        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1325     // Ok, we have a PHI node.  Figure out what the incoming value was for the
1326     // DestBlock.
1327     Value *IV = PN->getIncomingValueForBlock(OldPred);
1328     
1329     // Remap the value if necessary.
1330     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1331       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1332       if (I != ValueMap.end())
1333         IV = I->second;
1334     }
1335     
1336     PN->addIncoming(IV, NewPred);
1337   }
1338 }
1339
1340 /// ThreadEdge - We have decided that it is safe and profitable to factor the
1341 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1342 /// across BB.  Transform the IR to reflect this change.
1343 bool JumpThreading::ThreadEdge(BasicBlock *BB, 
1344                                const SmallVectorImpl<BasicBlock*> &PredBBs, 
1345                                BasicBlock *SuccBB) {
1346   // If threading to the same block as we come from, we would infinite loop.
1347   if (SuccBB == BB) {
1348     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
1349           << "' - would thread to self!\n");
1350     return false;
1351   }
1352   
1353   // If threading this would thread across a loop header, don't thread the edge.
1354   // See the comments above FindLoopHeaders for justifications and caveats.
1355   if (LoopHeaders.count(BB)) {
1356     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
1357           << "' to dest BB '" << SuccBB->getName()
1358           << "' - it might create an irreducible loop!\n");
1359     return false;
1360   }
1361
1362   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1363   if (JumpThreadCost > Threshold) {
1364     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
1365           << "' - Cost is too high: " << JumpThreadCost << "\n");
1366     return false;
1367   }
1368   
1369   // And finally, do it!  Start by factoring the predecessors is needed.
1370   BasicBlock *PredBB;
1371   if (PredBBs.size() == 1)
1372     PredBB = PredBBs[0];
1373   else {
1374     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1375           << " common predecessors.\n");
1376     PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1377                                     ".thr_comm", this);
1378   }
1379   
1380   // And finally, do it!
1381   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1382         << SuccBB->getName() << "' with cost: " << JumpThreadCost
1383         << ", across block:\n    "
1384         << *BB << "\n");
1385   
1386   LVI->threadEdge(PredBB, BB, SuccBB);
1387   
1388   // We are going to have to map operands from the original BB block to the new
1389   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1390   // account for entry from PredBB.
1391   DenseMap<Instruction*, Value*> ValueMapping;
1392   
1393   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 
1394                                          BB->getName()+".thread", 
1395                                          BB->getParent(), BB);
1396   NewBB->moveAfter(PredBB);
1397   
1398   BasicBlock::iterator BI = BB->begin();
1399   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1400     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1401   
1402   // Clone the non-phi instructions of BB into NewBB, keeping track of the
1403   // mapping and using it to remap operands in the cloned instructions.
1404   for (; !isa<TerminatorInst>(BI); ++BI) {
1405     Instruction *New = BI->clone();
1406     New->setName(BI->getName());
1407     NewBB->getInstList().push_back(New);
1408     ValueMapping[BI] = New;
1409    
1410     // Remap operands to patch up intra-block references.
1411     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1412       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1413         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1414         if (I != ValueMapping.end())
1415           New->setOperand(i, I->second);
1416       }
1417   }
1418   
1419   // We didn't copy the terminator from BB over to NewBB, because there is now
1420   // an unconditional jump to SuccBB.  Insert the unconditional jump.
1421   BranchInst::Create(SuccBB, NewBB);
1422   
1423   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1424   // PHI nodes for NewBB now.
1425   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1426   
1427   // If there were values defined in BB that are used outside the block, then we
1428   // now have to update all uses of the value to use either the original value,
1429   // the cloned value, or some PHI derived value.  This can require arbitrary
1430   // PHI insertion, of which we are prepared to do, clean these up now.
1431   SSAUpdater SSAUpdate;
1432   SmallVector<Use*, 16> UsesToRename;
1433   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1434     // Scan all uses of this instruction to see if it is used outside of its
1435     // block, and if so, record them in UsesToRename.
1436     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1437          ++UI) {
1438       Instruction *User = cast<Instruction>(*UI);
1439       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1440         if (UserPN->getIncomingBlock(UI) == BB)
1441           continue;
1442       } else if (User->getParent() == BB)
1443         continue;
1444       
1445       UsesToRename.push_back(&UI.getUse());
1446     }
1447     
1448     // If there are no uses outside the block, we're done with this instruction.
1449     if (UsesToRename.empty())
1450       continue;
1451     
1452     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
1453
1454     // We found a use of I outside of BB.  Rename all uses of I that are outside
1455     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1456     // with the two values we know.
1457     SSAUpdate.Initialize(I->getType(), I->getName());
1458     SSAUpdate.AddAvailableValue(BB, I);
1459     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1460     
1461     while (!UsesToRename.empty())
1462       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1463     DEBUG(dbgs() << "\n");
1464   }
1465   
1466   
1467   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1468   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1469   // us to simplify any PHI nodes in BB.
1470   TerminatorInst *PredTerm = PredBB->getTerminator();
1471   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1472     if (PredTerm->getSuccessor(i) == BB) {
1473       BB->removePredecessor(PredBB, true);
1474       PredTerm->setSuccessor(i, NewBB);
1475     }
1476   
1477   // At this point, the IR is fully up to date and consistent.  Do a quick scan
1478   // over the new instructions and zap any that are constants or dead.  This
1479   // frequently happens because of phi translation.
1480   SimplifyInstructionsInBlock(NewBB, TD);
1481   
1482   // Threaded an edge!
1483   ++NumThreads;
1484   return true;
1485 }
1486
1487 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1488 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1489 /// If we can duplicate the contents of BB up into PredBB do so now, this
1490 /// improves the odds that the branch will be on an analyzable instruction like
1491 /// a compare.
1492 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1493                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
1494   assert(!PredBBs.empty() && "Can't handle an empty set");
1495
1496   // If BB is a loop header, then duplicating this block outside the loop would
1497   // cause us to transform this into an irreducible loop, don't do this.
1498   // See the comments above FindLoopHeaders for justifications and caveats.
1499   if (LoopHeaders.count(BB)) {
1500     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
1501           << "' into predecessor block '" << PredBBs[0]->getName()
1502           << "' - it might create an irreducible loop!\n");
1503     return false;
1504   }
1505   
1506   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1507   if (DuplicationCost > Threshold) {
1508     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
1509           << "' - Cost is too high: " << DuplicationCost << "\n");
1510     return false;
1511   }
1512   
1513   // And finally, do it!  Start by factoring the predecessors is needed.
1514   BasicBlock *PredBB;
1515   if (PredBBs.size() == 1)
1516     PredBB = PredBBs[0];
1517   else {
1518     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1519           << " common predecessors.\n");
1520     PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1521                                     ".thr_comm", this);
1522   }
1523   
1524   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
1525   // of PredBB.
1526   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
1527         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
1528         << DuplicationCost << " block is:" << *BB << "\n");
1529   
1530   // Unless PredBB ends with an unconditional branch, split the edge so that we
1531   // can just clone the bits from BB into the end of the new PredBB.
1532   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
1533   
1534   if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
1535     PredBB = SplitEdge(PredBB, BB, this);
1536     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1537   }
1538   
1539   // We are going to have to map operands from the original BB block into the
1540   // PredBB block.  Evaluate PHI nodes in BB.
1541   DenseMap<Instruction*, Value*> ValueMapping;
1542   
1543   BasicBlock::iterator BI = BB->begin();
1544   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1545     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1546   
1547   // Clone the non-phi instructions of BB into PredBB, keeping track of the
1548   // mapping and using it to remap operands in the cloned instructions.
1549   for (; BI != BB->end(); ++BI) {
1550     Instruction *New = BI->clone();
1551     
1552     // Remap operands to patch up intra-block references.
1553     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1554       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1555         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1556         if (I != ValueMapping.end())
1557           New->setOperand(i, I->second);
1558       }
1559
1560     // If this instruction can be simplified after the operands are updated,
1561     // just use the simplified value instead.  This frequently happens due to
1562     // phi translation.
1563     if (Value *IV = SimplifyInstruction(New, TD)) {
1564       delete New;
1565       ValueMapping[BI] = IV;
1566     } else {
1567       // Otherwise, insert the new instruction into the block.
1568       New->setName(BI->getName());
1569       PredBB->getInstList().insert(OldPredBranch, New);
1570       ValueMapping[BI] = New;
1571     }
1572   }
1573   
1574   // Check to see if the targets of the branch had PHI nodes. If so, we need to
1575   // add entries to the PHI nodes for branch from PredBB now.
1576   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1577   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1578                                   ValueMapping);
1579   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1580                                   ValueMapping);
1581   
1582   // If there were values defined in BB that are used outside the block, then we
1583   // now have to update all uses of the value to use either the original value,
1584   // the cloned value, or some PHI derived value.  This can require arbitrary
1585   // PHI insertion, of which we are prepared to do, clean these up now.
1586   SSAUpdater SSAUpdate;
1587   SmallVector<Use*, 16> UsesToRename;
1588   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1589     // Scan all uses of this instruction to see if it is used outside of its
1590     // block, and if so, record them in UsesToRename.
1591     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1592          ++UI) {
1593       Instruction *User = cast<Instruction>(*UI);
1594       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1595         if (UserPN->getIncomingBlock(UI) == BB)
1596           continue;
1597       } else if (User->getParent() == BB)
1598         continue;
1599       
1600       UsesToRename.push_back(&UI.getUse());
1601     }
1602     
1603     // If there are no uses outside the block, we're done with this instruction.
1604     if (UsesToRename.empty())
1605       continue;
1606     
1607     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
1608     
1609     // We found a use of I outside of BB.  Rename all uses of I that are outside
1610     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1611     // with the two values we know.
1612     SSAUpdate.Initialize(I->getType(), I->getName());
1613     SSAUpdate.AddAvailableValue(BB, I);
1614     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1615     
1616     while (!UsesToRename.empty())
1617       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1618     DEBUG(dbgs() << "\n");
1619   }
1620   
1621   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1622   // that we nuked.
1623   BB->removePredecessor(PredBB, true);
1624   
1625   // Remove the unconditional branch at the end of the PredBB block.
1626   OldPredBranch->eraseFromParent();
1627   
1628   ++NumDupes;
1629   return true;
1630 }
1631
1632