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