JumpThreading.cpp revision 87e9f59c7a823ba86d8aafa4e15ac03e6db244c3
18383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
28383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
38383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//                     The LLVM Compiler Infrastructure
48383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
58383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// This file is distributed under the University of Illinois Open Source
68383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// License. See LICENSE.TXT for details.
78383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
88383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
98383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
10177480b7ede0441135572d641a2497df25a7d95fChris Lattner// This file implements the Jump Threading pass.
118383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
128383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
138383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
148383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#define DEBUG_TYPE "jump-threading"
158383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Transforms/Scalar.h"
16177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/IntrinsicInst.h"
171ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson#include "llvm/LLVMContext.h"
188383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Pass.h"
199819ef7742cc2e3af92a0b760fa33e30218ff7bbChris Lattner#include "llvm/Analysis/InstructionSimplify.h"
20cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner#include "llvm/Analysis/LazyValueInfo.h"
212cc675180b06d0a2173365a4015606933f1a285dChris Lattner#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22bd3401fa98b578080e227afce940bca80137dea6Chris Lattner#include "llvm/Transforms/Utils/Local.h"
23433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner#include "llvm/Transforms/Utils/SSAUpdater.h"
24ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner#include "llvm/Target/TargetData.h"
25fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/DenseMap.h"
26fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/Statistic.h"
27fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/STLExtras.h"
28fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallPtrSet.h"
29fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallSet.h"
308383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Support/CommandLine.h"
31177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/Support/Debug.h"
3293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar#include "llvm/Support/raw_ostream.h"
338383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerusing namespace llvm;
348383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
35bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumThreads, "Number of jumps threaded");
36bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumFolds,   "Number of terminators folded");
3778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSTATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
388383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
39177480b7ede0441135572d641a2497df25a7d95fChris Lattnerstatic cl::opt<unsigned>
40177480b7ede0441135572d641a2497df25a7d95fChris LattnerThreshold("jump-threading-threshold",
41177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::desc("Max block size to duplicate for jump threading"),
42177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::init(6), cl::Hidden);
43177480b7ede0441135572d641a2497df25a7d95fChris Lattner
44cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner// Turn on use of LazyValueInfo.
45cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattnerstatic cl::opt<bool>
46cc4d3b25f336eef135cb7125716ecb2c1979e92eChris LattnerEnableLVI("enable-jump-threading-lvi", cl::ReallyHidden);
47cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
48cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
49cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
508383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnernamespace {
5194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// This pass performs 'jump threading', which looks at blocks that have
5294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// multiple predecessors and multiple successors.  If one or more of the
5394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// predecessors of the block can be proven to always jump to one of the
5494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// successors, we forward the edge from the predecessor to the successor by
5594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// duplicating the contents of this block.
5694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// An example of when this can occur is code like this:
5894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if () { ...
6094019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///     X = 4;
6194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   }
6294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if (X < 3) {
6394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
6494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// In this case, the unconditional branch at the end of the first if can be
6594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// revectored to the false side of the second if.
6694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
673e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  class JumpThreading : public FunctionPass {
68ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    TargetData *TD;
69cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    LazyValueInfo *LVI;
70fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#ifdef NDEBUG
71fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallPtrSet<BasicBlock*, 16> LoopHeaders;
72fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#else
73fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
74fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#endif
758383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  public:
768383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    static char ID; // Pass identification
77ae73dc1448d25b02cabc7c64c86c64371453dda8Dan Gohman    JumpThreading() : FunctionPass(&ID) {}
788383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
798383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    bool runOnFunction(Function &F);
80fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
81cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner      if (EnableLVI)
83cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner        AU.addRequired<LazyValueInfo>();
84cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    }
85cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
86cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    void FindLoopHeaders(Function &F);
87c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    bool ProcessBlock(BasicBlock *BB);
885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    BasicBlock *SuccBB);
9078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
9178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                          BasicBlock *PredBB);
925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    typedef SmallVectorImpl<std::pair<ConstantInt*,
945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      BasicBlock*> > PredValueInfo;
955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                         PredValueInfo &Result);
981c96b4187be7589492dccf33e9fe7679ac61023dChris Lattner    bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB);
995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
1005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
101421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
1023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
1036bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
104d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner    bool ProcessJumpOnPHI(PHINode *PN);
10569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
10669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
1078383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  };
1088383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
1098383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
110844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar JumpThreading::ID = 0;
111844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<JumpThreading>
112844731a7f1909f55935e3514c9e713a62d67662eDan GohmanX("jump-threading", "Jump Threading");
113844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
1148383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// Public interface to the Jump Threading pass
1158383a7b7a6acdae478d4b4c2520915153b73f676Chris LattnerFunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
1168383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
1178383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// runOnFunction - Top level algorithm.
1188383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner///
1198383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerbool JumpThreading::runOnFunction(Function &F) {
12093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
12102a436c48ecff9e34d50ce0a2f861e5acdd9bf3fDan Gohman  TD = getAnalysisIfAvailable<TargetData>();
122cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  LVI = EnableLVI ? &getAnalysis<LazyValueInfo>() : 0;
123bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
124fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindLoopHeaders(F);
125fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
126bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  bool AnotherIteration = true, EverChanged = false;
127bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  while (AnotherIteration) {
128bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = false;
129bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    bool Changed = false;
130421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
131421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BasicBlock *BB = I;
132f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      // Thread all of the branches we can over this block.
133421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      while (ProcessBlock(BB))
134bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Changed = true;
135421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
136421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ++I;
137421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
138421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // If the block is trivially dead, zap it.  This eliminates the successor
139421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // edges which simplifies the CFG.
140421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      if (pred_begin(BB) == pred_end(BB) &&
14120fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner          BB != &BB->getParent()->getEntryBlock()) {
14293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        DEBUG(errs() << "  JT: Deleting dead block '" << BB->getName()
14378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              << "' with terminator: " << *BB->getTerminator() << '\n');
144fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.erase(BB);
145421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        DeleteDeadBlock(BB);
146421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        Changed = true;
147f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
148f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // Can't thread an unconditional jump, but if the block is "almost
149f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // empty", we can replace uses of it with uses of the successor and make
150f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // this dead.
151f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        if (BI->isUnconditional() &&
152f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            BB != &BB->getParent()->getEntryBlock()) {
153f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          BasicBlock::iterator BBI = BB->getFirstNonPHI();
154f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          // Ignore dbg intrinsics.
155f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          while (isa<DbgInfoIntrinsic>(BBI))
156f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            ++BBI;
157f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          // If the terminator is the only non-phi instruction, try to nuke it.
158f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          if (BBI->isTerminator()) {
1596f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
1606f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // block, we have to make sure it isn't in the LoopHeaders set.  We
1616f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // reinsert afterward in the rare case when the block isn't deleted.
1626f84a5feee5c7322a5145992bd4704225987909cChris Lattner            bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
163f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
164f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            if (TryToSimplifyUncondBranchFromEmptyBlock(BB))
165f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner              Changed = true;
1666f84a5feee5c7322a5145992bd4704225987909cChris Lattner            else if (ErasedFromLoopHeaders)
167f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner              LoopHeaders.insert(BB);
168f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          }
169f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        }
170421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      }
171421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
172bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = Changed;
173bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EverChanged |= Changed;
174bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
175fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
176fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  LoopHeaders.clear();
177bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  return EverChanged;
1788383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
179177480b7ede0441135572d641a2497df25a7d95fChris Lattner
18078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
18178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// thread across it.
18278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
18378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  /// Ignore PHI nodes, these will be flattened when duplication happens.
18478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::const_iterator I = BB->getFirstNonPHI();
18578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
186b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner  // FIXME: THREADING will delete values that are just used to compute the
187b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner  // branch, so they shouldn't count against the duplication cost.
188b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner
189b14b88a40ab12996c2982c4bc10fd35bb9a371d4Chris Lattner
19078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Sum up the cost of each instruction until we get to the terminator.  Don't
19178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // include the terminator because the copy won't include it.
19278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned Size = 0;
19378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; !isa<TerminatorInst>(I); ++I) {
19478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Debugger intrinsics don't incur code size.
19578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<DbgInfoIntrinsic>(I)) continue;
19678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
19778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If this is a pointer->pointer bitcast, it is free.
19878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
19978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
20078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
20178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // All other instructions count for at least one unit.
20278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ++Size;
20378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
20478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Calls are more expensive.  If they are non-intrinsic calls, we model them
20578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 4.  If they are a non-vector intrinsic, we model them
20678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 2 total, and if they are a vector intrinsic, we model
20778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // them as having cost 1.
20878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
20978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (!isa<IntrinsicInst>(CI))
21078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 3;
21178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      else if (!isa<VectorType>(CI->getType()))
21278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 1;
21378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
21478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
21578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
21678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Threading through a switch statement is particularly profitable.  If this
21778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // block ends in a switch, decrease its cost to make it more likely to happen.
21878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(I))
21978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Size = Size > 6 ? Size-6 : 0;
22078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
22178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return Size;
22278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
22378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
224fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// FindLoopHeaders - We do not want jump threading to turn proper loop
225fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// structures into irreducible loops.  Doing this breaks up the loop nesting
226fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// hierarchy and pessimizes later transformations.  To prevent this from
227fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// happening, we first have to find the loop headers.  Here we approximate this
228fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// by finding targets of backedges in the CFG.
229fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
230fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// Note that there definitely are cases when we want to allow threading of
231fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edges across a loop header.  For example, threading a jump from outside the
232fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// loop (the preheader) to an exit block of the loop is definitely profitable.
233fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// It is also almost always profitable to thread backedges from within the loop
234fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// to exit blocks, and is often profitable to thread backedges to other blocks
235fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// within the loop (forming a nested loop).  This simple analysis is not rich
236fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// enough to track all of these properties and keep it up-to-date as the CFG
237fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// mutates, so we don't allow any of these transformations.
238fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
239fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpvoid JumpThreading::FindLoopHeaders(Function &F) {
240fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
241fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindFunctionBackedges(F, Edges);
242fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
243fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
244fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
245fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
246fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
2475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
2485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// if we can infer that the value is a known ConstantInt in any of our
249e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner/// predecessors.  If so, return the known list of value and pred BB in the
2505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// result vector.  If a value is known to be undef, it is returned as null.
2515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
2525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// This returns true if there were any known values.
2535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
2545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::
2555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
2565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a constantint, then it is known in all predecessors.
2575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
2585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(V);
259cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
260cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
261cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner      Result.push_back(std::make_pair(CI, *PI));
2625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return true;
2635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
2645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
2655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a non-instruction value, or an instruction in a different block,
2665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // then it can't be derived from a PHI.
2675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
268cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  if (I == 0 || I->getParent() != BB) {
269cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
270cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // Okay, if this is a live-in value, see if it has a known value at the end
271cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // of any of our predecessors.
272cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    //
273cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    // FIXME: This should be an edge property, not a block end property.
274cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    /// TODO: Per PR2563, we could infer value range information about a
275cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    /// predecessor based on its terminator.
276cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    //
277cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    if (LVI) {
278cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner      for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
279cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner        // If the value is known by LazyValueInfo to be a constant in a
280cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner        // predecessor, use that information to try to thread this block.
28138392bbeb81233d0b342ad33166fc82ad922bc34Chris Lattner        Constant *PredCst = LVI->getConstantOnEdge(V, *PI, BB);
282cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner        if (PredCst == 0 ||
283cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner            (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
284cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner          continue;
285cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
286cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner        Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), *PI));
287cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner      }
288cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
289cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner      return !Result.empty();
290cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    }
291cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner
2925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
293cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  }
2945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
2955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// If I is a PHI node, then we know the incoming values for any constants.
2965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PHINode *PN = dyn_cast<PHINode>(I)) {
2975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Value *InVal = PN->getIncomingValue(i);
2995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
3005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
3015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
3025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return !Result.empty();
3055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
3085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle some boolean conditions.
3105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (I->getType()->getPrimitiveSizeInBits() == 1) {
3115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X | true -> true
3125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X & false -> false
3135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (I->getOpcode() == Instruction::Or ||
3145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        I->getOpcode() == Instruction::And) {
3155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
3165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
3175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (LHSVals.empty() && RHSVals.empty())
3195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return false;
3205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ConstantInt *InterestingVal;
3225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (I->getOpcode() == Instruction::Or)
3235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getTrue(I->getContext());
3245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      else
3255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getFalse(I->getContext());
3265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Scan for the sentinel.
3285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
3295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
3305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(LHSVals[i]);
3315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
3325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
3335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(RHSVals[i]);
3345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
3355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
336785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
337055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    // Handle the NOT form of XOR.
338055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    if (I->getOpcode() == Instruction::Xor &&
339055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        isa<ConstantInt>(I->getOperand(1)) &&
340055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        cast<ConstantInt>(I->getOperand(1))->isOne()) {
341055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result);
342055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      if (Result.empty())
343055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        return false;
344055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner
345055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      // Invert the known values.
346055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      for (unsigned i = 0, e = Result.size(); i != e; ++i)
347055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner        Result[i].first =
348055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner          cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
349055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner      return true;
350055d046f483af3c66f4d19a32a17fc63ed2c22d5Chris Lattner    }
3515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
35212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
3535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle compare with phi operand, where the PHI is defined in this block.
3545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
3565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PN && PN->getParent() == BB) {
3575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // We can do this simplification if any comparisons fold to true or false.
3585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // See if any do.
3595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        BasicBlock *PredBB = PN->getIncomingBlock(i);
3615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *LHS = PN->getIncomingValue(i);
3625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
3635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3642ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
3655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (Res == 0) continue;
3665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (isa<UndefValue>(Res))
3685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
3695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
3705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair(CI, PredBB));
3715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
3745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3762ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner
3772ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    // If comparing a live-in value against a constant, see if we know the
3782ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    // live-in value on any predecessors.
3792ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    if (LVI && isa<Constant>(Cmp->getOperand(1)) &&
3802ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        (!isa<Instruction>(Cmp->getOperand(0)) ||
3812ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner         cast<Instruction>(Cmp->getOperand(0))->getParent() != BB)) {
3822ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner      Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
3832ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner
3842ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner      for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3852ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        // If the value is known by LazyValueInfo to be a constant in a
3862ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        // predecessor, use that information to try to thread this block.
38738392bbeb81233d0b342ad33166fc82ad922bc34Chris Lattner        Constant *PredCst = LVI->getConstantOnEdge(Cmp->getOperand(0), *PI, BB);
3882ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        if (PredCst == 0)
3892ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner          continue;
3902ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner
3912ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        // Constant fold the compare.
3922ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        Value *Res = SimplifyCmpInst(Cmp->getPredicate(), PredCst, RHSCst, TD);
3932ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner        if (isa<ConstantInt>(Res) || isa<UndefValue>(Res))
3942ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner          Result.push_back(std::make_pair(dyn_cast<ConstantInt>(Res), *PI));
3952ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner      }
3962ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner
3972ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner      return !Result.empty();
3982ad00bf99d5738c39dbc8cab7e30a0b55e0714adChris Lattner    }
3995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
4015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
4025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4046bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
405e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
406e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// in an undefined jump, decide which block is best to revector to.
407e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
408e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// Since we can pick an arbitrary destination, we pick the successor with the
409e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// fewest predecessors.  This should reduce the in-degree of the others.
410e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
411e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattnerstatic unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
412e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  TerminatorInst *BBTerm = BB->getTerminator();
413e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinSucc = 0;
414e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
415e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // Compute the successor with the minimum number of predecessors.
416e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
417e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
418e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TestBB = BBTerm->getSuccessor(i);
419e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
420e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (NumPreds < MinNumPreds)
421e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      MinSucc = i;
422e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
423e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
424e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  return MinSucc;
425e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner}
426e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
427c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner/// ProcessBlock - If there are any predecessors whose control can be threaded
428177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// through to a successor, transform them now.
429c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattnerbool JumpThreading::ProcessBlock(BasicBlock *BB) {
43069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If this block has a single predecessor, and if that pred has a single
43169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // successor, merge the blocks.  This encourages recursive jump threading
43269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // because now the condition in this block can be threaded through
43369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors of our predecessor block.
4345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
435f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
436f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner        SinglePred != BB) {
437fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // If SinglePred was a loop header, BB becomes one.
438fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      if (LoopHeaders.erase(SinglePred))
439fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.insert(BB);
440fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
4413d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Remember if SinglePred was the entry block of the function.  If so, we
4423d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // will need to move BB back to the entry position.
4433d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
44469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      MergeBasicBlockIntoOnlyPred(BB);
4453d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner
4463d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      if (isEntry && BB != &BB->getParent()->getEntryBlock())
4473d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner        BB->moveBefore(&BB->getParent()->getEntryBlock());
44869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
44969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
4505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look to see if the terminator is a branch of switch, if not we can't thread
4535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // it.
454177480b7ede0441135572d641a2497df25a7d95fChris Lattner  Value *Condition;
455bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
456bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Can't thread an unconditional jump.
457bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (BI->isUnconditional()) return false;
458177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = BI->getCondition();
459bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
460177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = SI->getCondition();
461177480b7ede0441135572d641a2497df25a7d95fChris Lattner  else
462177480b7ede0441135572d641a2497df25a7d95fChris Lattner    return false; // Must be an invoke.
463bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
464bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // If the terminator of this block is branching on a constant, simplify the
465037c781de797242ba652db775f1f2c5d2d4eb19bChris Lattner  // terminator to an unconditional branch.  This can occur due to threading in
466bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // other blocks.
467bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (isa<ConstantInt>(Condition)) {
46893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
46978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *BB->getTerminator() << '\n');
470bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ++NumFolds;
471bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ConstantFoldTerminator(BB);
472bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    return true;
473bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
474bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
475421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the terminator is branching on an undef, we can pick any of the
476e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
477421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (isa<UndefValue>(Condition)) {
478e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
479421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
480421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Fold the branch/switch.
481e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TerminatorInst *BBTerm = BB->getTerminator();
482421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
483e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (i == BestSucc) continue;
484c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD);
485421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
486421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
48793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
48878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding undef terminator: " << *BBTerm << '\n');
489e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
490421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BBTerm->eraseFromParent();
491421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
492421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
493421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
494421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Instruction *CondInst = dyn_cast<Instruction>(Condition);
495421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
496421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the condition is an instruction defined in another block, see if a
497421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // predecessor has the same condition:
498421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBX, BBY
499421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //  BBX:
500421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBZ, BBW
501421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (!Condition->hasOneUse() && // Multiple uses.
502421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
503421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
504421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (isa<BranchInst>(BB->getTerminator())) {
505421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      for (; PI != E; ++PI)
506421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
507421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner          if (PBI->isConditional() && PBI->getCondition() == Condition &&
508421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner              ProcessBranchOnDuplicateCond(*PI, BB))
509421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner            return true;
5103cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    } else {
5113cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
5123cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      for (; PI != E; ++PI)
5133cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
5143cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          if (PSI->getCondition() == Condition &&
5153cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner              ProcessSwitchOnDuplicateCond(*PI, BB))
5163cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner            return true;
517421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
518421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
519421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
520421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // All the rest of our checks depend on the condition being an instruction.
52187e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner  if (CondInst == 0) {
52287e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner    // FIXME: Unify this with code below.
52387e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner    if (LVI && ProcessThreadableEdges(Condition, BB))
52487e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner      return true;
525421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return false;
52687e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner  }
52787e9f59c7a823ba86d8aafa4e15ac03e6db244c3Chris Lattner
528421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
529177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // See if this is a phi node in the current block.
530421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
531421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (PN->getParent() == BB)
532421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      return ProcessJumpOnPHI(PN);
533177480b7ede0441135572d641a2497df25a7d95fChris Lattner
5349683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
5355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!isa<PHINode>(CondCmp->getOperand(0)) ||
5365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
5375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If we have a comparison, loop over the predecessors to see if there is
5385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // a condition with a lexically identical value.
5395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      pred_iterator PI = pred_begin(BB), E = pred_end(BB);
5405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (; PI != E; ++PI)
5415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PBI->isConditional() && *PI != BB) {
5435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
5445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              if (CI->getOperand(0) == CondCmp->getOperand(0) &&
5455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getOperand(1) == CondCmp->getOperand(1) &&
5465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getPredicate() == CondCmp->getPredicate()) {
5475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                // TODO: Could handle things like (x != 4) --> (x == 17)
5485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                if (ProcessBranchOnDuplicateCond(*PI, BB))
5495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  return true;
5505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              }
55179c740ff479dde322aceafe15887b162c19ea195Chris Lattner            }
55279c740ff479dde322aceafe15887b162c19ea195Chris Lattner          }
5535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
5549683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  }
55569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
55669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Check for some cases that are worth simplifying.  Right now we want to look
55769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // for loads that are used by a switch or by the condition for the branch.  If
55869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we see one, check to see if it's partially redundant.  If so, insert a PHI
55969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // which can then be used to thread the values.
56069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //
56169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This is particularly important because reg2mem inserts loads and stores all
56269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // over the place, and this blocks jump threading if we don't zap them.
563421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Value *SimplifyValue = CondInst;
56469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
56569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (isa<Constant>(CondCmp->getOperand(1)))
56669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SimplifyValue = CondCmp->getOperand(0);
56769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
56869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
56969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (SimplifyPartiallyRedundantLoad(LI))
57069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
57169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
5725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle a variety of cases where we are branching on something derived from
5745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a PHI node in the current block.  If we can prove that any predecessors
5755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // compute a predictable value based on a PHI node, thread those predecessors.
5765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  //
577cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner  if (ProcessThreadableEdges(CondInst, BB))
578cc4d3b25f336eef135cb7125716ecb2c1979e92eChris Lattner    return true;
5795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
58169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
58269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // "(X == 4)" thread through this block.
583a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
584d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  return false;
585d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner}
586d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner
587421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
588421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// block that jump on exactly the same condition.  This means that we almost
589421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// always know the direction of the edge in the DESTBB:
590421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  PREDBB:
591421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, DESTBB, BBY
592421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  DESTBB:
593421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, BBZ, BBW
594421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///
595421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// If DESTBB has multiple predecessors, we can't just constant fold the branch
596421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// in DESTBB, we have to thread over it.
597421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattnerbool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
598421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                                 BasicBlock *BB) {
599421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
600421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
601421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If both successors of PredBB go to DESTBB, we don't know anything.  We can
602421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // fold the branch to an unconditional one, which allows other recursive
603421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // simplifications.
604421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  bool BranchDir;
605421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PredBI->getSuccessor(1) != BB)
606421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = true;
607421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else if (PredBI->getSuccessor(0) != BB)
608421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = false;
609421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else {
61093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << PredBB->getName()
61178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *PredBB->getTerminator() << '\n');
612421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
613421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(PredBB);
614421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
615421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
616421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
617421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
618421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
619421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the dest block has one predecessor, just fix the branch condition to a
620421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // constant and fold it.
621421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (BB->getSinglePredecessor()) {
62293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
62393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' folding condition to '" << BranchDir << "': "
62478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << *BB->getTerminator() << '\n');
625421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
6265a06cf644f35b873686c8694968192ad3385e36aChris Lattner    Value *OldCond = DestBI->getCondition();
6271d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
6281d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                          BranchDir));
629421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(BB);
6305a06cf644f35b873686c8694968192ad3385e36aChris Lattner    RecursivelyDeleteTriviallyDeadInstructions(OldCond);
631421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
632421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
633bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
634421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
635421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Next, figure out which successor we are threading to.
636421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
637421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 2> Preds;
6395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Preds.push_back(PredBB);
6405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
641fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
6425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, Preds, SuccBB);
643421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
644421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6453cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
6463cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// block that switch on exactly the same condition.  This means that we almost
6473cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// always know the direction of the edge in the DESTBB:
6483cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  PREDBB:
6493cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... DESTBB, BBY ... ]
6503cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  DESTBB:
6513cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... BBZ, BBW ]
6523cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///
6533cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// Optimizing switches like this is very important, because simplifycfg builds
6543cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// switches out of repeated 'if' conditions.
6553cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattnerbool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
6563cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                                 BasicBlock *DestBB) {
6572c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  // Can't thread edge to self.
6582c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  if (PredBB == DestBB)
6592c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner    return false;
6602c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner
6613cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
6623cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
6633cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6643cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // There are a variety of optimizations that we can potentially do on these
6653cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // blocks: we order them from most to least preferable.
6663cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6673cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
6683cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // directly to their destination.  This does not introduce *any* code size
6696b233395025069f63156ea2b524cdb708a14731fDale Johannesen  // growth.  Skip debug info first.
6706b233395025069f63156ea2b524cdb708a14731fDale Johannesen  BasicBlock::iterator BBI = DestBB->begin();
6716b233395025069f63156ea2b524cdb708a14731fDale Johannesen  while (isa<DbgInfoIntrinsic>(BBI))
6726b233395025069f63156ea2b524cdb708a14731fDale Johannesen    BBI++;
6733cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6743cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // FIXME: Thread if it just contains a PHI.
6756b233395025069f63156ea2b524cdb708a14731fDale Johannesen  if (isa<SwitchInst>(BBI)) {
6763cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool MadeChange = false;
6773cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    // Ignore the default edge for now.
6783cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
6793cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      ConstantInt *DestVal = DestSI->getCaseValue(i);
6803cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      BasicBlock *DestSucc = DestSI->getSuccessor(i);
6813cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6823cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
6833cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // PredSI has an explicit case for it.  If so, forward.  If it is covered
6843cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // by the default case, we can't update PredSI.
6853cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      unsigned PredCase = PredSI->findCaseValue(DestVal);
6863cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredCase == 0) continue;
6873cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6883cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If PredSI doesn't go to DestBB on this value, then it won't reach the
6893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // case on this condition.
6903cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredSI->getSuccessor(PredCase) != DestBB &&
6913cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          DestSI->getSuccessor(i) != DestBB)
6923cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        continue;
6933cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6943cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Otherwise, we're safe to make the change.  Make sure that the edge from
6953cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // DestSI to DestSucc is not critical and has no PHI nodes.
69693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
69793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "THROUGH: " << *DestSI);
6983cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6993cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If the destination has PHI nodes, just split the edge for updating
7003cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // simplicity.
7013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
7023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        SplitCriticalEdge(DestSI, i, this);
7033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        DestSucc = DestSI->getSuccessor(i);
7043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      }
7053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      FoldSingleEntryPHINodes(DestSucc);
7063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      PredSI->setSuccessor(PredCase, DestSucc);
7073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      MadeChange = true;
7083cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    }
7093cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7103cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (MadeChange)
7113cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      return true;
7123cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  }
7133cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7143cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  return false;
7153cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner}
7163cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7173cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
71869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
71969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// load instruction, eliminate it by replacing it with a PHI node.  This is an
72069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// important optimization that encourages jump threading, and needs to be run
72169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// interlaced with other jump threading tasks.
72269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattnerbool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
72369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Don't hack volatile loads.
72469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LI->isVolatile()) return false;
72569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
72669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the load is defined in a block with exactly one predecessor, it can't be
72769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // partially redundant.
72869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *LoadBB = LI->getParent();
72969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadBB->getSinglePredecessor())
73069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
73169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
73269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Value *LoadedPtr = LI->getOperand(0);
73369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
73469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded operand is defined in the LoadBB, it can't be available.
73569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // FIXME: Could do PHI translation, that would be fun :)
73669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
73769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (PtrOp->getParent() == LoadBB)
73869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return false;
73969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Scan a few instructions up from the load, to see if it is obviously live at
74169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // the entry to its block.
74269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock::iterator BBIt = LI;
74369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74452c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner  if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
74552c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner                                                     BBIt, 6)) {
74669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If the value if the load is locally available within the block, just use
74769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // it.  This frequently occurs for reg2mem'd allocas.
74869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
7492a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner
7502a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // If the returned value is the load itself, replace with an undef. This can
7512a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // only happen in dead loops.
7529e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
75369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->replaceAllUsesWith(AvailableVal);
75469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->eraseFromParent();
75569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return true;
75669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
75769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
75869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Otherwise, if we scanned the whole block and got to the top of the block,
75969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we know the block is locally transparent to the load.  If not, something
76069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // might clobber its value.
76169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BBIt != LoadBB->begin())
76269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
76369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
76469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
76569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SmallPtrSet<BasicBlock*, 8> PredsScanned;
76669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
76769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  AvailablePredsTy AvailablePreds;
76869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *OneUnavailablePred = 0;
76969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If we got here, the loaded value is transparent through to the start of the
77169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // block.  Check to see if it is available in any of the predecessor blocks.
77269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
77369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       PI != PE; ++PI) {
77469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BasicBlock *PredBB = *PI;
77569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If we already scanned this predecessor, skip it.
77769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredsScanned.insert(PredBB))
77869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
77969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
78069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Scan the predecessor to see if the value is available in the pred.
78169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BBIt = PredBB->end();
78252c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
78369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredAvailable) {
78469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred = PredBB;
78569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
78669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
78769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
78869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If so, this load is partially redundant.  Remember this info so that we
78969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // can create a PHI node.
79069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
79169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
79269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
79369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded value isn't available in any predecessor, it isn't partially
79469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // redundant.
79569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (AvailablePreds.empty()) return false;
79669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
79769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Okay, the loaded value is available in at least one (and maybe all!)
79869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors.  If the value is unavailable in more than one unique
79969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessor, we want to insert a merge block for those common predecessors.
80069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This ensures that we only have to insert one reload, thus not increasing
80169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // code size.
80269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *UnavailablePred = 0;
80369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
80469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If there is exactly one predecessor where the value is unavailable, the
80569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // already computed 'OneUnavailablePred' block is it.  If it ends in an
80669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // unconditional branch, we know that it isn't a critical edge.
80769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (PredsScanned.size() == AvailablePreds.size()+1 &&
80869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
80969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred = OneUnavailablePred;
81069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  } else if (PredsScanned.size() != AvailablePreds.size()) {
81169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Otherwise, we had multiple unavailable predecessors or we had a critical
81269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // edge from the one.
81369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<BasicBlock*, 8> PredsToSplit;
81469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
81569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
81769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      AvailablePredSet.insert(AvailablePreds[i].first);
81869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Add all the unavailable predecessors to the PredsToSplit list.
82069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
82169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner         PI != PE; ++PI)
82269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!AvailablePredSet.count(*PI))
82369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        PredsToSplit.push_back(*PI);
82469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
82569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Split them out to their own block.
82669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred =
82769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
82869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                             "thread-split", this);
82969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
83069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the value isn't available in all predecessors, then there will be
83269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // exactly one where it isn't available.  Insert a load on that edge and add
83369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // it to the AvailablePreds list.
83469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (UnavailablePred) {
83569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
83669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Can't handle critical edge here!");
83769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
83869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 UnavailablePred->getTerminator());
83969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
84069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
84169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
84269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Now we know that each predecessor of this block has a value in
84369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // AvailablePreds, sort them for efficient access as we're walking the preds.
844a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
84569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
84669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Create a PHI node at the start of the block for the PRE'd load value.
84769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
84869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PN->takeName(LI);
84969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Insert new entries into the PHI for each predecessor.  A single block may
85169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // have multiple entries here.
85269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
85369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       ++PI) {
85469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePredsTy::iterator I =
85569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
85669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                       std::make_pair(*PI, (Value*)0));
85769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(I != AvailablePreds.end() && I->first == *PI &&
85969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Didn't find entry for predecessor!");
86069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    PN->addIncoming(I->second, I->first);
86269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
86369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //cerr << "PRE: " << *LI << *PN << "\n";
86569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->replaceAllUsesWith(PN);
86769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->eraseFromParent();
86869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  return true;
87069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner}
87169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
8725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// FindMostPopularDest - The specified list contains multiple possible
8735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// threadable destinations.  Pick the one that occurs the most frequently in
8745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the list.
8755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerstatic BasicBlock *
8765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerFindMostPopularDest(BasicBlock *BB,
8775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    const SmallVectorImpl<std::pair<BasicBlock*,
8785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  BasicBlock*> > &PredToDestList) {
8795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredToDestList.empty());
880785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine popularity.  If there are multiple possible destinations, we
8825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // explicitly choose to ignore 'undef' destinations.  We prefer to thread
8835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // blocks with known and real destinations to threading undef.  We'll handle
8845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // them later if interesting.
8855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned> DestPopularity;
8865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
8875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second)
8885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestPopularity[PredToDestList[i].second]++;
889785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Find the most popular dest.
8915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
8925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = DPI->first;
8935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned Popularity = DPI->second;
8945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 4> SamePopularity;
89578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
8965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (++DPI; DPI != DestPopularity.end(); ++DPI) {
8975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the popularity of this entry isn't higher than the popularity we've
8985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // seen so far, ignore it.
8995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (DPI->second < Popularity)
9005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ; // ignore.
9015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (DPI->second == Popularity) {
9025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is the same as what we've seen so far, keep track of it.
9035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.push_back(DPI->first);
9045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    } else {
9055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is more popular, remember it.
9065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.clear();
9075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = DPI->first;
9085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Popularity = DPI->second;
9095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
91078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
9115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, now we know the most popular destination.  If there is more than
9135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // destination, we need to determine one.  This is arbitrary, but we need
9145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to make a deterministic decision.  Pick the first one that appears in the
9155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // successor list.
9165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!SamePopularity.empty()) {
9175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SamePopularity.push_back(MostPopularDest);
9185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    TerminatorInst *TI = BB->getTerminator();
9195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0; ; ++i) {
9205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
92112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (std::find(SamePopularity.begin(), SamePopularity.end(),
9235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    TI->getSuccessor(i)) == SamePopularity.end())
9245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        continue;
9255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = TI->getSuccessor(i);
92712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      break;
92812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
92912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
93012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, we have finally picked the most popular destination.
9325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return MostPopularDest;
9335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
9345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9351c96b4187be7589492dccf33e9fe7679ac61023dChris Lattnerbool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB) {
9365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If threading this would thread across a loop header, don't even try to
9375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // thread the edge.
9385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (LoopHeaders.count(BB))
93912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
94012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
9421c96b4187be7589492dccf33e9fe7679ac61023dChris Lattner  if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
94312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
9445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredValues.empty() &&
9455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         "ComputeValueKnownInPredecessors returned true with no values");
9465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DEBUG(errs() << "IN BB: " << *BB;
9485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << "  BB '" << BB->getName() << "': FOUND condition = ";
9505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PredValues[i].first)
9515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << *PredValues[i].first;
9525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          else
9535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << "UNDEF";
9545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << " for pred '" << PredValues[i].second->getName()
9555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << "'.\n";
9565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        });
95712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Decide what we want to thread through.  Convert our list of known values to
9595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a list of known destinations for each pred.  This also discards duplicate
9605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors and keeps track of the undefined inputs (which are represented
961e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // as a null dest in the PredToDestList).
9625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallPtrSet<BasicBlock*, 16> SeenPreds;
9635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
9645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *OnlyDest = 0;
9665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
9675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *Pred = PredValues[i].second;
9705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!SeenPreds.insert(Pred))
9715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      continue;  // Duplicate predecessor entry.
97212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the predecessor ends with an indirect goto, we can't change its
9745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // destination.
9755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (isa<IndirectBrInst>(Pred->getTerminator()))
97612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      continue;
97712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *Val = PredValues[i].first;
9795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *DestBB;
9815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (Val == 0)      // Undef.
9825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = 0;
9835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
9845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = BI->getSuccessor(Val->isZero());
9855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else {
9865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
9875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = SI->getSuccessor(SI->findCaseValue(Val));
98812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
9895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If we have exactly one destination, remember it for efficiency below.
9915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (i == 0)
9925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = DestBB;
9935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (OnlyDest != DestBB)
9945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = MultipleDestSentinel;
99512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredToDestList.push_back(std::make_pair(Pred, DestBB));
99712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
99812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If all edges were unthreadable, we fail.
10005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredToDestList.empty())
100112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
100212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine which is the most common successor.  If we have many inputs and
10045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // this block is a switch, we want to start by threading the batch that goes
10055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to the most popular destination first.  If we only know about one
10065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threadable destination (the common case) we can avoid this.
10075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = OnlyDest;
100812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == MultipleDestSentinel)
10105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = FindMostPopularDest(BB, PredToDestList);
101112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Now that we know what the most popular destination is, factor all
10135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors that will jump to it into a single predecessor.
10145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 16> PredsToFactor;
10155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
10165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second == MostPopularDest) {
10175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      BasicBlock *Pred = PredToDestList[i].first;
10185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // This predecessor may be a switch or something else that has multiple
10205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // edges to the block.  Factor each of these edges by listing them
10215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // according to # occurrences in PredsToFactor.
10225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      TerminatorInst *PredTI = Pred->getTerminator();
10235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
10245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (PredTI->getSuccessor(i) == BB)
10255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          PredsToFactor.push_back(Pred);
10265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
10275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If the threadable edges are branching on an undefined value, we get to pick
10295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // the destination that these predecessors should get to.
10305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == 0)
10315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = BB->getTerminator()->
10325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            getSuccessor(GetBestDestForJumpOnUndef(BB));
10335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
103412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  // Ok, try to thread it!
10355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, PredsToFactor, MostPopularDest);
10365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
10375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
10395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the current block.  See if there are any simplifications we can do based on
10405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// inputs to the phi node.
10415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
10425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
10435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *BB = PN->getParent();
10445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If any of the predecessor blocks end in an unconditional branch, we can
10465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // *duplicate* the jump into that block in order to further encourage jump
10475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threading and to eliminate cases where we have branch on a phi of an icmp
10485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // (branch on icmp is much better).
10495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // We don't want to do this tranformation for switches, because we don't
10515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // really want to duplicate a switch.
10525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<SwitchInst>(BB->getTerminator()))
10535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
10545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look for unconditional branch predecessors.
10565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *PredBB = PN->getIncomingBlock(i);
10585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
10595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (PredBr->isUnconditional() &&
10605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          // Try to duplicate BB into PredBB.
10615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
10625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return true;
10635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
10645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
106612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel}
106712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
106812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
106978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
107078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
107178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// NewPred using the entries from OldPred (suitably mapped).
107278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
107378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *OldPred,
107478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *NewPred,
107578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                     DenseMap<Instruction*, Value*> &ValueMap) {
107678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator PNI = PHIBB->begin();
107778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner       PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
107878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Ok, we have a PHI node.  Figure out what the incoming value was for the
107978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // DestBlock.
108078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Value *IV = PN->getIncomingValueForBlock(OldPred);
1081bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
108278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap the value if necessary.
108378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
108478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
108578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (I != ValueMap.end())
108678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        IV = I->second;
1087bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    }
108878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
108978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PN->addIncoming(IV, NewPred);
1090bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  }
1091fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
1092fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
10935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ThreadEdge - We have decided that it is safe and profitable to factor the
10945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
10955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// across BB.  Transform the IR to reflect this change.
10965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ThreadEdge(BasicBlock *BB,
10975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                               const SmallVectorImpl<BasicBlock*> &PredBBs,
1098bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner                               BasicBlock *SuccBB) {
1099eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  // If threading to the same block as we come from, we would infinite loop.
1100eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  if (SuccBB == BB) {
110193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  Not threading across BB '" << BB->getName()
110293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - would thread to self!\n");
1103eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner    return false;
1104eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  }
1105eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner
1106fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // If threading this would thread across a loop header, don't thread the edge.
1107fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // See the comments above FindLoopHeaders for justifications and caveats.
1108fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (LoopHeaders.count(BB)) {
11095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Not threading across loop header BB '" << BB->getName()
111093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' to dest BB '" << SuccBB->getName()
111193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - it might create an irreducible loop!\n");
1112fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    return false;
1113fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
1114fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
111578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
111678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (JumpThreadCost > Threshold) {
111778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not threading BB '" << BB->getName()
111878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << JumpThreadCost << "\n");
111978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
112078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
112178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
11225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // And finally, do it!  Start by factoring the predecessors is needed.
11235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *PredBB;
11245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredBBs.size() == 1)
11255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = PredBBs[0];
11265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  else {
11275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Factoring out " << PredBBs.size()
11285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << " common predecessors.\n");
11295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
11305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                    ".thr_comm", this);
11315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
11325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
1133a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // And finally, do it!
113493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1135460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar        << SuccBB->getName() << "' with cost: " << JumpThreadCost
113693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << ", across block:\n    "
113793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << *BB << "\n");
1138a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
1139bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We are going to have to map operands from the original BB block to the new
1140bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1141bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // account for entry from PredBB.
1142bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
1143bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
11441d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
11451d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getName()+".thread",
11461d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getParent(), BB);
1147bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  NewBB->moveAfter(PredBB);
1148bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1149bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BasicBlock::iterator BI = BB->begin();
1150bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1151bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1152bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1153bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Clone the non-phi instructions of BB into NewBB, keeping track of the
1154bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
1155bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; !isa<TerminatorInst>(BI); ++BI) {
11566776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky    Instruction *New = BI->clone();
1157460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar    New->setName(BI->getName());
1158bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    NewBB->getInstList().push_back(New);
1159bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[BI] = New;
1160bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1161bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Remap operands to patch up intra-block references.
1162bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1163f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1164f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1165f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        if (I != ValueMapping.end())
1166f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman          New->setOperand(i, I->second);
1167f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      }
1168bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
1169bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1170bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We didn't copy the terminator from BB over to NewBB, because there is now
1171bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // an unconditional jump to SuccBB.  Insert the unconditional jump.
1172bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BranchInst::Create(SuccBB, NewBB);
1173bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1174bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1175bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // PHI nodes for NewBB now.
117678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1177177480b7ede0441135572d641a2497df25a7d95fChris Lattner
1178433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // If there were values defined in BB that are used outside the block, then we
1179433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // now have to update all uses of the value to use either the original value,
1180433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
1181433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
1182433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SSAUpdater SSAUpdate;
1183433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SmallVector<Use*, 16> UsesToRename;
1184433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1185433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // Scan all uses of this instruction to see if it is used outside of its
1186433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // block, and if so, record them in UsesToRename.
1187433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1188433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner         ++UI) {
1189433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Instruction *User = cast<Instruction>(*UI);
1190433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1191433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
1192433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          continue;
1193433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      } else if (User->getParent() == BB)
1194433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        continue;
1195433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1196433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      UsesToRename.push_back(&UI.getUse());
1197433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    }
1198433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1199433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // If there are no uses outside the block, we're done with this instruction.
1200433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    if (UsesToRename.empty())
1201433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      continue;
1202433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1203433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1204433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1205433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
1206433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1207433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // with the two values we know.
1208433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.Initialize(I);
1209433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(BB, I);
1210433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1211433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1212433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    while (!UsesToRename.empty())
1213433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1214433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "\n");
1215433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  }
1216433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1217433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1218ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1219bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1220bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // us to simplify any PHI nodes in BB.
1221bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  TerminatorInst *PredTerm = PredBB->getTerminator();
1222bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1223bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (PredTerm->getSuccessor(i) == BB) {
1224c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BB, PredBB, TD);
1225bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      PredTerm->setSuccessor(i, NewBB);
1226bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1227ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1228ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // At this point, the IR is fully up to date and consistent.  Do a quick scan
1229ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // over the new instructions and zap any that are constants or dead.  This
1230ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // frequently happens because of phi translation.
1231ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  BI = NewBB->begin();
1232ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1233ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    Instruction *Inst = BI++;
1234fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
1235e34537856a544c83513e390ac9552a8bc3823346Chris Lattner    if (Value *V = SimplifyInstruction(Inst, TD)) {
1236fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      WeakVH BIHandle(BI);
1237fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      ReplaceAndSimplifyAllUses(Inst, V, TD);
1238fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (BIHandle == 0)
1239fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        BI = NewBB->begin();
1240ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      continue;
1241ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    }
1242ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1243ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    RecursivelyDeleteTriviallyDeadInstructions(Inst);
1244ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  }
1245fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1246fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Threaded an edge!
1247fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  ++NumThreads;
1248fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return true;
1249177480b7ede0441135572d641a2497df25a7d95fChris Lattner}
125078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
125178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
125278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
125378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// If we can duplicate the contents of BB up into PredBB do so now, this
125478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// improves the odds that the branch will be on an analyzable instruction like
125578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// a compare.
125678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerbool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
125778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                     BasicBlock *PredBB) {
125878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If BB is a loop header, then duplicating this block outside the loop would
125978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // cause us to transform this into an irreducible loop, don't do this.
126078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // See the comments above FindLoopHeaders for justifications and caveats.
126178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (LoopHeaders.count(BB)) {
126278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating loop header '" << BB->getName()
126378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' into predecessor block '" << PredBB->getName()
126478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - it might create an irreducible loop!\n");
126578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
126678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
126778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
126878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
126978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (DuplicationCost > Threshold) {
127078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating BB '" << BB->getName()
127178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << DuplicationCost << "\n");
127278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
127378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
127478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
127578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Okay, we decided to do this!  Clone all the instructions in BB onto the end
127678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // of PredBB.
127778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DEBUG(errs() << "  Duplicating block '" << BB->getName() << "' into end of '"
127878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
127978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << DuplicationCost << " block is:" << *BB << "\n");
128078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We are going to have to map operands from the original BB block into the
128278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB block.  Evaluate PHI nodes in BB.
128378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
128478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::iterator BI = BB->begin();
128678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
128778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
128878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
129078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Clone the non-phi instructions of BB into PredBB, keeping track of the
129278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
129378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; BI != BB->end(); ++BI) {
129478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Instruction *New = BI->clone();
129578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    New->setName(BI->getName());
129678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PredBB->getInstList().insert(OldPredBranch, New);
129778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[BI] = New;
129878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap operands to patch up intra-block references.
130078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
130178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
130278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
130378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (I != ValueMapping.end())
130478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          New->setOperand(i, I->second);
130578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
130678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
130778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Check to see if the targets of the branch had PHI nodes. If so, we need to
130978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // add entries to the PHI nodes for branch from PredBB now.
131078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
131178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
131278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
131378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
131478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
131578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
131678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If there were values defined in BB that are used outside the block, then we
131778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // now have to update all uses of the value to use either the original value,
131878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
131978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
132078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SSAUpdater SSAUpdate;
132178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<Use*, 16> UsesToRename;
132278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
132378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Scan all uses of this instruction to see if it is used outside of its
132478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // block, and if so, record them in UsesToRename.
132578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
132678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner         ++UI) {
132778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Instruction *User = cast<Instruction>(*UI);
132878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
132978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
133078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          continue;
133178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else if (User->getParent() == BB)
133278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        continue;
133378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      UsesToRename.push_back(&UI.getUse());
133578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
133678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If there are no uses outside the block, we're done with this instruction.
133878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (UsesToRename.empty())
133978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
134078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
134278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
134478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
134578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // with the two values we know.
134678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.Initialize(I);
134778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(BB, I);
134878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
134978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    while (!UsesToRename.empty())
135178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
135278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "\n");
135378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
135478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
135678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // that we nuked.
1357c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  RemovePredecessorAndSimplify(BB, PredBB, TD);
135878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Remove the unconditional branch at the end of the PredBB block.
136078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  OldPredBranch->eraseFromParent();
136178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
136278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  ++NumDupes;
136378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return true;
136478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
136578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
136678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1367