JumpThreading.cpp revision 7b550ccfc5a3346c17e0390a59e2d6d19bc52705
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"
19ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner#include "llvm/Analysis/ConstantFolding.h"
202cc675180b06d0a2173365a4015606933f1a285dChris Lattner#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21bd3401fa98b578080e227afce940bca80137dea6Chris Lattner#include "llvm/Transforms/Utils/Local.h"
22433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner#include "llvm/Transforms/Utils/SSAUpdater.h"
23ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner#include "llvm/Target/TargetData.h"
24fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/DenseMap.h"
25fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/Statistic.h"
26fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/STLExtras.h"
27fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallPtrSet.h"
28fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/ADT/SmallSet.h"
298383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Support/CommandLine.h"
30177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/Support/Debug.h"
3193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar#include "llvm/Support/raw_ostream.h"
328383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerusing namespace llvm;
338383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
34bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumThreads, "Number of jumps threaded");
35bd3401fa98b578080e227afce940bca80137dea6Chris LattnerSTATISTIC(NumFolds,   "Number of terminators folded");
3678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSTATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
378383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
38177480b7ede0441135572d641a2497df25a7d95fChris Lattnerstatic cl::opt<unsigned>
39177480b7ede0441135572d641a2497df25a7d95fChris LattnerThreshold("jump-threading-threshold",
40177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::desc("Max block size to duplicate for jump threading"),
41177480b7ede0441135572d641a2497df25a7d95fChris Lattner          cl::init(6), cl::Hidden);
42177480b7ede0441135572d641a2497df25a7d95fChris Lattner
438383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnernamespace {
4494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// This pass performs 'jump threading', which looks at blocks that have
4594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// multiple predecessors and multiple successors.  If one or more of the
4694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// predecessors of the block can be proven to always jump to one of the
4794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// successors, we forward the edge from the predecessor to the successor by
4894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// duplicating the contents of this block.
4994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5094019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// An example of when this can occur is code like this:
5194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if () { ...
5394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///     X = 4;
5494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   }
5594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///   if (X < 3) {
5694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
5794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// In this case, the unconditional branch at the end of the first if can be
5894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// revectored to the false side of the second if.
5994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  ///
603e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  class JumpThreading : public FunctionPass {
61ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    TargetData *TD;
62fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#ifdef NDEBUG
63fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#else
65fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#endif
678383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  public:
688383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    static char ID; // Pass identification
69ae73dc1448d25b02cabc7c64c86c64371453dda8Dan Gohman    JumpThreading() : FunctionPass(&ID) {}
708383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
718383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    bool runOnFunction(Function &F);
72fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    void FindLoopHeaders(Function &F);
73fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
74c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    bool ProcessBlock(BasicBlock *BB);
75bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
7678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
7778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                          BasicBlock *PredBB);
7878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
799683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
80421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
813cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
826bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
83d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner    bool ProcessJumpOnPHI(PHINode *PN);
84ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner    bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
85a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
8669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
8769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
888383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  };
898383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
908383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
91844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar JumpThreading::ID = 0;
92844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<JumpThreading>
93844731a7f1909f55935e3514c9e713a62d67662eDan GohmanX("jump-threading", "Jump Threading");
94844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
958383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// Public interface to the Jump Threading pass
968383a7b7a6acdae478d4b4c2520915153b73f676Chris LattnerFunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
978383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
988383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// runOnFunction - Top level algorithm.
998383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner///
1008383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerbool JumpThreading::runOnFunction(Function &F) {
10193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
10202a436c48ecff9e34d50ce0a2f861e5acdd9bf3fDan Gohman  TD = getAnalysisIfAvailable<TargetData>();
103bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
104fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindLoopHeaders(F);
105fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
106bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  bool AnotherIteration = true, EverChanged = false;
107bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  while (AnotherIteration) {
108bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = false;
109bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    bool Changed = false;
110421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
111421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BasicBlock *BB = I;
112421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      while (ProcessBlock(BB))
113bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Changed = true;
114421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
115421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ++I;
116421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
117421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // If the block is trivially dead, zap it.  This eliminates the successor
118421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // edges which simplifies the CFG.
119421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      if (pred_begin(BB) == pred_end(BB) &&
12020fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner          BB != &BB->getParent()->getEntryBlock()) {
12193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        DEBUG(errs() << "  JT: Deleting dead block '" << BB->getName()
12278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              << "' with terminator: " << *BB->getTerminator() << '\n');
123fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.erase(BB);
124421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        DeleteDeadBlock(BB);
125421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        Changed = true;
126421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      }
127421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
128bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = Changed;
129bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EverChanged |= Changed;
130bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
131fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
132fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  LoopHeaders.clear();
133bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  return EverChanged;
1348383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
135177480b7ede0441135572d641a2497df25a7d95fChris Lattner
13678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
13778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// thread across it.
13878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
13978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  /// Ignore PHI nodes, these will be flattened when duplication happens.
14078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::const_iterator I = BB->getFirstNonPHI();
14178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
14278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Sum up the cost of each instruction until we get to the terminator.  Don't
14378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // include the terminator because the copy won't include it.
14478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned Size = 0;
14578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; !isa<TerminatorInst>(I); ++I) {
14678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Debugger intrinsics don't incur code size.
14778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<DbgInfoIntrinsic>(I)) continue;
14878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
14978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If this is a pointer->pointer bitcast, it is free.
15078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
15178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
15278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
15378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // All other instructions count for at least one unit.
15478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ++Size;
15578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
15678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Calls are more expensive.  If they are non-intrinsic calls, we model them
15778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 4.  If they are a non-vector intrinsic, we model them
15878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 2 total, and if they are a vector intrinsic, we model
15978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // them as having cost 1.
16078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
16178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (!isa<IntrinsicInst>(CI))
16278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 3;
16378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      else if (!isa<VectorType>(CI->getType()))
16478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 1;
16578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
16678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
16778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
16878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Threading through a switch statement is particularly profitable.  If this
16978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // block ends in a switch, decrease its cost to make it more likely to happen.
17078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(I))
17178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Size = Size > 6 ? Size-6 : 0;
17278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return Size;
17478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
17578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
178fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// FindLoopHeaders - We do not want jump threading to turn proper loop
179fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// structures into irreducible loops.  Doing this breaks up the loop nesting
180fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// hierarchy and pessimizes later transformations.  To prevent this from
181fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// happening, we first have to find the loop headers.  Here we approximate this
182fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// by finding targets of backedges in the CFG.
183fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
184fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// Note that there definitely are cases when we want to allow threading of
185fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edges across a loop header.  For example, threading a jump from outside the
186fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// loop (the preheader) to an exit block of the loop is definitely profitable.
187fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// It is also almost always profitable to thread backedges from within the loop
188fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// to exit blocks, and is often profitable to thread backedges to other blocks
189fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// within the loop (forming a nested loop).  This simple analysis is not rich
190fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// enough to track all of these properties and keep it up-to-date as the CFG
191fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// mutates, so we don't allow any of these transformations.
192fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
193fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpvoid JumpThreading::FindLoopHeaders(Function &F) {
194fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
195fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindFunctionBackedges(F, Edges);
196fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
197fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
198fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
199fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
200fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
201fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
2026bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
2036bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// value for the PHI, factor them together so we get one block to thread for
2046bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// the whole group.
2056bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// This is important for things like "phi i1 [true, true, false, true, x]"
2066bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// where we only need to clone the block for the true blocks once.
2076bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner///
2089683f181746c2312c8828c79b6e25a07fb441d57Nick LewyckyBasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
2096bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  SmallVector<BasicBlock*, 16> CommonPreds;
2106bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2119683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    if (PN->getIncomingValue(i) == Val)
2126bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner      CommonPreds.push_back(PN->getIncomingBlock(i));
2136bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
2146bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  if (CommonPreds.size() == 1)
2156bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner    return CommonPreds[0];
2166bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
21793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "  Factoring out " << CommonPreds.size()
21893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << " common predecessors.\n");
2196bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  return SplitBlockPredecessors(PN->getParent(),
2206bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner                                &CommonPreds[0], CommonPreds.size(),
2216bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner                                ".thr_comm", this);
2226bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner}
2236bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
2246bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
225e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
226e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// in an undefined jump, decide which block is best to revector to.
227e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
228e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// Since we can pick an arbitrary destination, we pick the successor with the
229e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// fewest predecessors.  This should reduce the in-degree of the others.
230e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
231e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattnerstatic unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
232e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  TerminatorInst *BBTerm = BB->getTerminator();
233e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinSucc = 0;
234e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
235e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // Compute the successor with the minimum number of predecessors.
236e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
237e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
238e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TestBB = BBTerm->getSuccessor(i);
239e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
240e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (NumPreds < MinNumPreds)
241e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      MinSucc = i;
242e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
243e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
244e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  return MinSucc;
245e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner}
246e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
247c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner/// ProcessBlock - If there are any predecessors whose control can be threaded
248177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// through to a successor, transform them now.
249c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattnerbool JumpThreading::ProcessBlock(BasicBlock *BB) {
25069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If this block has a single predecessor, and if that pred has a single
25169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // successor, merge the blocks.  This encourages recursive jump threading
25269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // because now the condition in this block can be threaded through
25369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors of our predecessor block.
25469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BasicBlock *SinglePred = BB->getSinglePredecessor())
255f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
256f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner        SinglePred != BB) {
257fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // If SinglePred was a loop header, BB becomes one.
258fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      if (LoopHeaders.erase(SinglePred))
259fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.insert(BB);
260fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
2613d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Remember if SinglePred was the entry block of the function.  If so, we
2623d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // will need to move BB back to the entry position.
2633d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
26469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      MergeBasicBlockIntoOnlyPred(BB);
2653d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner
2663d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      if (isEntry && BB != &BB->getParent()->getEntryBlock())
2673d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner        BB->moveBefore(&BB->getParent()->getEntryBlock());
26869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
26969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
27069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
2716e7b322d36fc9e571cd54cb4b9c6043346a97e3aMatthijs Kooijman  // See if this block ends with a branch or switch.  If so, see if the
272177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // condition is a phi node.  If so, and if an entry of the phi node is a
273177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // constant, we can thread the block.
274177480b7ede0441135572d641a2497df25a7d95fChris Lattner  Value *Condition;
275bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
276bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Can't thread an unconditional jump.
277bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (BI->isUnconditional()) return false;
278177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = BI->getCondition();
279bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
280177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = SI->getCondition();
281177480b7ede0441135572d641a2497df25a7d95fChris Lattner  else
282177480b7ede0441135572d641a2497df25a7d95fChris Lattner    return false; // Must be an invoke.
283bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
284bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // If the terminator of this block is branching on a constant, simplify the
285037c781de797242ba652db775f1f2c5d2d4eb19bChris Lattner  // terminator to an unconditional branch.  This can occur due to threading in
286bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // other blocks.
287bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (isa<ConstantInt>(Condition)) {
28893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
28978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *BB->getTerminator() << '\n');
290bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ++NumFolds;
291bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ConstantFoldTerminator(BB);
292bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    return true;
293bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
294bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
295421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the terminator is branching on an undef, we can pick any of the
296e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
297421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (isa<UndefValue>(Condition)) {
298e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
299421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
300421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Fold the branch/switch.
301e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TerminatorInst *BBTerm = BB->getTerminator();
302421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
303e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (i == BestSucc) continue;
304421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BBTerm->getSuccessor(i)->removePredecessor(BB);
305421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
306421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
30793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
30878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding undef terminator: " << *BBTerm << '\n');
309e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
310421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BBTerm->eraseFromParent();
311421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
312421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
313421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
314421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Instruction *CondInst = dyn_cast<Instruction>(Condition);
315421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
316421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the condition is an instruction defined in another block, see if a
317421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // predecessor has the same condition:
318421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBX, BBY
319421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //  BBX:
320421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBZ, BBW
321421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (!Condition->hasOneUse() && // Multiple uses.
322421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
323421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
324421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (isa<BranchInst>(BB->getTerminator())) {
325421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      for (; PI != E; ++PI)
326421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
327421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner          if (PBI->isConditional() && PBI->getCondition() == Condition &&
328421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner              ProcessBranchOnDuplicateCond(*PI, BB))
329421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner            return true;
3303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    } else {
3313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
3323cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      for (; PI != E; ++PI)
3333cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
3343cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          if (PSI->getCondition() == Condition &&
3353cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner              ProcessSwitchOnDuplicateCond(*PI, BB))
3363cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner            return true;
337421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
338421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
339421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
340421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // All the rest of our checks depend on the condition being an instruction.
341421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (CondInst == 0)
342421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return false;
343421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
344177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // See if this is a phi node in the current block.
345421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
346421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (PN->getParent() == BB)
347421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      return ProcessJumpOnPHI(PN);
348177480b7ede0441135572d641a2497df25a7d95fChris Lattner
3496bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // If this is a conditional branch whose condition is and/or of a phi, try to
3506bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // simplify it.
351421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if ((CondInst->getOpcode() == Instruction::And ||
352421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner       CondInst->getOpcode() == Instruction::Or) &&
353421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      isa<BranchInst>(BB->getTerminator()) &&
354421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ProcessBranchOnLogical(CondInst, BB,
355421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                             CondInst->getOpcode() == Instruction::And))
356421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
3576bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
3589683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
3599683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    if (isa<PHINode>(CondCmp->getOperand(0))) {
3609683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      // If we have "br (phi != 42)" and the phi node has any constant values
3619683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      // as operands, we can thread through this block.
3629683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      //
3639683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      // If we have "br (cmp phi, x)" and the phi node contains x such that the
3649683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      // comparison uniquely identifies the branch target, we can thread
3659683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      // through this block.
3669683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky
3679683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      if (ProcessBranchOnCompare(CondCmp, BB))
3689683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky        return true;
3699683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    }
37079c740ff479dde322aceafe15887b162c19ea195Chris Lattner
37179c740ff479dde322aceafe15887b162c19ea195Chris Lattner    // If we have a comparison, loop over the predecessors to see if there is
37279c740ff479dde322aceafe15887b162c19ea195Chris Lattner    // a condition with the same value.
37379c740ff479dde322aceafe15887b162c19ea195Chris Lattner    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
37479c740ff479dde322aceafe15887b162c19ea195Chris Lattner    for (; PI != E; ++PI)
37579c740ff479dde322aceafe15887b162c19ea195Chris Lattner      if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
37679c740ff479dde322aceafe15887b162c19ea195Chris Lattner        if (PBI->isConditional() && *PI != BB) {
37779c740ff479dde322aceafe15887b162c19ea195Chris Lattner          if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
37879c740ff479dde322aceafe15887b162c19ea195Chris Lattner            if (CI->getOperand(0) == CondCmp->getOperand(0) &&
37979c740ff479dde322aceafe15887b162c19ea195Chris Lattner                CI->getOperand(1) == CondCmp->getOperand(1) &&
38079c740ff479dde322aceafe15887b162c19ea195Chris Lattner                CI->getPredicate() == CondCmp->getPredicate()) {
38179c740ff479dde322aceafe15887b162c19ea195Chris Lattner              // TODO: Could handle things like (x != 4) --> (x == 17)
38279c740ff479dde322aceafe15887b162c19ea195Chris Lattner              if (ProcessBranchOnDuplicateCond(*PI, BB))
38379c740ff479dde322aceafe15887b162c19ea195Chris Lattner                return true;
38479c740ff479dde322aceafe15887b162c19ea195Chris Lattner            }
38579c740ff479dde322aceafe15887b162c19ea195Chris Lattner          }
38679c740ff479dde322aceafe15887b162c19ea195Chris Lattner        }
3879683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  }
38869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
38969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Check for some cases that are worth simplifying.  Right now we want to look
39069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // for loads that are used by a switch or by the condition for the branch.  If
39169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we see one, check to see if it's partially redundant.  If so, insert a PHI
39269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // which can then be used to thread the values.
39369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //
39469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This is particularly important because reg2mem inserts loads and stores all
39569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // over the place, and this blocks jump threading if we don't zap them.
396421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Value *SimplifyValue = CondInst;
39769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
39869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (isa<Constant>(CondCmp->getOperand(1)))
39969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SimplifyValue = CondCmp->getOperand(0);
40069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
40169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
40269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (SimplifyPartiallyRedundantLoad(LI))
40369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
40469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
40569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
40669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // "(X == 4)" thread through this block.
407a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
408d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  return false;
409d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner}
410d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner
411421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
412421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// block that jump on exactly the same condition.  This means that we almost
413421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// always know the direction of the edge in the DESTBB:
414421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  PREDBB:
415421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, DESTBB, BBY
416421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  DESTBB:
417421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, BBZ, BBW
418421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///
419421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// If DESTBB has multiple predecessors, we can't just constant fold the branch
420421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// in DESTBB, we have to thread over it.
421421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattnerbool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
422421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                                 BasicBlock *BB) {
423421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
424421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
425421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If both successors of PredBB go to DESTBB, we don't know anything.  We can
426421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // fold the branch to an unconditional one, which allows other recursive
427421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // simplifications.
428421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  bool BranchDir;
429421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PredBI->getSuccessor(1) != BB)
430421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = true;
431421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else if (PredBI->getSuccessor(0) != BB)
432421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = false;
433421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else {
43493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << PredBB->getName()
43578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *PredBB->getTerminator() << '\n');
436421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
437421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(PredBB);
438421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
439421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
440421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
441421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
442421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
443421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the dest block has one predecessor, just fix the branch condition to a
444421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // constant and fold it.
445421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (BB->getSinglePredecessor()) {
44693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
44793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' folding condition to '" << BranchDir << "': "
44878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << *BB->getTerminator() << '\n');
449421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
4505a06cf644f35b873686c8694968192ad3385e36aChris Lattner    Value *OldCond = DestBI->getCondition();
4511d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
4521d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                          BranchDir));
453421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(BB);
4545a06cf644f35b873686c8694968192ad3385e36aChris Lattner    RecursivelyDeleteTriviallyDeadInstructions(OldCond);
455421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
456421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
457bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
458421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
459421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Next, figure out which successor we are threading to.
460421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
461421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
462fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
463bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  return ThreadEdge(BB, PredBB, SuccBB);
464421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
465421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
4663cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
4673cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// block that switch on exactly the same condition.  This means that we almost
4683cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// always know the direction of the edge in the DESTBB:
4693cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  PREDBB:
4703cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... DESTBB, BBY ... ]
4713cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  DESTBB:
4723cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... BBZ, BBW ]
4733cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///
4743cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// Optimizing switches like this is very important, because simplifycfg builds
4753cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// switches out of repeated 'if' conditions.
4763cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattnerbool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
4773cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                                 BasicBlock *DestBB) {
4782c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  // Can't thread edge to self.
4792c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  if (PredBB == DestBB)
4802c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner    return false;
4812c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner
4823cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
4833cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
4843cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
4853cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // There are a variety of optimizations that we can potentially do on these
4863cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // blocks: we order them from most to least preferable.
4873cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
4883cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
4893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // directly to their destination.  This does not introduce *any* code size
4906b233395025069f63156ea2b524cdb708a14731fDale Johannesen  // growth.  Skip debug info first.
4916b233395025069f63156ea2b524cdb708a14731fDale Johannesen  BasicBlock::iterator BBI = DestBB->begin();
4926b233395025069f63156ea2b524cdb708a14731fDale Johannesen  while (isa<DbgInfoIntrinsic>(BBI))
4936b233395025069f63156ea2b524cdb708a14731fDale Johannesen    BBI++;
4943cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
4953cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // FIXME: Thread if it just contains a PHI.
4966b233395025069f63156ea2b524cdb708a14731fDale Johannesen  if (isa<SwitchInst>(BBI)) {
4973cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool MadeChange = false;
4983cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    // Ignore the default edge for now.
4993cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
5003cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      ConstantInt *DestVal = DestSI->getCaseValue(i);
5013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      BasicBlock *DestSucc = DestSI->getSuccessor(i);
5023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
5043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // PredSI has an explicit case for it.  If so, forward.  If it is covered
5053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // by the default case, we can't update PredSI.
5063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      unsigned PredCase = PredSI->findCaseValue(DestVal);
5073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredCase == 0) continue;
5083cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5093cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If PredSI doesn't go to DestBB on this value, then it won't reach the
5103cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // case on this condition.
5113cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredSI->getSuccessor(PredCase) != DestBB &&
5123cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          DestSI->getSuccessor(i) != DestBB)
5133cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        continue;
5143cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5153cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Otherwise, we're safe to make the change.  Make sure that the edge from
5163cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // DestSI to DestSucc is not critical and has no PHI nodes.
51793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
51893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "THROUGH: " << *DestSI);
5193cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5203cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If the destination has PHI nodes, just split the edge for updating
5213cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // simplicity.
5223cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
5233cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        SplitCriticalEdge(DestSI, i, this);
5243cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        DestSucc = DestSI->getSuccessor(i);
5253cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      }
5263cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      FoldSingleEntryPHINodes(DestSucc);
5273cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      PredSI->setSuccessor(PredCase, DestSucc);
5283cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      MadeChange = true;
5293cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    }
5303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (MadeChange)
5323cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      return true;
5333cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  }
5343cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5353cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  return false;
5363cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner}
5373cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
5383cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
53969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
54069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// load instruction, eliminate it by replacing it with a PHI node.  This is an
54169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// important optimization that encourages jump threading, and needs to be run
54269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// interlaced with other jump threading tasks.
54369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattnerbool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
54469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Don't hack volatile loads.
54569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LI->isVolatile()) return false;
54669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
54769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the load is defined in a block with exactly one predecessor, it can't be
54869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // partially redundant.
54969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *LoadBB = LI->getParent();
55069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadBB->getSinglePredecessor())
55169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
55269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
55369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Value *LoadedPtr = LI->getOperand(0);
55469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
55569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded operand is defined in the LoadBB, it can't be available.
55669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // FIXME: Could do PHI translation, that would be fun :)
55769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
55869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (PtrOp->getParent() == LoadBB)
55969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return false;
56069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
56169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Scan a few instructions up from the load, to see if it is obviously live at
56269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // the entry to its block.
56369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock::iterator BBIt = LI;
56469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
56552c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner  if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
56652c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner                                                     BBIt, 6)) {
56769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If the value if the load is locally available within the block, just use
56869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // it.  This frequently occurs for reg2mem'd allocas.
56969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
5702a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner
5712a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // If the returned value is the load itself, replace with an undef. This can
5722a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // only happen in dead loops.
5739e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
57469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->replaceAllUsesWith(AvailableVal);
57569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->eraseFromParent();
57669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return true;
57769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
57869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
57969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Otherwise, if we scanned the whole block and got to the top of the block,
58069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we know the block is locally transparent to the load.  If not, something
58169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // might clobber its value.
58269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BBIt != LoadBB->begin())
58369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
58469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
58569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
58669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SmallPtrSet<BasicBlock*, 8> PredsScanned;
58769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
58869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  AvailablePredsTy AvailablePreds;
58969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *OneUnavailablePred = 0;
59069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
59169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If we got here, the loaded value is transparent through to the start of the
59269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // block.  Check to see if it is available in any of the predecessor blocks.
59369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
59469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       PI != PE; ++PI) {
59569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BasicBlock *PredBB = *PI;
59669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
59769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If we already scanned this predecessor, skip it.
59869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredsScanned.insert(PredBB))
59969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
60069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
60169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Scan the predecessor to see if the value is available in the pred.
60269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BBIt = PredBB->end();
60352c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
60469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredAvailable) {
60569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred = PredBB;
60669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
60769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
60869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
60969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If so, this load is partially redundant.  Remember this info so that we
61069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // can create a PHI node.
61169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
61269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
61369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
61469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded value isn't available in any predecessor, it isn't partially
61569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // redundant.
61669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (AvailablePreds.empty()) return false;
61769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
61869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Okay, the loaded value is available in at least one (and maybe all!)
61969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors.  If the value is unavailable in more than one unique
62069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessor, we want to insert a merge block for those common predecessors.
62169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This ensures that we only have to insert one reload, thus not increasing
62269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // code size.
62369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *UnavailablePred = 0;
62469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
62569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If there is exactly one predecessor where the value is unavailable, the
62669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // already computed 'OneUnavailablePred' block is it.  If it ends in an
62769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // unconditional branch, we know that it isn't a critical edge.
62869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (PredsScanned.size() == AvailablePreds.size()+1 &&
62969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
63069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred = OneUnavailablePred;
63169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  } else if (PredsScanned.size() != AvailablePreds.size()) {
63269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Otherwise, we had multiple unavailable predecessors or we had a critical
63369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // edge from the one.
63469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<BasicBlock*, 8> PredsToSplit;
63569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
63669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
63769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
63869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      AvailablePredSet.insert(AvailablePreds[i].first);
63969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
64069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Add all the unavailable predecessors to the PredsToSplit list.
64169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
64269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner         PI != PE; ++PI)
64369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!AvailablePredSet.count(*PI))
64469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        PredsToSplit.push_back(*PI);
64569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
64669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Split them out to their own block.
64769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred =
64869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
64969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                             "thread-split", this);
65069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
65169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
65269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the value isn't available in all predecessors, then there will be
65369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // exactly one where it isn't available.  Insert a load on that edge and add
65469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // it to the AvailablePreds list.
65569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (UnavailablePred) {
65669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
65769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Can't handle critical edge here!");
65869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
65969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 UnavailablePred->getTerminator());
66069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
66169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
66269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
66369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Now we know that each predecessor of this block has a value in
66469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // AvailablePreds, sort them for efficient access as we're walking the preds.
665a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
66669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
66769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Create a PHI node at the start of the block for the PRE'd load value.
66869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
66969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PN->takeName(LI);
67069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
67169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Insert new entries into the PHI for each predecessor.  A single block may
67269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // have multiple entries here.
67369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
67469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       ++PI) {
67569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePredsTy::iterator I =
67669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
67769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                       std::make_pair(*PI, (Value*)0));
67869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
67969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(I != AvailablePreds.end() && I->first == *PI &&
68069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Didn't find entry for predecessor!");
68169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
68269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    PN->addIncoming(I->second, I->first);
68369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
68469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
68569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //cerr << "PRE: " << *LI << *PN << "\n";
68669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
68769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->replaceAllUsesWith(PN);
68869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->eraseFromParent();
68969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
69069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  return true;
69169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner}
69269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
69369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
694e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
695d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner/// the current block.  See if there are any simplifications we can do based on
696d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner/// inputs to the phi node.
697d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner///
698d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattnerbool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
6996b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner  BasicBlock *BB = PN->getParent();
7006b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner
701e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // See if the phi node has any constant integer or undef values.  If so, we
702e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // can determine where the corresponding predecessor will branch.
703e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
704e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    Value *PredVal = PN->getIncomingValue(i);
7056b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner
7066b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner    // Check to see if this input is a constant integer.  If so, the direction
7076b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner    // of the branch is predictable.
708e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
7096b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      // Merge any common predecessors that will act the same.
7106b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI);
7116b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner
7126b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      BasicBlock *SuccBB;
7136b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
7146b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner        SuccBB = BI->getSuccessor(CI->isZero());
7156b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      else {
7166b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner        SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
7176b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner        SuccBB = SI->getSuccessor(SI->findCaseValue(CI));
7186b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      }
7196b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner
7206b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      // Ok, try to thread it!
7216b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      return ThreadEdge(BB, PredBB, SuccBB);
722e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    }
723e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
7246b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner    // If the input is an undef, then it doesn't matter which way it will go.
7256b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner    // Pick an arbitrary dest and thread the edge.
726e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
7276b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      // Merge any common predecessors that will act the same.
7286b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV);
7296b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      BasicBlock *SuccBB =
7306b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner        BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB));
7316b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner
7326b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      // Ok, try to thread it!
7336b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner      return ThreadEdge(BB, PredBB, SuccBB);
734e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    }
7356b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner  }
736f9065a904fca1018d6ea3e1536b9b3368c084725Chris Lattner
73778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If the incoming values are all variables, we don't know the destination of
73878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // any predecessors.  However, if any of the predecessor blocks end in an
73978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // unconditional branch, we can *duplicate* the jump into that block in order
74078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // to further encourage jump threading and to eliminate cases where we have
74178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // branch on a phi of an icmp (branch on icmp is much better).
74278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
74378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We don't want to do this tranformation for switches, because we don't
74478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // really want to duplicate a switch.
74578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(BB->getTerminator()))
74678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
74778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
74878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Look for unconditional branch predecessors.
74978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
75078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    BasicBlock *PredBB = PN->getIncomingBlock(i);
75178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
75278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PredBr->isUnconditional() &&
75378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // Try to duplicate BB into PredBB.
75478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
75578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        return true;
75678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
75778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
7586b65f47ad5d4da8bab31802a2c3df88379f0c9d9Chris Lattner  return false;
759bd3401fa98b578080e227afce940bca80137dea6Chris Lattner}
760bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
76178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
7626bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
7636bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// whose condition is an AND/OR where one side is PN.  If PN has constant
7646bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// operands that permit us to evaluate the condition for some operand, thread
7656bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// through the block.  For example with:
7666bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner///   br (and X, phi(Y, Z, false))
7676bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// the predecessor corresponding to the 'false' will always jump to the false
7686bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner/// destination of the branch.
7696bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner///
770ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattnerbool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
771ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner                                           bool isAnd) {
772ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  // If this is a binary operator tree of the same AND/OR opcode, check the
773ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  // LHS/RHS.
774ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
77543e2a035309f4e353a8bd5547d10125414597e74Duncan Sands    if ((isAnd && BO->getOpcode() == Instruction::And) ||
77643e2a035309f4e353a8bd5547d10125414597e74Duncan Sands        (!isAnd && BO->getOpcode() == Instruction::Or)) {
777ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner      if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
778ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner        return true;
779ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner      if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
780ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner        return true;
781ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner    }
782ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner
783ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  // If this isn't a PHI node, we can't handle it.
784ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  PHINode *PN = dyn_cast<PHINode>(V);
785ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner  if (!PN || PN->getParent() != BB) return false;
786ae65b3c7912138ec636b3bde5ff528d948161651Chris Lattner
7876bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // We can only do the simplification for phi nodes of 'false' with AND or
7886bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // 'true' with OR.  See if we have any entries in the phi for this.
7896bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  unsigned PredNo = ~0U;
7901d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
7911d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                          !isAnd);
7926bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7936bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner    if (PN->getIncomingValue(i) == PredCst) {
7946bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner      PredNo = i;
7956bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner      break;
7966bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner    }
7976bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  }
7986bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
7996bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // If no match, bail out.
8006bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  if (PredNo == ~0U)
8016bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner    return false;
8026bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
8036bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // If so, we can actually do this threading.  Merge any common predecessors
8046bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // that will act the same.
8056bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
8066bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
8076bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // Next, figure out which successor we are threading to.  If this was an AND,
8086bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // the constant must be FALSE, and we must be targeting the 'false' block.
8096bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // If this is an OR, the constant must be TRUE, and we must be targeting the
8106bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  // 'true' block.
8116bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
8126bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
813fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
814bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  return ThreadEdge(BB, PredBB, SuccBB);
8156bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner}
8166bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
8179683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
8189683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// hand sides of the compare instruction, try to determine the result. If the
8199683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// result can not be determined, a null pointer is returned.
8209683f181746c2312c8828c79b6e25a07fb441d57Nick Lewyckystatic Constant *GetResultOfComparison(CmpInst::Predicate pred,
8211ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson                                       Value *LHS, Value *RHS,
822e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson                                       LLVMContext &Context) {
8239683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (Constant *CLHS = dyn_cast<Constant>(LHS))
8249683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    if (Constant *CRHS = dyn_cast<Constant>(RHS))
825baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::getCompare(pred, CLHS, CRHS);
8269683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky
8279683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (LHS == RHS)
8289683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
8299683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      return ICmpInst::isTrueWhenEqual(pred) ?
8305defacc6e605f4651c6300237cef8e9bb2eb6d0eOwen Anderson                 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
8319683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky
8329683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  return 0;
8339683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky}
8349683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky
835a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
8369683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// node and a value.  If we can identify when the comparison is true between
8379683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// the phi inputs and the value, we can fold the compare for that edge and
8389683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky/// thread through it.
839a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattnerbool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
840a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
8419683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  Value *RHS = Cmp->getOperand(1);
842a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
843a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // If the phi isn't in the current block, an incoming edge to this block
844a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // doesn't control the destination.
845a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  if (PN->getParent() != BB)
846a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    return false;
847a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
848a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // We can do this simplification if any comparisons fold to true or false.
849a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // See if any do.
8509683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  Value *PredVal = 0;
851a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  bool TrueDirection = false;
852a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8539683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    PredVal = PN->getIncomingValue(i);
8549683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky
8551ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson    Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
856e922c0201916e0b980ab3cfe91e1413e68d55647Owen Anderson                                          RHS, Cmp->getContext());
8579683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    if (!Res) {
8589683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      PredVal = 0;
8599683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky      continue;
8609683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    }
861a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
862a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    // If this folded to a constant expr, we can't do anything.
863a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
864a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner      TrueDirection = ResC->getZExtValue();
865a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner      break;
866a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    }
867a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    // If this folded to undef, just go the false way.
868a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    if (isa<UndefValue>(Res)) {
869a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner      TrueDirection = false;
870a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner      break;
871a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    }
872a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
873a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    // Otherwise, we can't fold this input.
8749683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky    PredVal = 0;
875a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  }
876a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
877a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // If no match, bail out.
8789683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (PredVal == 0)
879a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner    return false;
880a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
881a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // If so, we can actually do this threading.  Merge any common predecessors
882a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // that will act the same.
8839683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
884a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
885a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // Next, get our successor.
886a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
887a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
888fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
889bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  return ThreadEdge(BB, PredBB, SuccBB);
890bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner}
891bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
89278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
89378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
89478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
89578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// NewPred using the entries from OldPred (suitably mapped).
89678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
89778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *OldPred,
89878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *NewPred,
89978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                     DenseMap<Instruction*, Value*> &ValueMap) {
90078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator PNI = PHIBB->begin();
90178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner       PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
90278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Ok, we have a PHI node.  Figure out what the incoming value was for the
90378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // DestBlock.
90478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Value *IV = PN->getIncomingValueForBlock(OldPred);
905bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
90678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap the value if necessary.
90778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
90878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
90978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (I != ValueMap.end())
91078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        IV = I->second;
911bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    }
91278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
91378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PN->addIncoming(IV, NewPred);
914bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  }
915fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
916fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
917fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// ThreadEdge - We have decided that it is safe and profitable to thread an
918fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edge from PredBB to SuccBB across BB.  Transform the IR to reflect this
919fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// change.
920fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpbool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
921bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner                               BasicBlock *SuccBB) {
922eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  // If threading to the same block as we come from, we would infinite loop.
923eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  if (SuccBB == BB) {
92493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  Not threading across BB '" << BB->getName()
92593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - would thread to self!\n");
926eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner    return false;
927eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  }
928eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner
929fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // If threading this would thread across a loop header, don't thread the edge.
930fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // See the comments above FindLoopHeaders for justifications and caveats.
931fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (LoopHeaders.count(BB)) {
93293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  Not threading from '" << PredBB->getName()
93393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' across loop header BB '" << BB->getName()
93493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' to dest BB '" << SuccBB->getName()
93593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - it might create an irreducible loop!\n");
936fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    return false;
937fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
938fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
93978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
94078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (JumpThreadCost > Threshold) {
94178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not threading BB '" << BB->getName()
94278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << JumpThreadCost << "\n");
94378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
94478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
94578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
946a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // And finally, do it!
94793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "  Threading edge from '" << PredBB->getName() << "' to '"
948460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar        << SuccBB->getName() << "' with cost: " << JumpThreadCost
94993b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << ", across block:\n    "
95093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << *BB << "\n");
951a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
952bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We are going to have to map operands from the original BB block to the new
953bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
954bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // account for entry from PredBB.
955bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
956bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
9571d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
9581d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getName()+".thread",
9591d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getParent(), BB);
960bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  NewBB->moveAfter(PredBB);
961bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
962bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BasicBlock::iterator BI = BB->begin();
963bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
964bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
965bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
966bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Clone the non-phi instructions of BB into NewBB, keeping track of the
967bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
968bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; !isa<TerminatorInst>(BI); ++BI) {
9696776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky    Instruction *New = BI->clone();
970460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar    New->setName(BI->getName());
971bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    NewBB->getInstList().push_back(New);
972bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[BI] = New;
973bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
974bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Remap operands to patch up intra-block references.
975bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
976f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
977f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
978f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        if (I != ValueMapping.end())
979f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman          New->setOperand(i, I->second);
980f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      }
981bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
982bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
983bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We didn't copy the terminator from BB over to NewBB, because there is now
984bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // an unconditional jump to SuccBB.  Insert the unconditional jump.
985bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BranchInst::Create(SuccBB, NewBB);
986bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
987bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
988bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // PHI nodes for NewBB now.
98978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
990177480b7ede0441135572d641a2497df25a7d95fChris Lattner
991433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // If there were values defined in BB that are used outside the block, then we
992433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // now have to update all uses of the value to use either the original value,
993433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
994433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
995433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SSAUpdater SSAUpdate;
996433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SmallVector<Use*, 16> UsesToRename;
997433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
998433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // Scan all uses of this instruction to see if it is used outside of its
999433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // block, and if so, record them in UsesToRename.
1000433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1001433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner         ++UI) {
1002433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Instruction *User = cast<Instruction>(*UI);
1003433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1004433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
1005433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          continue;
1006433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      } else if (User->getParent() == BB)
1007433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        continue;
1008433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1009433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      UsesToRename.push_back(&UI.getUse());
1010433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    }
1011433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1012433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // If there are no uses outside the block, we're done with this instruction.
1013433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    if (UsesToRename.empty())
1014433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      continue;
1015433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1016433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1017433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1018433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
1019433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1020433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // with the two values we know.
1021433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.Initialize(I);
1022433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(BB, I);
1023433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1024433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1025433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    while (!UsesToRename.empty())
1026433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1027433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "\n");
1028433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  }
1029433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1030433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1031ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1032bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1033bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // us to simplify any PHI nodes in BB.
1034bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  TerminatorInst *PredTerm = PredBB->getTerminator();
1035bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1036bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (PredTerm->getSuccessor(i) == BB) {
1037bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      BB->removePredecessor(PredBB);
1038bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      PredTerm->setSuccessor(i, NewBB);
1039bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1040ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1041ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // At this point, the IR is fully up to date and consistent.  Do a quick scan
1042ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // over the new instructions and zap any that are constants or dead.  This
1043ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // frequently happens because of phi translation.
1044ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  BI = NewBB->begin();
1045ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1046ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    Instruction *Inst = BI++;
10477b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1048ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      Inst->replaceAllUsesWith(C);
1049ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      Inst->eraseFromParent();
1050ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      continue;
1051ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    }
1052ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1053ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    RecursivelyDeleteTriviallyDeadInstructions(Inst);
1054ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  }
1055fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1056fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Threaded an edge!
1057fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  ++NumThreads;
1058fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return true;
1059177480b7ede0441135572d641a2497df25a7d95fChris Lattner}
106078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
106178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
106278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
106378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// If we can duplicate the contents of BB up into PredBB do so now, this
106478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// improves the odds that the branch will be on an analyzable instruction like
106578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// a compare.
106678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerbool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
106778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                     BasicBlock *PredBB) {
106878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If BB is a loop header, then duplicating this block outside the loop would
106978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // cause us to transform this into an irreducible loop, don't do this.
107078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // See the comments above FindLoopHeaders for justifications and caveats.
107178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (LoopHeaders.count(BB)) {
107278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating loop header '" << BB->getName()
107378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' into predecessor block '" << PredBB->getName()
107478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - it might create an irreducible loop!\n");
107578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
107678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
107778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
107878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
107978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (DuplicationCost > Threshold) {
108078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating BB '" << BB->getName()
108178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << DuplicationCost << "\n");
108278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
108378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
108478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
108578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Okay, we decided to do this!  Clone all the instructions in BB onto the end
108678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // of PredBB.
108778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DEBUG(errs() << "  Duplicating block '" << BB->getName() << "' into end of '"
108878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
108978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << DuplicationCost << " block is:" << *BB << "\n");
109078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
109178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We are going to have to map operands from the original BB block into the
109278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB block.  Evaluate PHI nodes in BB.
109378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
109478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
109578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::iterator BI = BB->begin();
109678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
109778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
109878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
109978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
110078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
110178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Clone the non-phi instructions of BB into PredBB, keeping track of the
110278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
110378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; BI != BB->end(); ++BI) {
110478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Instruction *New = BI->clone();
110578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    New->setName(BI->getName());
110678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PredBB->getInstList().insert(OldPredBranch, New);
110778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[BI] = New;
110878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
110978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap operands to patch up intra-block references.
111078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
111178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
111278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
111378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (I != ValueMapping.end())
111478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          New->setOperand(i, I->second);
111578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
111678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
111778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
111878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Check to see if the targets of the branch had PHI nodes. If so, we need to
111978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // add entries to the PHI nodes for branch from PredBB now.
112078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
112178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
112278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
112378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
112478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
112578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
112678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If there were values defined in BB that are used outside the block, then we
112778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // now have to update all uses of the value to use either the original value,
112878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
112978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
113078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SSAUpdater SSAUpdate;
113178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<Use*, 16> UsesToRename;
113278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
113378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Scan all uses of this instruction to see if it is used outside of its
113478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // block, and if so, record them in UsesToRename.
113578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
113678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner         ++UI) {
113778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Instruction *User = cast<Instruction>(*UI);
113878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
113978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
114078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          continue;
114178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else if (User->getParent() == BB)
114278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        continue;
114378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
114478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      UsesToRename.push_back(&UI.getUse());
114578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
114678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
114778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If there are no uses outside the block, we're done with this instruction.
114878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (UsesToRename.empty())
114978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
115078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
115178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
115278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
115378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
115478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
115578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // with the two values we know.
115678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.Initialize(I);
115778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(BB, I);
115878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
115978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
116078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    while (!UsesToRename.empty())
116178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
116278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "\n");
116378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
116478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
116578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
116678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // that we nuked.
116778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BB->removePredecessor(PredBB);
116878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
116978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Remove the unconditional branch at the end of the PredBB block.
117078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  OldPredBranch->eraseFromParent();
117178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
117278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  ++NumDupes;
117378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return true;
117478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
117578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
117678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1177