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