JumpThreading.cpp revision 6f84a5feee5c7322a5145992bd4704225987909c
18383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
28383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
38383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//                     The LLVM Compiler Infrastructure
48383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
58383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// This file is distributed under the University of Illinois Open Source
68383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// License. See LICENSE.TXT for details.
78383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
88383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
98383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
10177480b7ede0441135572d641a2497df25a7d95fChris Lattner// This file implements the Jump Threading pass.
118383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
128383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
138383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
148383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#define DEBUG_TYPE "jump-threading"
158383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Transforms/Scalar.h"
16177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/IntrinsicInst.h"
171ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson#include "llvm/LLVMContext.h"
188383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Pass.h"
199819ef7742cc2e3af92a0b760fa33e30218ff7bbChris Lattner#include "llvm/Analysis/InstructionSimplify.h"
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);
755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    BasicBlock *SuccBB);
7778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
7878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                          BasicBlock *PredBB);
795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    typedef SmallVectorImpl<std::pair<ConstantInt*,
815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      BasicBlock*> > PredValueInfo;
825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                         PredValueInfo &Result);
855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
88421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
906bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
91d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner    bool ProcessJumpOnPHI(PHINode *PN);
9269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
9369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
948383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  };
958383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
968383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
97844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanchar JumpThreading::ID = 0;
98844731a7f1909f55935e3514c9e713a62d67662eDan Gohmanstatic RegisterPass<JumpThreading>
99844731a7f1909f55935e3514c9e713a62d67662eDan GohmanX("jump-threading", "Jump Threading");
100844731a7f1909f55935e3514c9e713a62d67662eDan Gohman
1018383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// Public interface to the Jump Threading pass
1028383a7b7a6acdae478d4b4c2520915153b73f676Chris LattnerFunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
1038383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
1048383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// runOnFunction - Top level algorithm.
1058383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner///
1068383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerbool JumpThreading::runOnFunction(Function &F) {
10793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
10802a436c48ecff9e34d50ce0a2f861e5acdd9bf3fDan Gohman  TD = getAnalysisIfAvailable<TargetData>();
109bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
110fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindLoopHeaders(F);
111fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
112bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  bool AnotherIteration = true, EverChanged = false;
113bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  while (AnotherIteration) {
114bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = false;
115bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    bool Changed = false;
116421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
117421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      BasicBlock *BB = I;
118f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      // Thread all of the branches we can over this block.
119421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      while (ProcessBlock(BB))
120bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Changed = true;
121421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
122421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      ++I;
123421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
124421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // If the block is trivially dead, zap it.  This eliminates the successor
125421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // edges which simplifies the CFG.
126421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      if (pred_begin(BB) == pred_end(BB) &&
12720fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner          BB != &BB->getParent()->getEntryBlock()) {
12893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        DEBUG(errs() << "  JT: Deleting dead block '" << BB->getName()
12978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              << "' with terminator: " << *BB->getTerminator() << '\n');
130fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.erase(BB);
131421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        DeleteDeadBlock(BB);
132421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        Changed = true;
133f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
134f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // Can't thread an unconditional jump, but if the block is "almost
135f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // empty", we can replace uses of it with uses of the successor and make
136f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        // this dead.
137f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        if (BI->isUnconditional() &&
138f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            BB != &BB->getParent()->getEntryBlock()) {
139f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          BasicBlock::iterator BBI = BB->getFirstNonPHI();
140f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          // Ignore dbg intrinsics.
141f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          while (isa<DbgInfoIntrinsic>(BBI))
142f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            ++BBI;
143f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          // If the terminator is the only non-phi instruction, try to nuke it.
144f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          if (BBI->isTerminator()) {
1456f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
1466f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // block, we have to make sure it isn't in the LoopHeaders set.  We
1476f84a5feee5c7322a5145992bd4704225987909cChris Lattner            // reinsert afterward in the rare case when the block isn't deleted.
1486f84a5feee5c7322a5145992bd4704225987909cChris Lattner            bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
149f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
150f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner            if (TryToSimplifyUncondBranchFromEmptyBlock(BB))
151f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner              Changed = true;
1526f84a5feee5c7322a5145992bd4704225987909cChris Lattner            else if (ErasedFromLoopHeaders)
153f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner              LoopHeaders.insert(BB);
154f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner          }
155f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner        }
156421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      }
157421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
158bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    AnotherIteration = Changed;
159bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EverChanged |= Changed;
160bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
161fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
162fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  LoopHeaders.clear();
163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  return EverChanged;
1648383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner}
165177480b7ede0441135572d641a2497df25a7d95fChris Lattner
16678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
16778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// thread across it.
16878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
16978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  /// Ignore PHI nodes, these will be flattened when duplication happens.
17078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::const_iterator I = BB->getFirstNonPHI();
17178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Sum up the cost of each instruction until we get to the terminator.  Don't
17378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // include the terminator because the copy won't include it.
17478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned Size = 0;
17578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; !isa<TerminatorInst>(I); ++I) {
17678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Debugger intrinsics don't incur code size.
17778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<DbgInfoIntrinsic>(I)) continue;
17878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If this is a pointer->pointer bitcast, it is free.
18078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
18178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
18278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
18378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // All other instructions count for at least one unit.
18478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ++Size;
18578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
18678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Calls are more expensive.  If they are non-intrinsic calls, we model them
18778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 4.  If they are a non-vector intrinsic, we model them
18878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // as having cost of 2 total, and if they are a vector intrinsic, we model
18978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // them as having cost 1.
19078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (const CallInst *CI = dyn_cast<CallInst>(I)) {
19178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (!isa<IntrinsicInst>(CI))
19278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 3;
19378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      else if (!isa<VectorType>(CI->getType()))
19478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Size += 1;
19578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
19678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
19778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
19878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Threading through a switch statement is particularly profitable.  If this
19978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // block ends in a switch, decrease its cost to make it more likely to happen.
20078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (isa<SwitchInst>(I))
20178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Size = Size > 6 ? Size-6 : 0;
20278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
20378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return Size;
20478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
20578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
20678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
207c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner//===----------------------------------------------------------------------===//
208c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
209fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
210fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// delete the From instruction.  In addition to a basic RAUW, this does a
211fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// recursive simplification of the newly formed instructions.  This catches
212fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// things where one simplification exposes other opportunities.  This only
213fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// simplifies and deletes scalar operations, it does not change the CFG.
214fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner///
215fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattnerstatic void ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
216fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner                                      const TargetData *TD) {
217fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
218fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
219fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // FromHandle - This keeps a weakvh on the from value so that we can know if
220fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // it gets deleted out from under us in a recursive simplification.
221fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  WeakVH FromHandle(From);
222fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
223fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  while (!From->use_empty()) {
224fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // Update the instruction to use the new value.
225fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    Use &U = From->use_begin().getUse();
226fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    Instruction *User = cast<Instruction>(U.getUser());
227fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    U = To;
228fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
229fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // See if we can simplify it.
230fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    if (Value *V = SimplifyInstruction(User, TD)) {
231fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // Recursively simplify this.
232fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      ReplaceAndSimplifyAllUses(User, V, TD);
233fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
234fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // If the recursive simplification ended up revisiting and deleting 'From'
235fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      // then we're done.
236fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (FromHandle == 0)
237fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        return;
238fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    }
239fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  }
240fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  From->eraseFromParent();
241fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner}
242fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
243c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
244c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
245c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// method is called when we're about to delete Pred as a predecessor of BB.  If
246c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
247c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///
248c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
249c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// nodes that collapse into identity values.  For example, if we have:
250c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///   x = phi(1, 0, 0, 0)
251c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///   y = and x, z
252c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner///
253c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// .. and delete the predecessor corresponding to the '1', this will attempt to
254c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner/// recursively fold the and to 0.
255c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattnerstatic void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
256c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                                         TargetData *TD) {
257c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // This only adjusts blocks with PHI nodes.
258c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  if (!isa<PHINode>(BB->begin()))
259c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    return;
260c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
261c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
262c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // them down.  This will leave us with single entry phi nodes and other phis
263c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // that can be removed.
264c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  BB->removePredecessor(Pred, true);
265c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
266c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  WeakVH PhiIt = &BB->front();
267c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
268c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
269c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
270c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    Value *PNV = PN->hasConstantValue();
271c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    if (PNV == 0) continue;
272c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
273fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // If we're able to simplify the phi to a single value, substitute the new
274fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    // value into all of its uses.
275c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    assert(PNV != PN && "hasConstantValue broken");
276c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
277fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    ReplaceAndSimplifyAllUses(PN, PNV, TD);
278c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
279c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // If recursive simplification ended up deleting the next PHI node we would
280c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // iterate to, then our iterator is invalid, restart scanning from the top
281c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    // of the block.
282c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    if (PhiIt == 0) PhiIt = &BB->front();
283c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  }
284c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner}
285c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
286c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner//===----------------------------------------------------------------------===//
287c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
28878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
289fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// FindLoopHeaders - We do not want jump threading to turn proper loop
290fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// structures into irreducible loops.  Doing this breaks up the loop nesting
291fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// hierarchy and pessimizes later transformations.  To prevent this from
292fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// happening, we first have to find the loop headers.  Here we approximate this
293fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// by finding targets of backedges in the CFG.
294fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
295fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// Note that there definitely are cases when we want to allow threading of
296fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// edges across a loop header.  For example, threading a jump from outside the
297fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// loop (the preheader) to an exit block of the loop is definitely profitable.
298fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// It is also almost always profitable to thread backedges from within the loop
299fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// to exit blocks, and is often profitable to thread backedges to other blocks
300fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// within the loop (forming a nested loop).  This simple analysis is not rich
301fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// enough to track all of these properties and keep it up-to-date as the CFG
302fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// mutates, so we don't allow any of these transformations.
303fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump///
304fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpvoid JumpThreading::FindLoopHeaders(Function &F) {
305fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
306fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  FindFunctionBackedges(F, Edges);
307fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
308fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
309fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
310fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
311fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
3125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
3135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// if we can infer that the value is a known ConstantInt in any of our
314e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner/// predecessors.  If so, return the known list of value and pred BB in the
3155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// result vector.  If a value is known to be undef, it is returned as null.
3165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
3175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// The BB basic block is known to start with a PHI node.
3185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
3195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// This returns true if there were any known values.
3205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
321785672534d32d196d04ad022c111fde3864e0d28Chris Lattner///
3225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// TODO: Per PR2563, we could infer value range information about a predecessor
3235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// based on its terminator.
3245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::
3255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
3265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
3275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a constantint, then it is known in all predecessors.
3295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
3305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *CI = dyn_cast<ConstantInt>(V);
3315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    Result.resize(TheFirstPHI->getNumIncomingValues());
3325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = Result.size(); i != e; ++i)
3335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
3345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return true;
3355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If V is a non-instruction value, or an instruction in a different block,
3385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // then it can't be derived from a PHI.
3395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Instruction *I = dyn_cast<Instruction>(V);
3405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (I == 0 || I->getParent() != BB)
3415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
3425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// If I is a PHI node, then we know the incoming values for any constants.
3445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PHINode *PN = dyn_cast<PHINode>(I)) {
3455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Value *InVal = PN->getIncomingValue(i);
3475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
3485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
3495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
3505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
3515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return !Result.empty();
3535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
3565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle some boolean conditions.
3585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (I->getType()->getPrimitiveSizeInBits() == 1) {
3595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X | true -> true
3605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // X & false -> false
3615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (I->getOpcode() == Instruction::Or ||
3625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        I->getOpcode() == Instruction::And) {
3635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
3645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
3655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (LHSVals.empty() && RHSVals.empty())
3675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return false;
3685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ConstantInt *InterestingVal;
3705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (I->getOpcode() == Instruction::Or)
3715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getTrue(I->getContext());
3725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      else
3735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        InterestingVal = ConstantInt::getFalse(I->getContext());
3745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Scan for the sentinel.
3765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
3775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
3785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(LHSVals[i]);
3795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
3805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
3815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(RHSVals[i]);
3825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
3835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
384785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
3855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // TODO: Should handle the NOT form of XOR.
3865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
38812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
3895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle compare with phi operand, where the PHI is defined in this block.
3905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
3925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PN && PN->getParent() == BB) {
3935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // We can do this simplification if any comparisons fold to true or false.
3945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // See if any do.
3955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        BasicBlock *PredBB = PN->getIncomingBlock(i);
3975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *LHS = PN->getIncomingValue(i);
3985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
3995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4009dbb42944c4d7caddab21016b24cca31019a3fafChris Lattner        Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS);
4015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (Res == 0) continue;
4025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (isa<UndefValue>(Res))
4045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
4055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
4065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Result.push_back(std::make_pair(CI, PredBB));
4075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
4085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return !Result.empty();
4105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
4115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // TODO: We could also recurse to see if we can determine constants another
4135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // way.
4145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
4165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
4175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4196bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner
420e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
421e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// in an undefined jump, decide which block is best to revector to.
422e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
423e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// Since we can pick an arbitrary destination, we pick the successor with the
424e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner/// fewest predecessors.  This should reduce the in-degree of the others.
425e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner///
426e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattnerstatic unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
427e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  TerminatorInst *BBTerm = BB->getTerminator();
428e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinSucc = 0;
429e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
430e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // Compute the successor with the minimum number of predecessors.
431e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
432e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
433e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TestBB = BBTerm->getSuccessor(i);
434e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
435e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (NumPreds < MinNumPreds)
436e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      MinSucc = i;
437e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
438e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
439e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  return MinSucc;
440e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner}
441e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
442c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner/// ProcessBlock - If there are any predecessors whose control can be threaded
443177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// through to a successor, transform them now.
444c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattnerbool JumpThreading::ProcessBlock(BasicBlock *BB) {
44569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If this block has a single predecessor, and if that pred has a single
44669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // successor, merge the blocks.  This encourages recursive jump threading
44769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // because now the condition in this block can be threaded through
44869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors of our predecessor block.
4495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
450f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
451f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner        SinglePred != BB) {
452fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // If SinglePred was a loop header, BB becomes one.
453fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      if (LoopHeaders.erase(SinglePred))
454fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump        LoopHeaders.insert(BB);
455fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
4563d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Remember if SinglePred was the entry block of the function.  If so, we
4573d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // will need to move BB back to the entry position.
4583d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
45969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      MergeBasicBlockIntoOnlyPred(BB);
4603d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner
4613d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      if (isEntry && BB != &BB->getParent()->getEntryBlock())
4623d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner        BB->moveBefore(&BB->getParent()->getEntryBlock());
46369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
46469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
4655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
4665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look to see if the terminator is a branch of switch, if not we can't thread
4685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // it.
469177480b7ede0441135572d641a2497df25a7d95fChris Lattner  Value *Condition;
470bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
471bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Can't thread an unconditional jump.
472bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (BI->isUnconditional()) return false;
473177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = BI->getCondition();
474bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
475177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Condition = SI->getCondition();
476177480b7ede0441135572d641a2497df25a7d95fChris Lattner  else
477177480b7ede0441135572d641a2497df25a7d95fChris Lattner    return false; // Must be an invoke.
478bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
479bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // If the terminator of this block is branching on a constant, simplify the
480037c781de797242ba652db775f1f2c5d2d4eb19bChris Lattner  // terminator to an unconditional branch.  This can occur due to threading in
481bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // other blocks.
482bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  if (isa<ConstantInt>(Condition)) {
48393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
48478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *BB->getTerminator() << '\n');
485bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ++NumFolds;
486bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ConstantFoldTerminator(BB);
487bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    return true;
488bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
489bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
490421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the terminator is branching on an undef, we can pick any of the
491e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
492421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (isa<UndefValue>(Condition)) {
493e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
494421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
495421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Fold the branch/switch.
496e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    TerminatorInst *BBTerm = BB->getTerminator();
497421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
498e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (i == BestSucc) continue;
499c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD);
500421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
501421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
50293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
50378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding undef terminator: " << *BBTerm << '\n');
504e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
505421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BBTerm->eraseFromParent();
506421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
507421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
508421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
509421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Instruction *CondInst = dyn_cast<Instruction>(Condition);
510421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
511421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the condition is an instruction defined in another block, see if a
512421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // predecessor has the same condition:
513421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBX, BBY
514421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //  BBX:
515421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  //     br COND, BBZ, BBW
516421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (!Condition->hasOneUse() && // Multiple uses.
517421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
518421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
519421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (isa<BranchInst>(BB->getTerminator())) {
520421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      for (; PI != E; ++PI)
521421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
522421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner          if (PBI->isConditional() && PBI->getCondition() == Condition &&
523421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner              ProcessBranchOnDuplicateCond(*PI, BB))
524421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner            return true;
5253cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    } else {
5263cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
5273cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      for (; PI != E; ++PI)
5283cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
5293cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          if (PSI->getCondition() == Condition &&
5303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner              ProcessSwitchOnDuplicateCond(*PI, BB))
5313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner            return true;
532421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
533421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
534421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
535421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // All the rest of our checks depend on the condition being an instruction.
536421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (CondInst == 0)
537421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return false;
538421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
539177480b7ede0441135572d641a2497df25a7d95fChris Lattner  // See if this is a phi node in the current block.
540421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(CondInst))
541421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (PN->getParent() == BB)
542421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      return ProcessJumpOnPHI(PN);
543177480b7ede0441135572d641a2497df25a7d95fChris Lattner
5449683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
5455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!isa<PHINode>(CondCmp->getOperand(0)) ||
5465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
5475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If we have a comparison, loop over the predecessors to see if there is
5485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // a condition with a lexically identical value.
5495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      pred_iterator PI = pred_begin(BB), E = pred_end(BB);
5505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (; PI != E; ++PI)
5515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PBI->isConditional() && *PI != BB) {
5535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
5545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              if (CI->getOperand(0) == CondCmp->getOperand(0) &&
5555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getOperand(1) == CondCmp->getOperand(1) &&
5565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  CI->getPredicate() == CondCmp->getPredicate()) {
5575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                // TODO: Could handle things like (x != 4) --> (x == 17)
5585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                if (ProcessBranchOnDuplicateCond(*PI, BB))
5595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  return true;
5605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              }
56179c740ff479dde322aceafe15887b162c19ea195Chris Lattner            }
56279c740ff479dde322aceafe15887b162c19ea195Chris Lattner          }
5635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
5649683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky  }
56569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
56669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Check for some cases that are worth simplifying.  Right now we want to look
56769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // for loads that are used by a switch or by the condition for the branch.  If
56869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we see one, check to see if it's partially redundant.  If so, insert a PHI
56969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // which can then be used to thread the values.
57069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //
57169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This is particularly important because reg2mem inserts loads and stores all
57269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // over the place, and this blocks jump threading if we don't zap them.
573421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  Value *SimplifyValue = CondInst;
57469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
57569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (isa<Constant>(CondCmp->getOperand(1)))
57669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SimplifyValue = CondCmp->getOperand(0);
57769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
57869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
57969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (SimplifyPartiallyRedundantLoad(LI))
58069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return true;
58169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
5825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Handle a variety of cases where we are branching on something derived from
5845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a PHI node in the current block.  If we can prove that any predecessors
5855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // compute a predictable value based on a PHI node, thread those predecessors.
5865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  //
5875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // We only bother doing this if the current block has a PHI node and if the
5885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // conditional instruction lives in the current block.  If either condition
589e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // fails, this won't be a computable value anyway.
5905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
5915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (ProcessThreadableEdges(CondInst, BB))
5925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return true;
5935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
59569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
59669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // "(X == 4)" thread through this block.
597a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
598d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  return false;
599d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner}
600d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner
601421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
602421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// block that jump on exactly the same condition.  This means that we almost
603421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// always know the direction of the edge in the DESTBB:
604421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  PREDBB:
605421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, DESTBB, BBY
606421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///  DESTBB:
607421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///     br COND, BBZ, BBW
608421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner///
609421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// If DESTBB has multiple predecessors, we can't just constant fold the branch
610421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner/// in DESTBB, we have to thread over it.
611421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattnerbool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
612421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                                 BasicBlock *BB) {
613421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
614421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
615421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If both successors of PredBB go to DESTBB, we don't know anything.  We can
616421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // fold the branch to an unconditional one, which allows other recursive
617421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // simplifications.
618421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  bool BranchDir;
619421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (PredBI->getSuccessor(1) != BB)
620421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = true;
621421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else if (PredBI->getSuccessor(0) != BB)
622421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    BranchDir = false;
623421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  else {
62493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << PredBB->getName()
62578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' folding terminator: " << *PredBB->getTerminator() << '\n');
626421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
627421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(PredBB);
628421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
629421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
630421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
631421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
632421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
633421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the dest block has one predecessor, just fix the branch condition to a
634421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // constant and fold it.
635421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (BB->getSinglePredecessor()) {
63693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  In block '" << BB->getName()
63793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' folding condition to '" << BranchDir << "': "
63878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << *BB->getTerminator() << '\n');
639421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ++NumFolds;
6405a06cf644f35b873686c8694968192ad3385e36aChris Lattner    Value *OldCond = DestBI->getCondition();
6411d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson    DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
6421d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                          BranchDir));
643421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ConstantFoldTerminator(BB);
6445a06cf644f35b873686c8694968192ad3385e36aChris Lattner    RecursivelyDeleteTriviallyDeadInstructions(OldCond);
645421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    return true;
646421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
647bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
648421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
649421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Next, figure out which successor we are threading to.
650421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
651421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 2> Preds;
6535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Preds.push_back(PredBB);
6545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
655fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Ok, try to thread it!
6565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, Preds, SuccBB);
657421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
658421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6593cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
6603cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// block that switch on exactly the same condition.  This means that we almost
6613cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// always know the direction of the edge in the DESTBB:
6623cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  PREDBB:
6633cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... DESTBB, BBY ... ]
6643cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///  DESTBB:
6653cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///     switch COND [... BBZ, BBW ]
6663cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner///
6673cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// Optimizing switches like this is very important, because simplifycfg builds
6683cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// switches out of repeated 'if' conditions.
6693cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattnerbool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
6703cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                                 BasicBlock *DestBB) {
6712c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  // Can't thread edge to self.
6722c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner  if (PredBB == DestBB)
6732c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner    return false;
6742c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner
6753cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
6763cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
6773cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6783cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // There are a variety of optimizations that we can potentially do on these
6793cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // blocks: we order them from most to least preferable.
6803cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6813cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
6823cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // directly to their destination.  This does not introduce *any* code size
6836b233395025069f63156ea2b524cdb708a14731fDale Johannesen  // growth.  Skip debug info first.
6846b233395025069f63156ea2b524cdb708a14731fDale Johannesen  BasicBlock::iterator BBI = DestBB->begin();
6856b233395025069f63156ea2b524cdb708a14731fDale Johannesen  while (isa<DbgInfoIntrinsic>(BBI))
6866b233395025069f63156ea2b524cdb708a14731fDale Johannesen    BBI++;
6873cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6883cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // FIXME: Thread if it just contains a PHI.
6896b233395025069f63156ea2b524cdb708a14731fDale Johannesen  if (isa<SwitchInst>(BBI)) {
6903cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    bool MadeChange = false;
6913cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    // Ignore the default edge for now.
6923cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
6933cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      ConstantInt *DestVal = DestSI->getCaseValue(i);
6943cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      BasicBlock *DestSucc = DestSI->getSuccessor(i);
6953cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6963cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'.  See if
6973cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // PredSI has an explicit case for it.  If so, forward.  If it is covered
6983cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // by the default case, we can't update PredSI.
6993cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      unsigned PredCase = PredSI->findCaseValue(DestVal);
7003cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredCase == 0) continue;
7013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If PredSI doesn't go to DestBB on this value, then it won't reach the
7033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // case on this condition.
7043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (PredSI->getSuccessor(PredCase) != DestBB &&
7053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner          DestSI->getSuccessor(i) != DestBB)
7063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        continue;
7073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7083cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // Otherwise, we're safe to make the change.  Make sure that the edge from
7093cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // DestSI to DestSucc is not critical and has no PHI nodes.
71093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "FORWARDING EDGE " << *DestVal << "   FROM: " << *PredSI);
71193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      DEBUG(errs() << "THROUGH: " << *DestSI);
7123cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7133cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If the destination has PHI nodes, just split the edge for updating
7143cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // simplicity.
7153cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
7163cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        SplitCriticalEdge(DestSI, i, this);
7173cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        DestSucc = DestSI->getSuccessor(i);
7183cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      }
7193cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      FoldSingleEntryPHINodes(DestSucc);
7203cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      PredSI->setSuccessor(PredCase, DestSucc);
7213cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      MadeChange = true;
7223cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    }
7233cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7243cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (MadeChange)
7253cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      return true;
7263cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  }
7273cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7283cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  return false;
7293cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner}
7303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
73269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
73369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// load instruction, eliminate it by replacing it with a PHI node.  This is an
73469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// important optimization that encourages jump threading, and needs to be run
73569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner/// interlaced with other jump threading tasks.
73669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattnerbool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
73769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Don't hack volatile loads.
73869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LI->isVolatile()) return false;
73969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the load is defined in a block with exactly one predecessor, it can't be
74169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // partially redundant.
74269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *LoadBB = LI->getParent();
74369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (LoadBB->getSinglePredecessor())
74469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
74569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Value *LoadedPtr = LI->getOperand(0);
74769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
74869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded operand is defined in the LoadBB, it can't be available.
74969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // FIXME: Could do PHI translation, that would be fun :)
75069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
75169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (PtrOp->getParent() == LoadBB)
75269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return false;
75369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
75469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Scan a few instructions up from the load, to see if it is obviously live at
75569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // the entry to its block.
75669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock::iterator BBIt = LI;
75769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
75852c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner  if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
75952c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner                                                     BBIt, 6)) {
76069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If the value if the load is locally available within the block, just use
76169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // it.  This frequently occurs for reg2mem'd allocas.
76269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
7632a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner
7642a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // If the returned value is the load itself, replace with an undef. This can
7652a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    // only happen in dead loops.
7669e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson    if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
76769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->replaceAllUsesWith(AvailableVal);
76869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    LI->eraseFromParent();
76969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return true;
77069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
77169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Otherwise, if we scanned the whole block and got to the top of the block,
77369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // we know the block is locally transparent to the load.  If not, something
77469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // might clobber its value.
77569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (BBIt != LoadBB->begin())
77669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    return false;
77769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
77969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SmallPtrSet<BasicBlock*, 8> PredsScanned;
78069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
78169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  AvailablePredsTy AvailablePreds;
78269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *OneUnavailablePred = 0;
78369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
78469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If we got here, the loaded value is transparent through to the start of the
78569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // block.  Check to see if it is available in any of the predecessor blocks.
78669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
78769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       PI != PE; ++PI) {
78869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BasicBlock *PredBB = *PI;
78969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
79069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If we already scanned this predecessor, skip it.
79169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredsScanned.insert(PredBB))
79269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
79369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
79469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Scan the predecessor to see if the value is available in the pred.
79569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    BBIt = PredBB->end();
79652c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
79769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (!PredAvailable) {
79869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred = PredBB;
79969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      continue;
80069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
80169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
80269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // If so, this load is partially redundant.  Remember this info so that we
80369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // can create a PHI node.
80469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
80569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
80669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
80769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the loaded value isn't available in any predecessor, it isn't partially
80869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // redundant.
80969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (AvailablePreds.empty()) return false;
81069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Okay, the loaded value is available in at least one (and maybe all!)
81269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessors.  If the value is unavailable in more than one unique
81369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // predecessor, we want to insert a merge block for those common predecessors.
81469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // This ensures that we only have to insert one reload, thus not increasing
81569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // code size.
81669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  BasicBlock *UnavailablePred = 0;
81769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If there is exactly one predecessor where the value is unavailable, the
81969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // already computed 'OneUnavailablePred' block is it.  If it ends in an
82069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // unconditional branch, we know that it isn't a critical edge.
82169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (PredsScanned.size() == AvailablePreds.size()+1 &&
82269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
82369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred = OneUnavailablePred;
82469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  } else if (PredsScanned.size() != AvailablePreds.size()) {
82569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Otherwise, we had multiple unavailable predecessors or we had a critical
82669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // edge from the one.
82769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<BasicBlock*, 8> PredsToSplit;
82869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
82969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
83169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      AvailablePredSet.insert(AvailablePreds[i].first);
83269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Add all the unavailable predecessors to the PredsToSplit list.
83469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
83569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner         PI != PE; ++PI)
83669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!AvailablePredSet.count(*PI))
83769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        PredsToSplit.push_back(*PI);
83869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
83969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Split them out to their own block.
84069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    UnavailablePred =
84169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
84269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                             "thread-split", this);
84369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
84469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
84569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the value isn't available in all predecessors, then there will be
84669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // exactly one where it isn't available.  Insert a load on that edge and add
84769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // it to the AvailablePreds list.
84869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (UnavailablePred) {
84969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
85069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Can't handle critical edge here!");
85169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
85269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 UnavailablePred->getTerminator());
85369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
85469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
85569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Now we know that each predecessor of this block has a value in
85769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // AvailablePreds, sort them for efficient access as we're walking the preds.
858a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner  array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
85969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Create a PHI node at the start of the block for the PRE'd load value.
86169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
86269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  PN->takeName(LI);
86369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
86469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // Insert new entries into the PHI for each predecessor.  A single block may
86569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // have multiple entries here.
86669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
86769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner       ++PI) {
86869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    AvailablePredsTy::iterator I =
86969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
87069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                       std::make_pair(*PI, (Value*)0));
87169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
87269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    assert(I != AvailablePreds.end() && I->first == *PI &&
87369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner           "Didn't find entry for predecessor!");
87469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
87569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    PN->addIncoming(I->second, I->first);
87669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
87769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
87869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  //cerr << "PRE: " << *LI << *PN << "\n";
87969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
88069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->replaceAllUsesWith(PN);
88169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  LI->eraseFromParent();
88269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
88369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  return true;
88469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner}
88569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
8865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// FindMostPopularDest - The specified list contains multiple possible
8875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// threadable destinations.  Pick the one that occurs the most frequently in
8885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the list.
8895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerstatic BasicBlock *
8905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerFindMostPopularDest(BasicBlock *BB,
8915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    const SmallVectorImpl<std::pair<BasicBlock*,
8925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  BasicBlock*> > &PredToDestList) {
8935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredToDestList.empty());
894785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine popularity.  If there are multiple possible destinations, we
8965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // explicitly choose to ignore 'undef' destinations.  We prefer to thread
8975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // blocks with known and real destinations to threading undef.  We'll handle
8985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // them later if interesting.
8995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned> DestPopularity;
9005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
9015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second)
9025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestPopularity[PredToDestList[i].second]++;
903785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
9045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Find the most popular dest.
9055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
9065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = DPI->first;
9075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned Popularity = DPI->second;
9085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 4> SamePopularity;
90978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
9105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (++DPI; DPI != DestPopularity.end(); ++DPI) {
9115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the popularity of this entry isn't higher than the popularity we've
9125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // seen so far, ignore it.
9135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (DPI->second < Popularity)
9145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ; // ignore.
9155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (DPI->second == Popularity) {
9165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is the same as what we've seen so far, keep track of it.
9175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.push_back(DPI->first);
9185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    } else {
9195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If it is more popular, remember it.
9205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SamePopularity.clear();
9215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = DPI->first;
9225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Popularity = DPI->second;
9235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
92478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
9255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, now we know the most popular destination.  If there is more than
9275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // destination, we need to determine one.  This is arbitrary, but we need
9285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to make a deterministic decision.  Pick the first one that appears in the
9295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // successor list.
9305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!SamePopularity.empty()) {
9315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SamePopularity.push_back(MostPopularDest);
9325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    TerminatorInst *TI = BB->getTerminator();
9335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 0; ; ++i) {
9345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
93512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (std::find(SamePopularity.begin(), SamePopularity.end(),
9375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    TI->getSuccessor(i)) == SamePopularity.end())
9385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        continue;
9395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      MostPopularDest = TI->getSuccessor(i);
94112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      break;
94212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
94312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
94412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Okay, we have finally picked the most popular destination.
9465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return MostPopularDest;
9475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
9485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
9505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                           BasicBlock *BB) {
9515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If threading this would thread across a loop header, don't even try to
9525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // thread the edge.
9535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (LoopHeaders.count(BB))
95412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
95512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
9575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
95812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
9595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(!PredValues.empty() &&
9605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         "ComputeValueKnownInPredecessors returned true with no values");
9615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DEBUG(errs() << "IN BB: " << *BB;
9635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << "  BB '" << BB->getName() << "': FOUND condition = ";
9655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (PredValues[i].first)
9665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << *PredValues[i].first;
9675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          else
9685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            errs() << "UNDEF";
9695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          errs() << " for pred '" << PredValues[i].second->getName()
9705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << "'.\n";
9715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        });
97212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Decide what we want to thread through.  Convert our list of known values to
9745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // a list of known destinations for each pred.  This also discards duplicate
9755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors and keeps track of the undefined inputs (which are represented
976e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner  // as a null dest in the PredToDestList).
9775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallPtrSet<BasicBlock*, 16> SeenPreds;
9785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
9795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *OnlyDest = 0;
9815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
9825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
9845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *Pred = PredValues[i].second;
9855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (!SeenPreds.insert(Pred))
9865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      continue;  // Duplicate predecessor entry.
98712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If the predecessor ends with an indirect goto, we can't change its
9895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // destination.
9905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (isa<IndirectBrInst>(Pred->getTerminator()))
99112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      continue;
99212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ConstantInt *Val = PredValues[i].first;
9945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *DestBB;
9965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (Val == 0)      // Undef.
9975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = 0;
9985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
9995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = BI->getSuccessor(Val->isZero());
10005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else {
10015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
10025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DestBB = SI->getSuccessor(SI->findCaseValue(Val));
100312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    }
10045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // If we have exactly one destination, remember it for efficiency below.
10065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (i == 0)
10075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = DestBB;
10085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    else if (OnlyDest != DestBB)
10095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      OnlyDest = MultipleDestSentinel;
101012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredToDestList.push_back(std::make_pair(Pred, DestBB));
101212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  }
101312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If all edges were unthreadable, we fail.
10155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredToDestList.empty())
101612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    return false;
101712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Determine which is the most common successor.  If we have many inputs and
10195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // this block is a switch, we want to start by threading the batch that goes
10205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // to the most popular destination first.  If we only know about one
10215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threadable destination (the common case) we can avoid this.
10225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *MostPopularDest = OnlyDest;
102312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == MultipleDestSentinel)
10255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = FindMostPopularDest(BB, PredToDestList);
102612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Now that we know what the most popular destination is, factor all
10285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // predecessors that will jump to it into a single predecessor.
10295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SmallVector<BasicBlock*, 16> PredsToFactor;
10305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
10315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (PredToDestList[i].second == MostPopularDest) {
10325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      BasicBlock *Pred = PredToDestList[i].first;
10335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // This predecessor may be a switch or something else that has multiple
10355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // edges to the block.  Factor each of these edges by listing them
10365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // according to # occurrences in PredsToFactor.
10375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      TerminatorInst *PredTI = Pred->getTerminator();
10385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
10395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (PredTI->getSuccessor(i) == BB)
10405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          PredsToFactor.push_back(Pred);
10415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
10425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If the threadable edges are branching on an undefined value, we get to pick
10445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // the destination that these predecessors should get to.
10455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (MostPopularDest == 0)
10465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    MostPopularDest = BB->getTerminator()->
10475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            getSuccessor(GetBestDestForJumpOnUndef(BB));
10485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
104912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  // Ok, try to thread it!
10505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return ThreadEdge(BB, PredsToFactor, MostPopularDest);
10515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
10525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
10545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the current block.  See if there are any simplifications we can do based on
10555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// inputs to the phi node.
10565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner///
10575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
10585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *BB = PN->getParent();
10595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // If any of the predecessor blocks end in an unconditional branch, we can
10615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // *duplicate* the jump into that block in order to further encourage jump
10625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // threading and to eliminate cases where we have branch on a phi of an icmp
10635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // (branch on icmp is much better).
10645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // We don't want to do this tranformation for switches, because we don't
10665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // really want to duplicate a switch.
10675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (isa<SwitchInst>(BB->getTerminator()))
10685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return false;
10695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Look for unconditional branch predecessors.
10715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    BasicBlock *PredBB = PN->getIncomingBlock(i);
10735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
10745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (PredBr->isUnconditional() &&
10755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          // Try to duplicate BB into PredBB.
10765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
10775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        return true;
10785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
10795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  return false;
108112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel}
108212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
108312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
108478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
108578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
108678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// NewPred using the entries from OldPred (suitably mapped).
108778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerstatic void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
108878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *OldPred,
108978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                            BasicBlock *NewPred,
109078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                     DenseMap<Instruction*, Value*> &ValueMap) {
109178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator PNI = PHIBB->begin();
109278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner       PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
109378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Ok, we have a PHI node.  Figure out what the incoming value was for the
109478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // DestBlock.
109578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Value *IV = PN->getIncomingValueForBlock(OldPred);
1096bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner
109778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap the value if necessary.
109878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
109978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
110078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (I != ValueMap.end())
110178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        IV = I->second;
1102bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner    }
110378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
110478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PN->addIncoming(IV, NewPred);
1105bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  }
1106fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
1107fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
11085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ThreadEdge - We have decided that it is safe and profitable to factor the
11095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
11105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// across BB.  Transform the IR to reflect this change.
11115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerbool JumpThreading::ThreadEdge(BasicBlock *BB,
11125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                               const SmallVectorImpl<BasicBlock*> &PredBBs,
1113bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner                               BasicBlock *SuccBB) {
1114eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  // If threading to the same block as we come from, we would infinite loop.
1115eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  if (SuccBB == BB) {
111693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    DEBUG(errs() << "  Not threading across BB '" << BB->getName()
111793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - would thread to self!\n");
1118eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner    return false;
1119eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner  }
1120eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner
1121fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // If threading this would thread across a loop header, don't thread the edge.
1122fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // See the comments above FindLoopHeaders for justifications and caveats.
1123fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (LoopHeaders.count(BB)) {
11245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Not threading across loop header BB '" << BB->getName()
112593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' to dest BB '" << SuccBB->getName()
112693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          << "' - it might create an irreducible loop!\n");
1127fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    return false;
1128fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
1129fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
113078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
113178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (JumpThreadCost > Threshold) {
113278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not threading BB '" << BB->getName()
113378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << JumpThreadCost << "\n");
113478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
113578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
113678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
11375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // And finally, do it!  Start by factoring the predecessors is needed.
11385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  BasicBlock *PredBB;
11395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  if (PredBBs.size() == 1)
11405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = PredBBs[0];
11415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  else {
11425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DEBUG(errs() << "  Factoring out " << PredBBs.size()
11435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          << " common predecessors.\n");
11445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
11455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                    ".thr_comm", this);
11465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
11475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
1148a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // And finally, do it!
114993b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  DEBUG(errs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1150460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar        << SuccBB->getName() << "' with cost: " << JumpThreadCost
115193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << ", across block:\n    "
115293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        << *BB << "\n");
1153a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner
1154bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We are going to have to map operands from the original BB block to the new
1155bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1156bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // account for entry from PredBB.
1157bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
1158bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
11591d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
11601d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getName()+".thread",
11611d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                         BB->getParent(), BB);
1162bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  NewBB->moveAfter(PredBB);
1163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1164bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BasicBlock::iterator BI = BB->begin();
1165bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1166bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1167bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1168bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Clone the non-phi instructions of BB into NewBB, keeping track of the
1169bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
1170bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (; !isa<TerminatorInst>(BI); ++BI) {
11716776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky    Instruction *New = BI->clone();
1172460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar    New->setName(BI->getName());
1173bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    NewBB->getInstList().push_back(New);
1174bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ValueMapping[BI] = New;
1175bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1176bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Remap operands to patch up intra-block references.
1177bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1178f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1179f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1180f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman        if (I != ValueMapping.end())
1181f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman          New->setOperand(i, I->second);
1182f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman      }
1183bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
1184bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1185bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // We didn't copy the terminator from BB over to NewBB, because there is now
1186bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // an unconditional jump to SuccBB.  Insert the unconditional jump.
1187bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  BranchInst::Create(SuccBB, NewBB);
1188bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1189bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1190bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // PHI nodes for NewBB now.
119178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1192177480b7ede0441135572d641a2497df25a7d95fChris Lattner
1193433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // If there were values defined in BB that are used outside the block, then we
1194433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // now have to update all uses of the value to use either the original value,
1195433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
1196433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
1197433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SSAUpdater SSAUpdate;
1198433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  SmallVector<Use*, 16> UsesToRename;
1199433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1200433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // Scan all uses of this instruction to see if it is used outside of its
1201433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // block, and if so, record them in UsesToRename.
1202433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1203433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner         ++UI) {
1204433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Instruction *User = cast<Instruction>(*UI);
1205433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1206433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
1207433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          continue;
1208433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      } else if (User->getParent() == BB)
1209433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        continue;
1210433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1211433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      UsesToRename.push_back(&UI.getUse());
1212433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    }
1213433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1214433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // If there are no uses outside the block, we're done with this instruction.
1215433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    if (UsesToRename.empty())
1216433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      continue;
1217433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1218433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1219433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1220433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
1221433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1222433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    // with the two values we know.
1223433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.Initialize(I);
1224433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(BB, I);
1225433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1226433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1227433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    while (!UsesToRename.empty())
1228433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1229433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    DEBUG(errs() << "\n");
1230433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner  }
1231433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1232433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1233ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1234bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1235bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  // us to simplify any PHI nodes in BB.
1236bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  TerminatorInst *PredTerm = PredBB->getTerminator();
1237bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1238bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (PredTerm->getSuccessor(i) == BB) {
1239c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      RemovePredecessorAndSimplify(BB, PredBB, TD);
1240bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      PredTerm->setSuccessor(i, NewBB);
1241bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1242ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1243ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // At this point, the IR is fully up to date and consistent.  Do a quick scan
1244ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // over the new instructions and zap any that are constants or dead.  This
1245ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  // frequently happens because of phi translation.
1246ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  BI = NewBB->begin();
1247ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1248ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    Instruction *Inst = BI++;
1249fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
1250e34537856a544c83513e390ac9552a8bc3823346Chris Lattner    if (Value *V = SimplifyInstruction(Inst, TD)) {
1251fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      WeakVH BIHandle(BI);
1252fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      ReplaceAndSimplifyAllUses(Inst, V, TD);
1253fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (BIHandle == 0)
1254fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        BI = NewBB->begin();
1255ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      continue;
1256ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    }
1257ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1258ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner    RecursivelyDeleteTriviallyDeadInstructions(Inst);
1259ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner  }
1260fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1261fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  // Threaded an edge!
1262fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  ++NumThreads;
1263fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return true;
1264177480b7ede0441135572d641a2497df25a7d95fChris Lattner}
126578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
126678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
126778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
126878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// If we can duplicate the contents of BB up into PredBB do so now, this
126978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// improves the odds that the branch will be on an analyzable instruction like
127078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// a compare.
127178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattnerbool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
127278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                     BasicBlock *PredBB) {
127378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If BB is a loop header, then duplicating this block outside the loop would
127478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // cause us to transform this into an irreducible loop, don't do this.
127578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // See the comments above FindLoopHeaders for justifications and caveats.
127678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (LoopHeaders.count(BB)) {
127778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating loop header '" << BB->getName()
127878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' into predecessor block '" << PredBB->getName()
127978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - it might create an irreducible loop!\n");
128078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
128178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
128278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
128478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (DuplicationCost > Threshold) {
128578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "  Not duplicating BB '" << BB->getName()
128678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          << "' - Cost is too high: " << DuplicationCost << "\n");
128778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return false;
128878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
128978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Okay, we decided to do this!  Clone all the instructions in BB onto the end
129178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // of PredBB.
129278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DEBUG(errs() << "  Duplicating block '" << BB->getName() << "' into end of '"
129378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
129478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        << DuplicationCost << " block is:" << *BB << "\n");
129578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // We are going to have to map operands from the original BB block into the
129778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB block.  Evaluate PHI nodes in BB.
129878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DenseMap<Instruction*, Value*> ValueMapping;
129978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BasicBlock::iterator BI = BB->begin();
130178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
130278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
130378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
130578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Clone the non-phi instructions of BB into PredBB, keeping track of the
130778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // mapping and using it to remap operands in the cloned instructions.
130878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (; BI != BB->end(); ++BI) {
130978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Instruction *New = BI->clone();
131078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    New->setName(BI->getName());
131178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    PredBB->getInstList().insert(OldPredBranch, New);
131278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ValueMapping[BI] = New;
131378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
131478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Remap operands to patch up intra-block references.
131578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
131678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
131778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
131878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (I != ValueMapping.end())
131978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          New->setOperand(i, I->second);
132078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
132178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
132278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
132378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Check to see if the targets of the branch had PHI nodes. If so, we need to
132478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // add entries to the PHI nodes for branch from PredBB now.
132578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
132678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
132778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
132878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
132978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  ValueMapping);
133078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // If there were values defined in BB that are used outside the block, then we
133278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // now have to update all uses of the value to use either the original value,
133378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // the cloned value, or some PHI derived value.  This can require arbitrary
133478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PHI insertion, of which we are prepared to do, clean these up now.
133578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SSAUpdater SSAUpdate;
133678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<Use*, 16> UsesToRename;
133778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
133878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // Scan all uses of this instruction to see if it is used outside of its
133978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // block, and if so, record them in UsesToRename.
134078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
134178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner         ++UI) {
134278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Instruction *User = cast<Instruction>(*UI);
134378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
134478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        if (UserPN->getIncomingBlock(UI) == BB)
134578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          continue;
134678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else if (User->getParent() == BB)
134778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        continue;
134878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      UsesToRename.push_back(&UI.getUse());
135078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
135178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // If there are no uses outside the block, we're done with this instruction.
135378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    if (UsesToRename.empty())
135478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      continue;
135578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
135778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // We found a use of I outside of BB.  Rename all uses of I that are outside
135978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
136078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    // with the two values we know.
136178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.Initialize(I);
136278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(BB, I);
136378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
136478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
136578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    while (!UsesToRename.empty())
136678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
136778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DEBUG(errs() << "\n");
136878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
136978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
137078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
137178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // that we nuked.
1372c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  RemovePredecessorAndSimplify(BB, PredBB, TD);
137378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
137478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Remove the unconditional branch at the end of the PredBB block.
137578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  OldPredBranch->eraseFromParent();
137678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
137778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  ++NumDupes;
137878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return true;
137978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
138078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
138178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1382