blob: 43460beb3bd96de79caec77e2a029fb1ae500be3 [file] [log] [blame]
Chris Lattner8383a7b2008-04-20 20:35:01 +00001//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner177480b2008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattner8383a7b2008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner177480b2008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Owen Anderson1ff50b32009-07-03 00:54:20 +000017#include "llvm/LLVMContext.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000018#include "llvm/Pass.h"
Chris Lattner9819ef72009-11-09 23:00:14 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000020#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohmandd9344f2010-05-28 16:19:17 +000021#include "llvm/Analysis/Loads.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000023#include "llvm/Transforms/Utils/Local.h"
Chris Lattner433a0db2009-10-10 09:05:58 +000024#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000025#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000026#include "llvm/ADT/DenseMap.h"
Owen Andersoncb211902010-08-31 07:36:34 +000027#include "llvm/ADT/DenseSet.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000028#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000032#include "llvm/Support/CommandLine.h"
Chris Lattner177480b2008-04-20 21:13:06 +000033#include "llvm/Support/Debug.h"
Chris Lattner56608462009-12-28 08:20:46 +000034#include "llvm/Support/ValueHandle.h"
Daniel Dunbar93b67e42009-07-26 07:49:05 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000036using namespace llvm;
37
Chris Lattnerbd3401f2008-04-20 22:39:42 +000038STATISTIC(NumThreads, "Number of jumps threaded");
39STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner78c552e2009-10-11 07:24:57 +000040STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
Chris Lattner8383a7b2008-04-20 20:35:01 +000041
Chris Lattner177480b2008-04-20 21:13:06 +000042static cl::opt<unsigned>
43Threshold("jump-threading-threshold",
44 cl::desc("Max block size to duplicate for jump threading"),
45 cl::init(6), cl::Hidden);
46
Chris Lattner8383a7b2008-04-20 20:35:01 +000047namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000048 /// This pass performs 'jump threading', which looks at blocks that have
49 /// multiple predecessors and multiple successors. If one or more of the
50 /// predecessors of the block can be proven to always jump to one of the
51 /// successors, we forward the edge from the predecessor to the successor by
52 /// duplicating the contents of this block.
53 ///
54 /// An example of when this can occur is code like this:
55 ///
56 /// if () { ...
57 /// X = 4;
58 /// }
59 /// if (X < 3) {
60 ///
61 /// In this case, the unconditional branch at the end of the first if can be
62 /// revectored to the false side of the second if.
63 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +000064 class JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000065 TargetData *TD;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000066 LazyValueInfo *LVI;
Mike Stumpfe095f32009-05-04 18:40:41 +000067#ifdef NDEBUG
68 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
69#else
70 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
71#endif
Owen Andersoncb211902010-08-31 07:36:34 +000072 DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
Owen Anderson9ba35362010-08-31 19:24:27 +000073
74 // RAII helper for updating the recursion stack.
75 struct RecursionSetRemover {
76 DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
77 std::pair<Value*, BasicBlock*> ThePair;
78
79 RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
80 std::pair<Value*, BasicBlock*> P)
81 : TheSet(S), ThePair(P) { }
82
83 ~RecursionSetRemover() {
84 TheSet.erase(ThePair);
85 }
86 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000087 public:
88 static char ID; // Pass identification
Owen Anderson90c579d2010-08-06 18:33:48 +000089 JumpThreading() : FunctionPass(ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000090
91 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000092
Chris Lattnercc4d3b22009-11-11 02:08:33 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonc809d902010-09-14 20:57:41 +000094 AU.addRequired<LazyValueInfo>();
95 AU.addPreserved<LazyValueInfo>();
Chris Lattnercc4d3b22009-11-11 02:08:33 +000096 }
97
98 void FindLoopHeaders(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000099 bool ProcessBlock(BasicBlock *BB);
Chris Lattner5729d382009-11-07 08:05:03 +0000100 bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
101 BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +0000102 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
Chris Lattner2249a0b2010-01-12 02:07:17 +0000103 const SmallVectorImpl<BasicBlock *> &PredBBs);
Chris Lattner5729d382009-11-07 08:05:03 +0000104
105 typedef SmallVectorImpl<std::pair<ConstantInt*,
106 BasicBlock*> > PredValueInfo;
107
108 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
109 PredValueInfo &Result);
Chris Lattner1c96b412009-11-12 01:37:43 +0000110 bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB);
Chris Lattner5729d382009-11-07 08:05:03 +0000111
112
Chris Lattner421fa9e2008-12-03 07:48:08 +0000113 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000114 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +0000115
Chris Lattner77beb472010-01-11 23:41:09 +0000116 bool ProcessBranchOnPHI(PHINode *PN);
Chris Lattner2249a0b2010-01-12 02:07:17 +0000117 bool ProcessBranchOnXOR(BinaryOperator *BO);
Chris Lattner69e067f2008-11-27 05:07:53 +0000118
119 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +0000120 };
Chris Lattner8383a7b2008-04-20 20:35:01 +0000121}
122
Dan Gohman844731a2008-05-13 00:00:25 +0000123char JumpThreading::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000124INITIALIZE_PASS(JumpThreading, "jump-threading",
125 "Jump Threading", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +0000126
Chris Lattner8383a7b2008-04-20 20:35:01 +0000127// Public interface to the Jump Threading pass
128FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
129
130/// runOnFunction - Top level algorithm.
131///
132bool JumpThreading::runOnFunction(Function &F) {
David Greenefe7fe662010-01-05 01:27:19 +0000133 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000134 TD = getAnalysisIfAvailable<TargetData>();
Owen Andersonc809d902010-09-14 20:57:41 +0000135 LVI = &getAnalysis<LazyValueInfo>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000136
Mike Stumpfe095f32009-05-04 18:40:41 +0000137 FindLoopHeaders(F);
138
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000139 bool Changed, EverChanged = false;
140 do {
141 Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000142 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
143 BasicBlock *BB = I;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000144 // Thread all of the branches we can over this block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000145 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000146 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000147
148 ++I;
149
150 // If the block is trivially dead, zap it. This eliminates the successor
151 // edges which simplifies the CFG.
152 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000153 BB != &BB->getParent()->getEntryBlock()) {
David Greenefe7fe662010-01-05 01:27:19 +0000154 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000155 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000156 LoopHeaders.erase(BB);
Owen Andersonc809d902010-09-14 20:57:41 +0000157 LVI->eraseBlock(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000158 DeleteDeadBlock(BB);
159 Changed = true;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000160 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
161 // Can't thread an unconditional jump, but if the block is "almost
162 // empty", we can replace uses of it with uses of the successor and make
163 // this dead.
164 if (BI->isUnconditional() &&
165 BB != &BB->getParent()->getEntryBlock()) {
166 BasicBlock::iterator BBI = BB->getFirstNonPHI();
167 // Ignore dbg intrinsics.
168 while (isa<DbgInfoIntrinsic>(BBI))
169 ++BBI;
170 // If the terminator is the only non-phi instruction, try to nuke it.
171 if (BBI->isTerminator()) {
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000172 // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
173 // block, we have to make sure it isn't in the LoopHeaders set. We
Chris Lattner46875c02009-12-01 06:04:43 +0000174 // reinsert afterward if needed.
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000175 bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000176 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerf3183f62009-11-10 21:40:01 +0000177
Owen Anderson00ac77e2010-08-18 18:39:01 +0000178 // FIXME: It is always conservatively correct to drop the info
179 // for a block even if it doesn't get erased. This isn't totally
180 // awesome, but it allows us to use AssertingVH to prevent nasty
181 // dangling pointer issues within LazyValueInfo.
Owen Andersonc809d902010-09-14 20:57:41 +0000182 LVI->eraseBlock(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000183 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
Chris Lattnerf3183f62009-11-10 21:40:01 +0000184 Changed = true;
Chris Lattner46875c02009-12-01 06:04:43 +0000185 // If we deleted BB and BB was the header of a loop, then the
186 // successor is now the header of the loop.
187 BB = Succ;
188 }
189
190 if (ErasedFromLoopHeaders)
Chris Lattnerf3183f62009-11-10 21:40:01 +0000191 LoopHeaders.insert(BB);
192 }
193 }
Chris Lattner421fa9e2008-12-03 07:48:08 +0000194 }
195 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000196 EverChanged |= Changed;
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000197 } while (Changed);
Mike Stumpfe095f32009-05-04 18:40:41 +0000198
199 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000200 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000201}
Chris Lattner177480b2008-04-20 21:13:06 +0000202
Chris Lattner78c552e2009-10-11 07:24:57 +0000203/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
204/// thread across it.
205static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
206 /// Ignore PHI nodes, these will be flattened when duplication happens.
207 BasicBlock::const_iterator I = BB->getFirstNonPHI();
208
Chris Lattnerb14b88a2009-11-11 00:21:58 +0000209 // FIXME: THREADING will delete values that are just used to compute the
210 // branch, so they shouldn't count against the duplication cost.
211
212
Chris Lattner78c552e2009-10-11 07:24:57 +0000213 // Sum up the cost of each instruction until we get to the terminator. Don't
214 // include the terminator because the copy won't include it.
215 unsigned Size = 0;
216 for (; !isa<TerminatorInst>(I); ++I) {
217 // Debugger intrinsics don't incur code size.
218 if (isa<DbgInfoIntrinsic>(I)) continue;
219
220 // If this is a pointer->pointer bitcast, it is free.
Duncan Sands1df98592010-02-16 11:11:14 +0000221 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000222 continue;
223
224 // All other instructions count for at least one unit.
225 ++Size;
226
227 // Calls are more expensive. If they are non-intrinsic calls, we model them
228 // as having cost of 4. If they are a non-vector intrinsic, we model them
229 // as having cost of 2 total, and if they are a vector intrinsic, we model
230 // them as having cost 1.
231 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
232 if (!isa<IntrinsicInst>(CI))
233 Size += 3;
Duncan Sands1df98592010-02-16 11:11:14 +0000234 else if (!CI->getType()->isVectorTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000235 Size += 1;
236 }
237 }
238
239 // Threading through a switch statement is particularly profitable. If this
240 // block ends in a switch, decrease its cost to make it more likely to happen.
241 if (isa<SwitchInst>(I))
242 Size = Size > 6 ? Size-6 : 0;
243
244 return Size;
245}
246
Mike Stumpfe095f32009-05-04 18:40:41 +0000247/// FindLoopHeaders - We do not want jump threading to turn proper loop
248/// structures into irreducible loops. Doing this breaks up the loop nesting
249/// hierarchy and pessimizes later transformations. To prevent this from
250/// happening, we first have to find the loop headers. Here we approximate this
251/// by finding targets of backedges in the CFG.
252///
253/// Note that there definitely are cases when we want to allow threading of
254/// edges across a loop header. For example, threading a jump from outside the
255/// loop (the preheader) to an exit block of the loop is definitely profitable.
256/// It is also almost always profitable to thread backedges from within the loop
257/// to exit blocks, and is often profitable to thread backedges to other blocks
258/// within the loop (forming a nested loop). This simple analysis is not rich
259/// enough to track all of these properties and keep it up-to-date as the CFG
260/// mutates, so we don't allow any of these transformations.
261///
262void JumpThreading::FindLoopHeaders(Function &F) {
263 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
264 FindFunctionBackedges(F, Edges);
265
266 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
267 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
268}
269
Owen Anderson0eb355a2010-08-31 20:26:04 +0000270// Helper method for ComputeValueKnownInPredecessors. If Value is a
271// ConstantInt, push it. If it's an undef, push 0. Otherwise, do nothing.
272static void PushConstantIntOrUndef(SmallVectorImpl<std::pair<ConstantInt*,
273 BasicBlock*> > &Result,
274 Constant *Value, BasicBlock* BB){
275 if (ConstantInt *FoldedCInt = dyn_cast<ConstantInt>(Value))
276 Result.push_back(std::make_pair(FoldedCInt, BB));
277 else if (isa<UndefValue>(Value))
278 Result.push_back(std::make_pair((ConstantInt*)0, BB));
279}
280
Chris Lattner5729d382009-11-07 08:05:03 +0000281/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
282/// if we can infer that the value is a known ConstantInt in any of our
Chris Lattnere7e63fe2009-11-09 00:41:49 +0000283/// predecessors. If so, return the known list of value and pred BB in the
Chris Lattner5729d382009-11-07 08:05:03 +0000284/// result vector. If a value is known to be undef, it is returned as null.
285///
Chris Lattner5729d382009-11-07 08:05:03 +0000286/// This returns true if there were any known values.
287///
Chris Lattner5729d382009-11-07 08:05:03 +0000288bool JumpThreading::
289ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
Owen Anderson9ba35362010-08-31 19:24:27 +0000290 // This method walks up use-def chains recursively. Because of this, we could
291 // get into an infinite loop going around loops in the use-def chain. To
292 // prevent this, keep track of what (value, block) pairs we've already visited
293 // and terminate the search if we loop back to them
Owen Andersoncb211902010-08-31 07:36:34 +0000294 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
295 return false;
296
Owen Anderson9ba35362010-08-31 19:24:27 +0000297 // An RAII help to remove this pair from the recursion set once the recursion
298 // stack pops back out again.
299 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
300
Chris Lattner5729d382009-11-07 08:05:03 +0000301 // If V is a constantint, then it is known in all predecessors.
302 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
303 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000304
305 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
306 Result.push_back(std::make_pair(CI, *PI));
Owen Andersoncb211902010-08-31 07:36:34 +0000307
Chris Lattner5729d382009-11-07 08:05:03 +0000308 return true;
309 }
310
311 // If V is a non-instruction value, or an instruction in a different block,
312 // then it can't be derived from a PHI.
313 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000314 if (I == 0 || I->getParent() != BB) {
315
316 // Okay, if this is a live-in value, see if it has a known value at the end
317 // of any of our predecessors.
318 //
319 // FIXME: This should be an edge property, not a block end property.
320 /// TODO: Per PR2563, we could infer value range information about a
321 /// predecessor based on its terminator.
322 //
Owen Andersonc809d902010-09-14 20:57:41 +0000323 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
324 // "I" is a non-local compare-with-a-constant instruction. This would be
325 // able to handle value inequalities better, for example if the compare is
326 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
327 // Perhaps getConstantOnEdge should be smart enough to do this?
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000328
Owen Andersonc809d902010-09-14 20:57:41 +0000329 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
330 BasicBlock *P = *PI;
331 // If the value is known by LazyValueInfo to be a constant in a
332 // predecessor, use that information to try to thread this block.
333 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
334 if (PredCst == 0 ||
335 (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
336 continue;
337
338 Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), P));
339 }
340
341 return !Result.empty();
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000342 }
Chris Lattner5729d382009-11-07 08:05:03 +0000343
344 /// If I is a PHI node, then we know the incoming values for any constants.
345 if (PHINode *PN = dyn_cast<PHINode>(I)) {
346 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
347 Value *InVal = PN->getIncomingValue(i);
348 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
349 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
350 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
Owen Andersonc809d902010-09-14 20:57:41 +0000351 } else {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000352 Constant *CI = LVI->getConstantOnEdge(InVal,
353 PN->getIncomingBlock(i), BB);
Owen Anderson327ca7b2010-08-30 23:22:36 +0000354 // LVI returns null is no value could be determined.
355 if (!CI) continue;
Owen Anderson0eb355a2010-08-31 20:26:04 +0000356 PushConstantIntOrUndef(Result, CI, PN->getIncomingBlock(i));
Chris Lattner5729d382009-11-07 08:05:03 +0000357 }
358 }
Owen Andersoncb211902010-08-31 07:36:34 +0000359
Chris Lattner5729d382009-11-07 08:05:03 +0000360 return !Result.empty();
361 }
362
363 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
364
365 // Handle some boolean conditions.
366 if (I->getType()->getPrimitiveSizeInBits() == 1) {
367 // X | true -> true
368 // X & false -> false
369 if (I->getOpcode() == Instruction::Or ||
370 I->getOpcode() == Instruction::And) {
371 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
372 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
373
Owen Anderson9ba35362010-08-31 19:24:27 +0000374 if (LHSVals.empty() && RHSVals.empty())
Chris Lattner5729d382009-11-07 08:05:03 +0000375 return false;
376
377 ConstantInt *InterestingVal;
378 if (I->getOpcode() == Instruction::Or)
379 InterestingVal = ConstantInt::getTrue(I->getContext());
380 else
381 InterestingVal = ConstantInt::getFalse(I->getContext());
382
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000383 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
384
Chris Lattner1e452652010-02-11 04:40:44 +0000385 // Scan for the sentinel. If we find an undef, force it to the
386 // interesting value: x|undef -> true and x&undef -> false.
Chris Lattner5729d382009-11-07 08:05:03 +0000387 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000388 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) {
Chris Lattner5729d382009-11-07 08:05:03 +0000389 Result.push_back(LHSVals[i]);
Chris Lattner1e452652010-02-11 04:40:44 +0000390 Result.back().first = InterestingVal;
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000391 LHSKnownBBs.insert(LHSVals[i].second);
Chris Lattner1e452652010-02-11 04:40:44 +0000392 }
Chris Lattner5729d382009-11-07 08:05:03 +0000393 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000394 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) {
Chris Lattner0a961442010-07-12 00:47:34 +0000395 // If we already inferred a value for this block on the LHS, don't
396 // re-add it.
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000397 if (!LHSKnownBBs.count(RHSVals[i].second)) {
Chris Lattner0a961442010-07-12 00:47:34 +0000398 Result.push_back(RHSVals[i]);
399 Result.back().first = InterestingVal;
400 }
Chris Lattner1e452652010-02-11 04:40:44 +0000401 }
Owen Andersoncb211902010-08-31 07:36:34 +0000402
Chris Lattner5729d382009-11-07 08:05:03 +0000403 return !Result.empty();
404 }
405
Chris Lattner055d0462009-11-10 22:39:16 +0000406 // Handle the NOT form of XOR.
407 if (I->getOpcode() == Instruction::Xor &&
408 isa<ConstantInt>(I->getOperand(1)) &&
409 cast<ConstantInt>(I->getOperand(1))->isOne()) {
410 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result);
Owen Anderson9ba35362010-08-31 19:24:27 +0000411 if (Result.empty())
Chris Lattner055d0462009-11-10 22:39:16 +0000412 return false;
413
414 // Invert the known values.
415 for (unsigned i = 0, e = Result.size(); i != e; ++i)
Chris Lattner1fb56302009-11-15 19:57:43 +0000416 if (Result[i].first)
417 Result[i].first =
418 cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
Owen Andersoncb211902010-08-31 07:36:34 +0000419
Chris Lattner055d0462009-11-10 22:39:16 +0000420 return true;
421 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000422
423 // Try to simplify some other binary operator values.
424 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Owen Anderson0eb355a2010-08-31 20:26:04 +0000425 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000426 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
427 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals);
Owen Andersoncb211902010-08-31 07:36:34 +0000428
429 // Try to use constant folding to simplify the binary operator.
430 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Chris Lattner906a6752010-09-05 20:03:09 +0000431 Constant *V = LHSVals[i].first;
432 if (V == 0) V = UndefValue::get(BO->getType());
Owen Anderson0eb355a2010-08-31 20:26:04 +0000433 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
Owen Andersoncb211902010-08-31 07:36:34 +0000434
Owen Anderson0eb355a2010-08-31 20:26:04 +0000435 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Andersoncb211902010-08-31 07:36:34 +0000436 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000437 }
Owen Andersoncb211902010-08-31 07:36:34 +0000438
Owen Andersoncb211902010-08-31 07:36:34 +0000439 return !Result.empty();
Chris Lattner5729d382009-11-07 08:05:03 +0000440 }
441
442 // Handle compare with phi operand, where the PHI is defined in this block.
443 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
444 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
445 if (PN && PN->getParent() == BB) {
446 // We can do this simplification if any comparisons fold to true or false.
447 // See if any do.
448 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
449 BasicBlock *PredBB = PN->getIncomingBlock(i);
450 Value *LHS = PN->getIncomingValue(i);
451 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
452
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000453 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
Chris Lattner66c04c42009-11-12 05:24:05 +0000454 if (Res == 0) {
Owen Andersonc809d902010-09-14 20:57:41 +0000455 if (!isa<Constant>(RHS))
Chris Lattner66c04c42009-11-12 05:24:05 +0000456 continue;
457
458 LazyValueInfo::Tristate
459 ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
460 cast<Constant>(RHS), PredBB, BB);
461 if (ResT == LazyValueInfo::Unknown)
462 continue;
463 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
464 }
Chris Lattner5729d382009-11-07 08:05:03 +0000465
Owen Anderson0eb355a2010-08-31 20:26:04 +0000466 if (Constant *ConstRes = dyn_cast<Constant>(Res))
467 PushConstantIntOrUndef(Result, ConstRes, PredBB);
Chris Lattner5729d382009-11-07 08:05:03 +0000468 }
469
470 return !Result.empty();
471 }
472
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000473
474 // If comparing a live-in value against a constant, see if we know the
475 // live-in value on any predecessors.
Owen Andersonc809d902010-09-14 20:57:41 +0000476 if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000477 if (!isa<Instruction>(Cmp->getOperand(0)) ||
Owen Anderson327ca7b2010-08-30 23:22:36 +0000478 cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000479 Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
Gabor Greifee1f44f2010-07-12 14:10:24 +0000480
Owen Anderson62efd3b2010-08-26 17:40:24 +0000481 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
482 BasicBlock *P = *PI;
483 // If the value is known by LazyValueInfo to be a constant in a
484 // predecessor, use that information to try to thread this block.
485 LazyValueInfo::Tristate Res =
486 LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
487 RHSCst, P, BB);
488 if (Res == LazyValueInfo::Unknown)
489 continue;
Chris Lattner0e0ff292009-11-12 04:37:50 +0000490
Owen Anderson62efd3b2010-08-26 17:40:24 +0000491 Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
492 Result.push_back(std::make_pair(cast<ConstantInt>(ResC), P));
493 }
494
495 return !Result.empty();
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000496 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000497
Owen Andersoncb211902010-08-31 07:36:34 +0000498 // Try to find a constant value for the LHS of a comparison,
Owen Anderson62efd3b2010-08-26 17:40:24 +0000499 // and evaluate it statically if we can.
Owen Anderson327ca7b2010-08-30 23:22:36 +0000500 if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000501 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
502 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
503
Owen Anderson62efd3b2010-08-26 17:40:24 +0000504 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Chris Lattner906a6752010-09-05 20:03:09 +0000505 Constant *V = LHSVals[i].first;
506 if (V == 0) V = UndefValue::get(CmpConst->getType());
Owen Anderson0eb355a2010-08-31 20:26:04 +0000507 Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
508 V, CmpConst);
509 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Anderson62efd3b2010-08-26 17:40:24 +0000510 }
511
512 return !Result.empty();
513 }
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000514 }
Chris Lattner5729d382009-11-07 08:05:03 +0000515 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000516
Owen Andersonc809d902010-09-14 20:57:41 +0000517 // If all else fails, see if LVI can figure out a constant value for us.
518 Constant *CI = LVI->getConstant(V, BB);
519 ConstantInt *CInt = dyn_cast_or_null<ConstantInt>(CI);
520 if (CInt) {
521 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
522 Result.push_back(std::make_pair(CInt, *PI));
Owen Anderson62efd3b2010-08-26 17:40:24 +0000523 }
Owen Andersonc809d902010-09-14 20:57:41 +0000524
525 return !Result.empty();
Chris Lattner5729d382009-11-07 08:05:03 +0000526}
527
528
Chris Lattner6bf77502008-04-22 07:05:46 +0000529
Chris Lattnere33583b2009-10-11 04:18:15 +0000530/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
531/// in an undefined jump, decide which block is best to revector to.
532///
533/// Since we can pick an arbitrary destination, we pick the successor with the
534/// fewest predecessors. This should reduce the in-degree of the others.
535///
536static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
537 TerminatorInst *BBTerm = BB->getTerminator();
538 unsigned MinSucc = 0;
539 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
540 // Compute the successor with the minimum number of predecessors.
541 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
542 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
543 TestBB = BBTerm->getSuccessor(i);
544 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
545 if (NumPreds < MinNumPreds)
546 MinSucc = i;
547 }
548
549 return MinSucc;
550}
551
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000552/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000553/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000554bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner8231fd12010-01-23 18:56:07 +0000555 // If the block is trivially dead, just return and let the caller nuke it.
556 // This simplifies other transformations.
557 if (pred_begin(BB) == pred_end(BB) &&
558 BB != &BB->getParent()->getEntryBlock())
559 return false;
560
Chris Lattner69e067f2008-11-27 05:07:53 +0000561 // If this block has a single predecessor, and if that pred has a single
562 // successor, merge the blocks. This encourages recursive jump threading
563 // because now the condition in this block can be threaded through
564 // predecessors of our predecessor block.
Chris Lattner5729d382009-11-07 08:05:03 +0000565 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000566 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
567 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000568 // If SinglePred was a loop header, BB becomes one.
569 if (LoopHeaders.erase(SinglePred))
570 LoopHeaders.insert(BB);
571
Chris Lattner3d86d242008-11-27 19:25:19 +0000572 // Remember if SinglePred was the entry block of the function. If so, we
573 // will need to move BB back to the entry position.
574 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Owen Andersonc809d902010-09-14 20:57:41 +0000575 LVI->eraseBlock(SinglePred);
Chris Lattner69e067f2008-11-27 05:07:53 +0000576 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000577
578 if (isEntry && BB != &BB->getParent()->getEntryBlock())
579 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000580 return true;
581 }
Chris Lattner5729d382009-11-07 08:05:03 +0000582 }
583
584 // Look to see if the terminator is a branch of switch, if not we can't thread
585 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000586 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000587 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
588 // Can't thread an unconditional jump.
589 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000590 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000591 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000592 Condition = SI->getCondition();
593 else
594 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000595
596 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000597 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000598 // other blocks.
599 if (isa<ConstantInt>(Condition)) {
David Greenefe7fe662010-01-05 01:27:19 +0000600 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000601 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000602 ++NumFolds;
603 ConstantFoldTerminator(BB);
604 return true;
605 }
606
Chris Lattner421fa9e2008-12-03 07:48:08 +0000607 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000608 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000609 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000610 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000611
612 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000613 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000614 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000615 if (i == BestSucc) continue;
Owen Anderson36c4deb2010-09-29 20:34:41 +0000616 BBTerm->getSuccessor(i)->removePredecessor(BB, true);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000617 }
618
David Greenefe7fe662010-01-05 01:27:19 +0000619 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000620 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000621 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000622 BBTerm->eraseFromParent();
623 return true;
624 }
625
626 Instruction *CondInst = dyn_cast<Instruction>(Condition);
627
Chris Lattner421fa9e2008-12-03 07:48:08 +0000628 // All the rest of our checks depend on the condition being an instruction.
Chris Lattner87e9f592009-11-12 01:41:34 +0000629 if (CondInst == 0) {
630 // FIXME: Unify this with code below.
Owen Andersonc809d902010-09-14 20:57:41 +0000631 if (ProcessThreadableEdges(Condition, BB))
Chris Lattner87e9f592009-11-12 01:41:34 +0000632 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000633 return false;
Chris Lattner87e9f592009-11-12 01:41:34 +0000634 }
635
Chris Lattner421fa9e2008-12-03 07:48:08 +0000636
Nick Lewycky9683f182009-06-19 04:56:29 +0000637 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Owen Anderson660cab32010-08-27 17:12:29 +0000638 // For a comparison where the LHS is outside this block, it's possible
Owen Andersonfc2fb172010-08-27 20:32:56 +0000639 // that we've branched on it before. Used LVI to see if we can simplify
Owen Anderson660cab32010-08-27 17:12:29 +0000640 // the branch based on that.
641 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
642 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
Owen Andersonc1bdac62010-08-31 18:48:48 +0000643 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Owen Andersonc809d902010-09-14 20:57:41 +0000644 if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
Owen Anderson660cab32010-08-27 17:12:29 +0000645 (!isa<Instruction>(CondCmp->getOperand(0)) ||
646 cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
647 // For predecessor edge, determine if the comparison is true or false
648 // on that edge. If they're all true or all false, we can simplify the
649 // branch.
650 // FIXME: We could handle mixed true/false by duplicating code.
Owen Andersonc1bdac62010-08-31 18:48:48 +0000651 LazyValueInfo::Tristate Baseline =
652 LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
653 CondConst, *PI, BB);
654 if (Baseline != LazyValueInfo::Unknown) {
655 // Check that all remaining incoming values match the first one.
656 while (++PI != PE) {
Chris Lattnerbdabacd2010-09-05 20:10:47 +0000657 LazyValueInfo::Tristate Ret =
658 LVI->getPredicateOnEdge(CondCmp->getPredicate(),
659 CondCmp->getOperand(0), CondConst, *PI, BB);
Owen Andersonc1bdac62010-08-31 18:48:48 +0000660 if (Ret != Baseline) break;
661 }
662
663 // If we terminated early, then one of the values didn't match.
664 if (PI == PE) {
665 unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
666 unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
Owen Anderson36c4deb2010-09-29 20:34:41 +0000667 CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
Owen Andersonc1bdac62010-08-31 18:48:48 +0000668 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
669 CondBr->eraseFromParent();
670 return true;
671 }
Owen Anderson660cab32010-08-27 17:12:29 +0000672 }
673 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000674 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000675
676 // Check for some cases that are worth simplifying. Right now we want to look
677 // for loads that are used by a switch or by the condition for the branch. If
678 // we see one, check to see if it's partially redundant. If so, insert a PHI
679 // which can then be used to thread the values.
680 //
Chris Lattner421fa9e2008-12-03 07:48:08 +0000681 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000682 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
683 if (isa<Constant>(CondCmp->getOperand(1)))
684 SimplifyValue = CondCmp->getOperand(0);
685
Chris Lattner4e447eb2009-11-15 19:58:31 +0000686 // TODO: There are other places where load PRE would be profitable, such as
687 // more complex comparisons.
Chris Lattner69e067f2008-11-27 05:07:53 +0000688 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
689 if (SimplifyPartiallyRedundantLoad(LI))
690 return true;
691
Chris Lattner5729d382009-11-07 08:05:03 +0000692
693 // Handle a variety of cases where we are branching on something derived from
694 // a PHI node in the current block. If we can prove that any predecessors
695 // compute a predictable value based on a PHI node, thread those predecessors.
696 //
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000697 if (ProcessThreadableEdges(CondInst, BB))
698 return true;
Chris Lattner5729d382009-11-07 08:05:03 +0000699
Chris Lattner77beb472010-01-11 23:41:09 +0000700 // If this is an otherwise-unfoldable branch on a phi node in the current
701 // block, see if we can simplify.
702 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
703 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
704 return ProcessBranchOnPHI(PN);
Chris Lattner5729d382009-11-07 08:05:03 +0000705
Chris Lattner2249a0b2010-01-12 02:07:17 +0000706
707 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
708 if (CondInst->getOpcode() == Instruction::Xor &&
709 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
710 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
711
712
Chris Lattner69e067f2008-11-27 05:07:53 +0000713 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
Chris Lattner77beb472010-01-11 23:41:09 +0000714 // "(X == 4)", thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000715
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000716 return false;
717}
718
Chris Lattner421fa9e2008-12-03 07:48:08 +0000719/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
720/// block that jump on exactly the same condition. This means that we almost
721/// always know the direction of the edge in the DESTBB:
722/// PREDBB:
723/// br COND, DESTBB, BBY
724/// DESTBB:
725/// br COND, BBZ, BBW
726///
727/// If DESTBB has multiple predecessors, we can't just constant fold the branch
728/// in DESTBB, we have to thread over it.
729bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
730 BasicBlock *BB) {
731 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
732
733 // If both successors of PredBB go to DESTBB, we don't know anything. We can
734 // fold the branch to an unconditional one, which allows other recursive
735 // simplifications.
736 bool BranchDir;
737 if (PredBI->getSuccessor(1) != BB)
738 BranchDir = true;
739 else if (PredBI->getSuccessor(0) != BB)
740 BranchDir = false;
741 else {
David Greenefe7fe662010-01-05 01:27:19 +0000742 DEBUG(dbgs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000743 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000744 ++NumFolds;
745 ConstantFoldTerminator(PredBB);
746 return true;
747 }
748
749 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
750
751 // If the dest block has one predecessor, just fix the branch condition to a
752 // constant and fold it.
753 if (BB->getSinglePredecessor()) {
David Greenefe7fe662010-01-05 01:27:19 +0000754 DEBUG(dbgs() << " In block '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000755 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000756 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000757 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000758 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
760 BranchDir));
Chris Lattner6f285d22010-04-10 18:26:57 +0000761 // Delete dead instructions before we fold the branch. Folding the branch
762 // can eliminate edges from the CFG which can end up deleting OldCond.
Chris Lattner5a06cf62009-10-11 18:39:58 +0000763 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner6f285d22010-04-10 18:26:57 +0000764 ConstantFoldTerminator(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000765 return true;
766 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000767
Chris Lattner421fa9e2008-12-03 07:48:08 +0000768
769 // Next, figure out which successor we are threading to.
770 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
771
Chris Lattner5729d382009-11-07 08:05:03 +0000772 SmallVector<BasicBlock*, 2> Preds;
773 Preds.push_back(PredBB);
774
Mike Stumpfe095f32009-05-04 18:40:41 +0000775 // Ok, try to thread it!
Chris Lattner5729d382009-11-07 08:05:03 +0000776 return ThreadEdge(BB, Preds, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000777}
778
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000779/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
780/// block that switch on exactly the same condition. This means that we almost
781/// always know the direction of the edge in the DESTBB:
782/// PREDBB:
783/// switch COND [... DESTBB, BBY ... ]
784/// DESTBB:
785/// switch COND [... BBZ, BBW ]
786///
787/// Optimizing switches like this is very important, because simplifycfg builds
788/// switches out of repeated 'if' conditions.
789bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
790 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000791 // Can't thread edge to self.
792 if (PredBB == DestBB)
793 return false;
794
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000795 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
796 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
797
798 // There are a variety of optimizations that we can potentially do on these
799 // blocks: we order them from most to least preferable.
800
801 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
802 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000803 // growth. Skip debug info first.
804 BasicBlock::iterator BBI = DestBB->begin();
805 while (isa<DbgInfoIntrinsic>(BBI))
806 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000807
808 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000809 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000810 bool MadeChange = false;
811 // Ignore the default edge for now.
812 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
813 ConstantInt *DestVal = DestSI->getCaseValue(i);
814 BasicBlock *DestSucc = DestSI->getSuccessor(i);
815
816 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
817 // PredSI has an explicit case for it. If so, forward. If it is covered
818 // by the default case, we can't update PredSI.
819 unsigned PredCase = PredSI->findCaseValue(DestVal);
820 if (PredCase == 0) continue;
821
822 // If PredSI doesn't go to DestBB on this value, then it won't reach the
823 // case on this condition.
824 if (PredSI->getSuccessor(PredCase) != DestBB &&
825 DestSI->getSuccessor(i) != DestBB)
826 continue;
Chris Lattner08bc2702009-12-06 17:17:23 +0000827
828 // Do not forward this if it already goes to this destination, this would
829 // be an infinite loop.
830 if (PredSI->getSuccessor(PredCase) == DestSucc)
831 continue;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000832
833 // Otherwise, we're safe to make the change. Make sure that the edge from
834 // DestSI to DestSucc is not critical and has no PHI nodes.
David Greenefe7fe662010-01-05 01:27:19 +0000835 DEBUG(dbgs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
836 DEBUG(dbgs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000837
838 // If the destination has PHI nodes, just split the edge for updating
839 // simplicity.
840 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
841 SplitCriticalEdge(DestSI, i, this);
842 DestSucc = DestSI->getSuccessor(i);
843 }
844 FoldSingleEntryPHINodes(DestSucc);
845 PredSI->setSuccessor(PredCase, DestSucc);
846 MadeChange = true;
847 }
848
849 if (MadeChange)
850 return true;
851 }
852
853 return false;
854}
855
856
Chris Lattner69e067f2008-11-27 05:07:53 +0000857/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
858/// load instruction, eliminate it by replacing it with a PHI node. This is an
859/// important optimization that encourages jump threading, and needs to be run
860/// interlaced with other jump threading tasks.
861bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
862 // Don't hack volatile loads.
863 if (LI->isVolatile()) return false;
864
865 // If the load is defined in a block with exactly one predecessor, it can't be
866 // partially redundant.
867 BasicBlock *LoadBB = LI->getParent();
868 if (LoadBB->getSinglePredecessor())
869 return false;
870
871 Value *LoadedPtr = LI->getOperand(0);
872
873 // If the loaded operand is defined in the LoadBB, it can't be available.
Chris Lattner4e447eb2009-11-15 19:58:31 +0000874 // TODO: Could do simple PHI translation, that would be fun :)
Chris Lattner69e067f2008-11-27 05:07:53 +0000875 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
876 if (PtrOp->getParent() == LoadBB)
877 return false;
878
879 // Scan a few instructions up from the load, to see if it is obviously live at
880 // the entry to its block.
881 BasicBlock::iterator BBIt = LI;
882
Chris Lattner4e447eb2009-11-15 19:58:31 +0000883 if (Value *AvailableVal =
884 FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000885 // If the value if the load is locally available within the block, just use
886 // it. This frequently occurs for reg2mem'd allocas.
887 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000888
889 // If the returned value is the load itself, replace with an undef. This can
890 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000891 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000892 LI->replaceAllUsesWith(AvailableVal);
893 LI->eraseFromParent();
894 return true;
895 }
896
897 // Otherwise, if we scanned the whole block and got to the top of the block,
898 // we know the block is locally transparent to the load. If not, something
899 // might clobber its value.
900 if (BBIt != LoadBB->begin())
901 return false;
902
903
904 SmallPtrSet<BasicBlock*, 8> PredsScanned;
905 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
906 AvailablePredsTy AvailablePreds;
907 BasicBlock *OneUnavailablePred = 0;
908
909 // If we got here, the loaded value is transparent through to the start of the
910 // block. Check to see if it is available in any of the predecessor blocks.
911 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
912 PI != PE; ++PI) {
913 BasicBlock *PredBB = *PI;
914
915 // If we already scanned this predecessor, skip it.
916 if (!PredsScanned.insert(PredBB))
917 continue;
918
919 // Scan the predecessor to see if the value is available in the pred.
920 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000921 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000922 if (!PredAvailable) {
923 OneUnavailablePred = PredBB;
924 continue;
925 }
926
927 // If so, this load is partially redundant. Remember this info so that we
928 // can create a PHI node.
929 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
930 }
931
932 // If the loaded value isn't available in any predecessor, it isn't partially
933 // redundant.
934 if (AvailablePreds.empty()) return false;
935
936 // Okay, the loaded value is available in at least one (and maybe all!)
937 // predecessors. If the value is unavailable in more than one unique
938 // predecessor, we want to insert a merge block for those common predecessors.
939 // This ensures that we only have to insert one reload, thus not increasing
940 // code size.
941 BasicBlock *UnavailablePred = 0;
942
943 // If there is exactly one predecessor where the value is unavailable, the
944 // already computed 'OneUnavailablePred' block is it. If it ends in an
945 // unconditional branch, we know that it isn't a critical edge.
946 if (PredsScanned.size() == AvailablePreds.size()+1 &&
947 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
948 UnavailablePred = OneUnavailablePred;
949 } else if (PredsScanned.size() != AvailablePreds.size()) {
950 // Otherwise, we had multiple unavailable predecessors or we had a critical
951 // edge from the one.
952 SmallVector<BasicBlock*, 8> PredsToSplit;
953 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
954
955 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
956 AvailablePredSet.insert(AvailablePreds[i].first);
957
958 // Add all the unavailable predecessors to the PredsToSplit list.
959 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
Chris Lattnere58867e2010-06-14 19:45:43 +0000960 PI != PE; ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +0000961 BasicBlock *P = *PI;
Chris Lattnere58867e2010-06-14 19:45:43 +0000962 // If the predecessor is an indirect goto, we can't split the edge.
Gabor Greifee1f44f2010-07-12 14:10:24 +0000963 if (isa<IndirectBrInst>(P->getTerminator()))
Chris Lattnere58867e2010-06-14 19:45:43 +0000964 return false;
965
Gabor Greifee1f44f2010-07-12 14:10:24 +0000966 if (!AvailablePredSet.count(P))
967 PredsToSplit.push_back(P);
Chris Lattnere58867e2010-06-14 19:45:43 +0000968 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000969
970 // Split them out to their own block.
971 UnavailablePred =
972 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
Chris Lattner4e447eb2009-11-15 19:58:31 +0000973 "thread-pre-split", this);
Chris Lattner69e067f2008-11-27 05:07:53 +0000974 }
975
976 // If the value isn't available in all predecessors, then there will be
977 // exactly one where it isn't available. Insert a load on that edge and add
978 // it to the AvailablePreds list.
979 if (UnavailablePred) {
980 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
981 "Can't handle critical edge here!");
Chris Lattner4e447eb2009-11-15 19:58:31 +0000982 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
983 LI->getAlignment(),
Chris Lattner69e067f2008-11-27 05:07:53 +0000984 UnavailablePred->getTerminator());
985 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
986 }
987
988 // Now we know that each predecessor of this block has a value in
989 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000990 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000991
992 // Create a PHI node at the start of the block for the PRE'd load value.
993 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
994 PN->takeName(LI);
995
996 // Insert new entries into the PHI for each predecessor. A single block may
997 // have multiple entries here.
998 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
999 ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +00001000 BasicBlock *P = *PI;
Chris Lattner69e067f2008-11-27 05:07:53 +00001001 AvailablePredsTy::iterator I =
1002 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
Gabor Greifee1f44f2010-07-12 14:10:24 +00001003 std::make_pair(P, (Value*)0));
Chris Lattner69e067f2008-11-27 05:07:53 +00001004
Gabor Greifee1f44f2010-07-12 14:10:24 +00001005 assert(I != AvailablePreds.end() && I->first == P &&
Chris Lattner69e067f2008-11-27 05:07:53 +00001006 "Didn't find entry for predecessor!");
1007
1008 PN->addIncoming(I->second, I->first);
1009 }
1010
1011 //cerr << "PRE: " << *LI << *PN << "\n";
1012
1013 LI->replaceAllUsesWith(PN);
1014 LI->eraseFromParent();
1015
1016 return true;
1017}
1018
Chris Lattner5729d382009-11-07 08:05:03 +00001019/// FindMostPopularDest - The specified list contains multiple possible
1020/// threadable destinations. Pick the one that occurs the most frequently in
1021/// the list.
1022static BasicBlock *
1023FindMostPopularDest(BasicBlock *BB,
1024 const SmallVectorImpl<std::pair<BasicBlock*,
1025 BasicBlock*> > &PredToDestList) {
1026 assert(!PredToDestList.empty());
1027
1028 // Determine popularity. If there are multiple possible destinations, we
1029 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1030 // blocks with known and real destinations to threading undef. We'll handle
1031 // them later if interesting.
1032 DenseMap<BasicBlock*, unsigned> DestPopularity;
1033 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1034 if (PredToDestList[i].second)
1035 DestPopularity[PredToDestList[i].second]++;
1036
1037 // Find the most popular dest.
1038 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1039 BasicBlock *MostPopularDest = DPI->first;
1040 unsigned Popularity = DPI->second;
1041 SmallVector<BasicBlock*, 4> SamePopularity;
1042
1043 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1044 // If the popularity of this entry isn't higher than the popularity we've
1045 // seen so far, ignore it.
1046 if (DPI->second < Popularity)
1047 ; // ignore.
1048 else if (DPI->second == Popularity) {
1049 // If it is the same as what we've seen so far, keep track of it.
1050 SamePopularity.push_back(DPI->first);
1051 } else {
1052 // If it is more popular, remember it.
1053 SamePopularity.clear();
1054 MostPopularDest = DPI->first;
1055 Popularity = DPI->second;
1056 }
1057 }
1058
1059 // Okay, now we know the most popular destination. If there is more than
1060 // destination, we need to determine one. This is arbitrary, but we need
1061 // to make a deterministic decision. Pick the first one that appears in the
1062 // successor list.
1063 if (!SamePopularity.empty()) {
1064 SamePopularity.push_back(MostPopularDest);
1065 TerminatorInst *TI = BB->getTerminator();
1066 for (unsigned i = 0; ; ++i) {
1067 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1068
1069 if (std::find(SamePopularity.begin(), SamePopularity.end(),
1070 TI->getSuccessor(i)) == SamePopularity.end())
1071 continue;
1072
1073 MostPopularDest = TI->getSuccessor(i);
1074 break;
1075 }
1076 }
1077
1078 // Okay, we have finally picked the most popular destination.
1079 return MostPopularDest;
1080}
1081
Chris Lattner1c96b412009-11-12 01:37:43 +00001082bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB) {
Chris Lattner5729d382009-11-07 08:05:03 +00001083 // If threading this would thread across a loop header, don't even try to
1084 // thread the edge.
1085 if (LoopHeaders.count(BB))
1086 return false;
1087
Chris Lattner5729d382009-11-07 08:05:03 +00001088 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001089 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
Chris Lattner5729d382009-11-07 08:05:03 +00001090 return false;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001091
Chris Lattner5729d382009-11-07 08:05:03 +00001092 assert(!PredValues.empty() &&
1093 "ComputeValueKnownInPredecessors returned true with no values");
1094
David Greenefe7fe662010-01-05 01:27:19 +00001095 DEBUG(dbgs() << "IN BB: " << *BB;
Chris Lattner5729d382009-11-07 08:05:03 +00001096 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
David Greenefe7fe662010-01-05 01:27:19 +00001097 dbgs() << " BB '" << BB->getName() << "': FOUND condition = ";
Chris Lattner5729d382009-11-07 08:05:03 +00001098 if (PredValues[i].first)
David Greenefe7fe662010-01-05 01:27:19 +00001099 dbgs() << *PredValues[i].first;
Chris Lattner5729d382009-11-07 08:05:03 +00001100 else
David Greenefe7fe662010-01-05 01:27:19 +00001101 dbgs() << "UNDEF";
1102 dbgs() << " for pred '" << PredValues[i].second->getName()
Chris Lattner5729d382009-11-07 08:05:03 +00001103 << "'.\n";
1104 });
1105
1106 // Decide what we want to thread through. Convert our list of known values to
1107 // a list of known destinations for each pred. This also discards duplicate
1108 // predecessors and keeps track of the undefined inputs (which are represented
Chris Lattnere7e63fe2009-11-09 00:41:49 +00001109 // as a null dest in the PredToDestList).
Chris Lattner5729d382009-11-07 08:05:03 +00001110 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1111 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1112
1113 BasicBlock *OnlyDest = 0;
1114 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1115
1116 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1117 BasicBlock *Pred = PredValues[i].second;
1118 if (!SeenPreds.insert(Pred))
1119 continue; // Duplicate predecessor entry.
1120
1121 // If the predecessor ends with an indirect goto, we can't change its
1122 // destination.
1123 if (isa<IndirectBrInst>(Pred->getTerminator()))
1124 continue;
1125
1126 ConstantInt *Val = PredValues[i].first;
1127
1128 BasicBlock *DestBB;
1129 if (Val == 0) // Undef.
1130 DestBB = 0;
1131 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1132 DestBB = BI->getSuccessor(Val->isZero());
1133 else {
1134 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
1135 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
1136 }
1137
1138 // If we have exactly one destination, remember it for efficiency below.
1139 if (i == 0)
1140 OnlyDest = DestBB;
1141 else if (OnlyDest != DestBB)
1142 OnlyDest = MultipleDestSentinel;
1143
1144 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1145 }
1146
1147 // If all edges were unthreadable, we fail.
1148 if (PredToDestList.empty())
1149 return false;
1150
1151 // Determine which is the most common successor. If we have many inputs and
1152 // this block is a switch, we want to start by threading the batch that goes
1153 // to the most popular destination first. If we only know about one
1154 // threadable destination (the common case) we can avoid this.
1155 BasicBlock *MostPopularDest = OnlyDest;
1156
1157 if (MostPopularDest == MultipleDestSentinel)
1158 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1159
1160 // Now that we know what the most popular destination is, factor all
1161 // predecessors that will jump to it into a single predecessor.
1162 SmallVector<BasicBlock*, 16> PredsToFactor;
1163 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1164 if (PredToDestList[i].second == MostPopularDest) {
1165 BasicBlock *Pred = PredToDestList[i].first;
1166
1167 // This predecessor may be a switch or something else that has multiple
1168 // edges to the block. Factor each of these edges by listing them
1169 // according to # occurrences in PredsToFactor.
1170 TerminatorInst *PredTI = Pred->getTerminator();
1171 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1172 if (PredTI->getSuccessor(i) == BB)
1173 PredsToFactor.push_back(Pred);
1174 }
1175
1176 // If the threadable edges are branching on an undefined value, we get to pick
1177 // the destination that these predecessors should get to.
1178 if (MostPopularDest == 0)
1179 MostPopularDest = BB->getTerminator()->
1180 getSuccessor(GetBestDestForJumpOnUndef(BB));
1181
1182 // Ok, try to thread it!
1183 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1184}
Chris Lattner69e067f2008-11-27 05:07:53 +00001185
Chris Lattner77beb472010-01-11 23:41:09 +00001186/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1187/// a PHI node in the current block. See if there are any simplifications we
1188/// can do based on inputs to the phi node.
Chris Lattnerd38c14e2008-04-22 06:36:15 +00001189///
Chris Lattner77beb472010-01-11 23:41:09 +00001190bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +00001191 BasicBlock *BB = PN->getParent();
1192
Chris Lattner2249a0b2010-01-12 02:07:17 +00001193 // TODO: We could make use of this to do it once for blocks with common PHI
1194 // values.
1195 SmallVector<BasicBlock*, 1> PredBBs;
1196 PredBBs.resize(1);
1197
Chris Lattner5729d382009-11-07 08:05:03 +00001198 // If any of the predecessor blocks end in an unconditional branch, we can
Chris Lattner77beb472010-01-11 23:41:09 +00001199 // *duplicate* the conditional branch into that block in order to further
1200 // encourage jump threading and to eliminate cases where we have branch on a
1201 // phi of an icmp (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +00001202 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1203 BasicBlock *PredBB = PN->getIncomingBlock(i);
1204 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
Chris Lattner2249a0b2010-01-12 02:07:17 +00001205 if (PredBr->isUnconditional()) {
1206 PredBBs[0] = PredBB;
1207 // Try to duplicate BB into PredBB.
1208 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1209 return true;
1210 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001211 }
1212
Chris Lattner6b65f472009-10-11 04:40:21 +00001213 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001214}
1215
Chris Lattner2249a0b2010-01-12 02:07:17 +00001216/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1217/// a xor instruction in the current block. See if there are any
1218/// simplifications we can do based on inputs to the xor.
1219///
1220bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
1221 BasicBlock *BB = BO->getParent();
1222
1223 // If either the LHS or RHS of the xor is a constant, don't do this
1224 // optimization.
1225 if (isa<ConstantInt>(BO->getOperand(0)) ||
1226 isa<ConstantInt>(BO->getOperand(1)))
1227 return false;
1228
Chris Lattner2dd76572010-01-23 19:16:25 +00001229 // If the first instruction in BB isn't a phi, we won't be able to infer
1230 // anything special about any particular predecessor.
1231 if (!isa<PHINode>(BB->front()))
1232 return false;
1233
Chris Lattner2249a0b2010-01-12 02:07:17 +00001234 // If we have a xor as the branch input to this block, and we know that the
1235 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1236 // the condition into the predecessor and fix that value to true, saving some
1237 // logical ops on that path and encouraging other paths to simplify.
1238 //
1239 // This copies something like this:
1240 //
1241 // BB:
1242 // %X = phi i1 [1], [%X']
1243 // %Y = icmp eq i32 %A, %B
1244 // %Z = xor i1 %X, %Y
1245 // br i1 %Z, ...
1246 //
1247 // Into:
1248 // BB':
1249 // %Y = icmp ne i32 %A, %B
1250 // br i1 %Z, ...
1251
1252 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> XorOpValues;
1253 bool isLHS = true;
1254 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues)) {
1255 assert(XorOpValues.empty());
1256 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues))
1257 return false;
1258 isLHS = false;
1259 }
1260
1261 assert(!XorOpValues.empty() &&
1262 "ComputeValueKnownInPredecessors returned true with no values");
1263
1264 // Scan the information to see which is most popular: true or false. The
1265 // predecessors can be of the set true, false, or undef.
1266 unsigned NumTrue = 0, NumFalse = 0;
1267 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1268 if (!XorOpValues[i].first) continue; // Ignore undefs for the count.
1269 if (XorOpValues[i].first->isZero())
1270 ++NumFalse;
1271 else
1272 ++NumTrue;
1273 }
1274
1275 // Determine which value to split on, true, false, or undef if neither.
1276 ConstantInt *SplitVal = 0;
1277 if (NumTrue > NumFalse)
1278 SplitVal = ConstantInt::getTrue(BB->getContext());
1279 else if (NumTrue != 0 || NumFalse != 0)
1280 SplitVal = ConstantInt::getFalse(BB->getContext());
1281
1282 // Collect all of the blocks that this can be folded into so that we can
1283 // factor this once and clone it once.
1284 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1285 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1286 if (XorOpValues[i].first != SplitVal && XorOpValues[i].first != 0) continue;
1287
1288 BlocksToFoldInto.push_back(XorOpValues[i].second);
1289 }
1290
Chris Lattner2dd76572010-01-23 19:16:25 +00001291 // If we inferred a value for all of the predecessors, then duplication won't
1292 // help us. However, we can just replace the LHS or RHS with the constant.
1293 if (BlocksToFoldInto.size() ==
1294 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1295 if (SplitVal == 0) {
1296 // If all preds provide undef, just nuke the xor, because it is undef too.
1297 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1298 BO->eraseFromParent();
1299 } else if (SplitVal->isZero()) {
1300 // If all preds provide 0, replace the xor with the other input.
1301 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1302 BO->eraseFromParent();
1303 } else {
1304 // If all preds provide 1, set the computed value to 1.
1305 BO->setOperand(!isLHS, SplitVal);
1306 }
1307
1308 return true;
1309 }
1310
Chris Lattner2249a0b2010-01-12 02:07:17 +00001311 // Try to duplicate BB into PredBB.
Chris Lattner797c4402010-01-12 02:07:50 +00001312 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
Chris Lattner2249a0b2010-01-12 02:07:17 +00001313}
1314
1315
Chris Lattner78c552e2009-10-11 07:24:57 +00001316/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1317/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1318/// NewPred using the entries from OldPred (suitably mapped).
1319static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1320 BasicBlock *OldPred,
1321 BasicBlock *NewPred,
1322 DenseMap<Instruction*, Value*> &ValueMap) {
1323 for (BasicBlock::iterator PNI = PHIBB->begin();
1324 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1325 // Ok, we have a PHI node. Figure out what the incoming value was for the
1326 // DestBlock.
1327 Value *IV = PN->getIncomingValueForBlock(OldPred);
1328
1329 // Remap the value if necessary.
1330 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1331 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1332 if (I != ValueMap.end())
1333 IV = I->second;
1334 }
1335
1336 PN->addIncoming(IV, NewPred);
1337 }
1338}
Chris Lattner6bf77502008-04-22 07:05:46 +00001339
Chris Lattner5729d382009-11-07 08:05:03 +00001340/// ThreadEdge - We have decided that it is safe and profitable to factor the
1341/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1342/// across BB. Transform the IR to reflect this change.
1343bool JumpThreading::ThreadEdge(BasicBlock *BB,
1344 const SmallVectorImpl<BasicBlock*> &PredBBs,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001345 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001346 // If threading to the same block as we come from, we would infinite loop.
1347 if (SuccBB == BB) {
David Greenefe7fe662010-01-05 01:27:19 +00001348 DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001349 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001350 return false;
1351 }
1352
1353 // If threading this would thread across a loop header, don't thread the edge.
1354 // See the comments above FindLoopHeaders for justifications and caveats.
1355 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001356 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001357 << "' to dest BB '" << SuccBB->getName()
1358 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001359 return false;
1360 }
1361
Chris Lattner78c552e2009-10-11 07:24:57 +00001362 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1363 if (JumpThreadCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001364 DEBUG(dbgs() << " Not threading BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001365 << "' - Cost is too high: " << JumpThreadCost << "\n");
1366 return false;
1367 }
1368
Chris Lattner5729d382009-11-07 08:05:03 +00001369 // And finally, do it! Start by factoring the predecessors is needed.
1370 BasicBlock *PredBB;
1371 if (PredBBs.size() == 1)
1372 PredBB = PredBBs[0];
1373 else {
David Greenefe7fe662010-01-05 01:27:19 +00001374 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
Chris Lattner5729d382009-11-07 08:05:03 +00001375 << " common predecessors.\n");
1376 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1377 ".thr_comm", this);
1378 }
1379
Mike Stumpfe095f32009-05-04 18:40:41 +00001380 // And finally, do it!
David Greenefe7fe662010-01-05 01:27:19 +00001381 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001382 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001383 << ", across block:\n "
1384 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001385
Owen Andersonc809d902010-09-14 20:57:41 +00001386 LVI->threadEdge(PredBB, BB, SuccBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001387
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001388 // We are going to have to map operands from the original BB block to the new
1389 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1390 // account for entry from PredBB.
1391 DenseMap<Instruction*, Value*> ValueMapping;
1392
Owen Anderson1d0be152009-08-13 21:58:54 +00001393 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1394 BB->getName()+".thread",
1395 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001396 NewBB->moveAfter(PredBB);
1397
1398 BasicBlock::iterator BI = BB->begin();
1399 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1400 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1401
1402 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1403 // mapping and using it to remap operands in the cloned instructions.
1404 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001405 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001406 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001407 NewBB->getInstList().push_back(New);
1408 ValueMapping[BI] = New;
1409
1410 // Remap operands to patch up intra-block references.
1411 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001412 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1413 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1414 if (I != ValueMapping.end())
1415 New->setOperand(i, I->second);
1416 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001417 }
1418
1419 // We didn't copy the terminator from BB over to NewBB, because there is now
1420 // an unconditional jump to SuccBB. Insert the unconditional jump.
1421 BranchInst::Create(SuccBB, NewBB);
1422
1423 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1424 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001425 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001426
Chris Lattner433a0db2009-10-10 09:05:58 +00001427 // If there were values defined in BB that are used outside the block, then we
1428 // now have to update all uses of the value to use either the original value,
1429 // the cloned value, or some PHI derived value. This can require arbitrary
1430 // PHI insertion, of which we are prepared to do, clean these up now.
1431 SSAUpdater SSAUpdate;
1432 SmallVector<Use*, 16> UsesToRename;
1433 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1434 // Scan all uses of this instruction to see if it is used outside of its
1435 // block, and if so, record them in UsesToRename.
1436 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1437 ++UI) {
1438 Instruction *User = cast<Instruction>(*UI);
1439 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1440 if (UserPN->getIncomingBlock(UI) == BB)
1441 continue;
1442 } else if (User->getParent() == BB)
1443 continue;
1444
1445 UsesToRename.push_back(&UI.getUse());
1446 }
1447
1448 // If there are no uses outside the block, we're done with this instruction.
1449 if (UsesToRename.empty())
1450 continue;
1451
David Greenefe7fe662010-01-05 01:27:19 +00001452 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001453
1454 // We found a use of I outside of BB. Rename all uses of I that are outside
1455 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1456 // with the two values we know.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001457 SSAUpdate.Initialize(I->getType(), I->getName());
Chris Lattner433a0db2009-10-10 09:05:58 +00001458 SSAUpdate.AddAvailableValue(BB, I);
1459 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1460
1461 while (!UsesToRename.empty())
1462 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001463 DEBUG(dbgs() << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001464 }
1465
1466
Chris Lattneref0c6742008-12-01 04:48:07 +00001467 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001468 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1469 // us to simplify any PHI nodes in BB.
1470 TerminatorInst *PredTerm = PredBB->getTerminator();
1471 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1472 if (PredTerm->getSuccessor(i) == BB) {
Owen Anderson36c4deb2010-09-29 20:34:41 +00001473 BB->removePredecessor(PredBB, true);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001474 PredTerm->setSuccessor(i, NewBB);
1475 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001476
1477 // At this point, the IR is fully up to date and consistent. Do a quick scan
1478 // over the new instructions and zap any that are constants or dead. This
1479 // frequently happens because of phi translation.
Chris Lattner972a46c2010-01-12 20:41:47 +00001480 SimplifyInstructionsInBlock(NewBB, TD);
Mike Stumpfe095f32009-05-04 18:40:41 +00001481
1482 // Threaded an edge!
1483 ++NumThreads;
1484 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001485}
Chris Lattner78c552e2009-10-11 07:24:57 +00001486
1487/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1488/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1489/// If we can duplicate the contents of BB up into PredBB do so now, this
1490/// improves the odds that the branch will be on an analyzable instruction like
1491/// a compare.
1492bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
Chris Lattner2249a0b2010-01-12 02:07:17 +00001493 const SmallVectorImpl<BasicBlock *> &PredBBs) {
1494 assert(!PredBBs.empty() && "Can't handle an empty set");
1495
Chris Lattner78c552e2009-10-11 07:24:57 +00001496 // If BB is a loop header, then duplicating this block outside the loop would
1497 // cause us to transform this into an irreducible loop, don't do this.
1498 // See the comments above FindLoopHeaders for justifications and caveats.
1499 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001500 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
Chris Lattner2249a0b2010-01-12 02:07:17 +00001501 << "' into predecessor block '" << PredBBs[0]->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001502 << "' - it might create an irreducible loop!\n");
1503 return false;
1504 }
1505
1506 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1507 if (DuplicationCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001508 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001509 << "' - Cost is too high: " << DuplicationCost << "\n");
1510 return false;
1511 }
1512
Chris Lattner2249a0b2010-01-12 02:07:17 +00001513 // And finally, do it! Start by factoring the predecessors is needed.
1514 BasicBlock *PredBB;
1515 if (PredBBs.size() == 1)
1516 PredBB = PredBBs[0];
1517 else {
1518 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
1519 << " common predecessors.\n");
1520 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1521 ".thr_comm", this);
1522 }
1523
Chris Lattner78c552e2009-10-11 07:24:57 +00001524 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1525 // of PredBB.
David Greenefe7fe662010-01-05 01:27:19 +00001526 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
Chris Lattner78c552e2009-10-11 07:24:57 +00001527 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1528 << DuplicationCost << " block is:" << *BB << "\n");
1529
Chris Lattner2249a0b2010-01-12 02:07:17 +00001530 // Unless PredBB ends with an unconditional branch, split the edge so that we
1531 // can just clone the bits from BB into the end of the new PredBB.
Chris Lattnerd6688392010-01-23 19:21:31 +00001532 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
Chris Lattner2249a0b2010-01-12 02:07:17 +00001533
Chris Lattnerd6688392010-01-23 19:21:31 +00001534 if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
Chris Lattner2249a0b2010-01-12 02:07:17 +00001535 PredBB = SplitEdge(PredBB, BB, this);
1536 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1537 }
1538
Chris Lattner78c552e2009-10-11 07:24:57 +00001539 // We are going to have to map operands from the original BB block into the
1540 // PredBB block. Evaluate PHI nodes in BB.
1541 DenseMap<Instruction*, Value*> ValueMapping;
1542
1543 BasicBlock::iterator BI = BB->begin();
1544 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1545 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1546
Chris Lattner78c552e2009-10-11 07:24:57 +00001547 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1548 // mapping and using it to remap operands in the cloned instructions.
1549 for (; BI != BB->end(); ++BI) {
1550 Instruction *New = BI->clone();
Chris Lattner78c552e2009-10-11 07:24:57 +00001551
1552 // Remap operands to patch up intra-block references.
1553 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1554 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1555 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1556 if (I != ValueMapping.end())
1557 New->setOperand(i, I->second);
1558 }
Chris Lattner972a46c2010-01-12 20:41:47 +00001559
1560 // If this instruction can be simplified after the operands are updated,
1561 // just use the simplified value instead. This frequently happens due to
1562 // phi translation.
1563 if (Value *IV = SimplifyInstruction(New, TD)) {
1564 delete New;
1565 ValueMapping[BI] = IV;
1566 } else {
1567 // Otherwise, insert the new instruction into the block.
1568 New->setName(BI->getName());
1569 PredBB->getInstList().insert(OldPredBranch, New);
1570 ValueMapping[BI] = New;
1571 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001572 }
1573
1574 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1575 // add entries to the PHI nodes for branch from PredBB now.
1576 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1577 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1578 ValueMapping);
1579 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1580 ValueMapping);
1581
1582 // If there were values defined in BB that are used outside the block, then we
1583 // now have to update all uses of the value to use either the original value,
1584 // the cloned value, or some PHI derived value. This can require arbitrary
1585 // PHI insertion, of which we are prepared to do, clean these up now.
1586 SSAUpdater SSAUpdate;
1587 SmallVector<Use*, 16> UsesToRename;
1588 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1589 // Scan all uses of this instruction to see if it is used outside of its
1590 // block, and if so, record them in UsesToRename.
1591 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1592 ++UI) {
1593 Instruction *User = cast<Instruction>(*UI);
1594 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1595 if (UserPN->getIncomingBlock(UI) == BB)
1596 continue;
1597 } else if (User->getParent() == BB)
1598 continue;
1599
1600 UsesToRename.push_back(&UI.getUse());
1601 }
1602
1603 // If there are no uses outside the block, we're done with this instruction.
1604 if (UsesToRename.empty())
1605 continue;
1606
David Greenefe7fe662010-01-05 01:27:19 +00001607 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001608
1609 // We found a use of I outside of BB. Rename all uses of I that are outside
1610 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1611 // with the two values we know.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001612 SSAUpdate.Initialize(I->getType(), I->getName());
Chris Lattner78c552e2009-10-11 07:24:57 +00001613 SSAUpdate.AddAvailableValue(BB, I);
1614 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1615
1616 while (!UsesToRename.empty())
1617 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001618 DEBUG(dbgs() << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001619 }
1620
1621 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1622 // that we nuked.
Owen Anderson36c4deb2010-09-29 20:34:41 +00001623 BB->removePredecessor(PredBB, true);
Chris Lattner78c552e2009-10-11 07:24:57 +00001624
1625 // Remove the unconditional branch at the end of the PredBB block.
1626 OldPredBranch->eraseFromParent();
1627
1628 ++NumDupes;
1629 return true;
1630}
1631
1632