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