blob: 70e6cfdfb5d4635f9eed06341aa421437a2f5a38 [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 Anderson2ab36d32010-10-12 19:48:12 +0000124INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
125 "Jump Threading", false, false)
126INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
127INITIALIZE_PASS_END(JumpThreading, "jump-threading",
Owen Andersonce665bd2010-10-07 22:25:06 +0000128 "Jump Threading", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000129
Chris Lattner8383a7b2008-04-20 20:35:01 +0000130// Public interface to the Jump Threading pass
131FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
132
133/// runOnFunction - Top level algorithm.
134///
135bool JumpThreading::runOnFunction(Function &F) {
David Greenefe7fe662010-01-05 01:27:19 +0000136 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000137 TD = getAnalysisIfAvailable<TargetData>();
Owen Andersonc809d902010-09-14 20:57:41 +0000138 LVI = &getAnalysis<LazyValueInfo>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000139
Mike Stumpfe095f32009-05-04 18:40:41 +0000140 FindLoopHeaders(F);
141
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000142 bool Changed, EverChanged = false;
143 do {
144 Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000145 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
146 BasicBlock *BB = I;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000147 // Thread all of the branches we can over this block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000148 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000149 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000150
151 ++I;
152
153 // If the block is trivially dead, zap it. This eliminates the successor
154 // edges which simplifies the CFG.
155 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000156 BB != &BB->getParent()->getEntryBlock()) {
David Greenefe7fe662010-01-05 01:27:19 +0000157 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000158 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000159 LoopHeaders.erase(BB);
Owen Andersonc809d902010-09-14 20:57:41 +0000160 LVI->eraseBlock(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000161 DeleteDeadBlock(BB);
162 Changed = true;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000163 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
164 // Can't thread an unconditional jump, but if the block is "almost
165 // empty", we can replace uses of it with uses of the successor and make
166 // this dead.
167 if (BI->isUnconditional() &&
168 BB != &BB->getParent()->getEntryBlock()) {
169 BasicBlock::iterator BBI = BB->getFirstNonPHI();
170 // Ignore dbg intrinsics.
171 while (isa<DbgInfoIntrinsic>(BBI))
172 ++BBI;
173 // If the terminator is the only non-phi instruction, try to nuke it.
174 if (BBI->isTerminator()) {
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000175 // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
176 // block, we have to make sure it isn't in the LoopHeaders set. We
Chris Lattner46875c02009-12-01 06:04:43 +0000177 // reinsert afterward if needed.
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000178 bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000179 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerf3183f62009-11-10 21:40:01 +0000180
Owen Anderson00ac77e2010-08-18 18:39:01 +0000181 // FIXME: It is always conservatively correct to drop the info
182 // for a block even if it doesn't get erased. This isn't totally
183 // awesome, but it allows us to use AssertingVH to prevent nasty
184 // dangling pointer issues within LazyValueInfo.
Owen Andersonc809d902010-09-14 20:57:41 +0000185 LVI->eraseBlock(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000186 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
Chris Lattnerf3183f62009-11-10 21:40:01 +0000187 Changed = true;
Chris Lattner46875c02009-12-01 06:04:43 +0000188 // If we deleted BB and BB was the header of a loop, then the
189 // successor is now the header of the loop.
190 BB = Succ;
191 }
192
193 if (ErasedFromLoopHeaders)
Chris Lattnerf3183f62009-11-10 21:40:01 +0000194 LoopHeaders.insert(BB);
195 }
196 }
Chris Lattner421fa9e2008-12-03 07:48:08 +0000197 }
198 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000199 EverChanged |= Changed;
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000200 } while (Changed);
Mike Stumpfe095f32009-05-04 18:40:41 +0000201
202 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000203 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000204}
Chris Lattner177480b2008-04-20 21:13:06 +0000205
Chris Lattner78c552e2009-10-11 07:24:57 +0000206/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
207/// thread across it.
208static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
209 /// Ignore PHI nodes, these will be flattened when duplication happens.
210 BasicBlock::const_iterator I = BB->getFirstNonPHI();
211
Chris Lattnerb14b88a2009-11-11 00:21:58 +0000212 // FIXME: THREADING will delete values that are just used to compute the
213 // branch, so they shouldn't count against the duplication cost.
214
215
Chris Lattner78c552e2009-10-11 07:24:57 +0000216 // Sum up the cost of each instruction until we get to the terminator. Don't
217 // include the terminator because the copy won't include it.
218 unsigned Size = 0;
219 for (; !isa<TerminatorInst>(I); ++I) {
220 // Debugger intrinsics don't incur code size.
221 if (isa<DbgInfoIntrinsic>(I)) continue;
222
223 // If this is a pointer->pointer bitcast, it is free.
Duncan Sands1df98592010-02-16 11:11:14 +0000224 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000225 continue;
226
227 // All other instructions count for at least one unit.
228 ++Size;
229
230 // Calls are more expensive. If they are non-intrinsic calls, we model them
231 // as having cost of 4. If they are a non-vector intrinsic, we model them
232 // as having cost of 2 total, and if they are a vector intrinsic, we model
233 // them as having cost 1.
234 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
235 if (!isa<IntrinsicInst>(CI))
236 Size += 3;
Duncan Sands1df98592010-02-16 11:11:14 +0000237 else if (!CI->getType()->isVectorTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000238 Size += 1;
239 }
240 }
241
242 // Threading through a switch statement is particularly profitable. If this
243 // block ends in a switch, decrease its cost to make it more likely to happen.
244 if (isa<SwitchInst>(I))
245 Size = Size > 6 ? Size-6 : 0;
246
247 return Size;
248}
249
Mike Stumpfe095f32009-05-04 18:40:41 +0000250/// FindLoopHeaders - We do not want jump threading to turn proper loop
251/// structures into irreducible loops. Doing this breaks up the loop nesting
252/// hierarchy and pessimizes later transformations. To prevent this from
253/// happening, we first have to find the loop headers. Here we approximate this
254/// by finding targets of backedges in the CFG.
255///
256/// Note that there definitely are cases when we want to allow threading of
257/// edges across a loop header. For example, threading a jump from outside the
258/// loop (the preheader) to an exit block of the loop is definitely profitable.
259/// It is also almost always profitable to thread backedges from within the loop
260/// to exit blocks, and is often profitable to thread backedges to other blocks
261/// within the loop (forming a nested loop). This simple analysis is not rich
262/// enough to track all of these properties and keep it up-to-date as the CFG
263/// mutates, so we don't allow any of these transformations.
264///
265void JumpThreading::FindLoopHeaders(Function &F) {
266 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
267 FindFunctionBackedges(F, Edges);
268
269 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
270 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
271}
272
Owen Anderson0eb355a2010-08-31 20:26:04 +0000273// Helper method for ComputeValueKnownInPredecessors. If Value is a
274// ConstantInt, push it. If it's an undef, push 0. Otherwise, do nothing.
275static void PushConstantIntOrUndef(SmallVectorImpl<std::pair<ConstantInt*,
276 BasicBlock*> > &Result,
277 Constant *Value, BasicBlock* BB){
278 if (ConstantInt *FoldedCInt = dyn_cast<ConstantInt>(Value))
279 Result.push_back(std::make_pair(FoldedCInt, BB));
280 else if (isa<UndefValue>(Value))
281 Result.push_back(std::make_pair((ConstantInt*)0, BB));
282}
283
Chris Lattner5729d382009-11-07 08:05:03 +0000284/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
285/// if we can infer that the value is a known ConstantInt in any of our
Chris Lattnere7e63fe2009-11-09 00:41:49 +0000286/// predecessors. If so, return the known list of value and pred BB in the
Chris Lattner5729d382009-11-07 08:05:03 +0000287/// result vector. If a value is known to be undef, it is returned as null.
288///
Chris Lattner5729d382009-11-07 08:05:03 +0000289/// This returns true if there were any known values.
290///
Chris Lattner5729d382009-11-07 08:05:03 +0000291bool JumpThreading::
292ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
Owen Anderson9ba35362010-08-31 19:24:27 +0000293 // This method walks up use-def chains recursively. Because of this, we could
294 // get into an infinite loop going around loops in the use-def chain. To
295 // prevent this, keep track of what (value, block) pairs we've already visited
296 // and terminate the search if we loop back to them
Owen Andersoncb211902010-08-31 07:36:34 +0000297 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
298 return false;
299
Owen Anderson9ba35362010-08-31 19:24:27 +0000300 // An RAII help to remove this pair from the recursion set once the recursion
301 // stack pops back out again.
302 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
303
Chris Lattner5729d382009-11-07 08:05:03 +0000304 // If V is a constantint, then it is known in all predecessors.
305 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
306 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000307
308 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
309 Result.push_back(std::make_pair(CI, *PI));
Owen Andersoncb211902010-08-31 07:36:34 +0000310
Chris Lattner5729d382009-11-07 08:05:03 +0000311 return true;
312 }
313
314 // If V is a non-instruction value, or an instruction in a different block,
315 // then it can't be derived from a PHI.
316 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000317 if (I == 0 || I->getParent() != BB) {
318
319 // Okay, if this is a live-in value, see if it has a known value at the end
320 // of any of our predecessors.
321 //
322 // FIXME: This should be an edge property, not a block end property.
323 /// TODO: Per PR2563, we could infer value range information about a
324 /// predecessor based on its terminator.
325 //
Owen Andersonc809d902010-09-14 20:57:41 +0000326 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
327 // "I" is a non-local compare-with-a-constant instruction. This would be
328 // able to handle value inequalities better, for example if the compare is
329 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
330 // Perhaps getConstantOnEdge should be smart enough to do this?
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000331
Owen Andersonc809d902010-09-14 20:57:41 +0000332 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
333 BasicBlock *P = *PI;
334 // If the value is known by LazyValueInfo to be a constant in a
335 // predecessor, use that information to try to thread this block.
336 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
337 if (PredCst == 0 ||
338 (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
339 continue;
340
341 Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), P));
342 }
343
344 return !Result.empty();
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000345 }
Chris Lattner5729d382009-11-07 08:05:03 +0000346
347 /// If I is a PHI node, then we know the incoming values for any constants.
348 if (PHINode *PN = dyn_cast<PHINode>(I)) {
349 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
350 Value *InVal = PN->getIncomingValue(i);
351 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
352 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
353 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
Owen Andersonc809d902010-09-14 20:57:41 +0000354 } else {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000355 Constant *CI = LVI->getConstantOnEdge(InVal,
356 PN->getIncomingBlock(i), BB);
Owen Anderson327ca7b2010-08-30 23:22:36 +0000357 // LVI returns null is no value could be determined.
358 if (!CI) continue;
Owen Anderson0eb355a2010-08-31 20:26:04 +0000359 PushConstantIntOrUndef(Result, CI, PN->getIncomingBlock(i));
Chris Lattner5729d382009-11-07 08:05:03 +0000360 }
361 }
Owen Andersoncb211902010-08-31 07:36:34 +0000362
Chris Lattner5729d382009-11-07 08:05:03 +0000363 return !Result.empty();
364 }
365
366 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
367
368 // Handle some boolean conditions.
369 if (I->getType()->getPrimitiveSizeInBits() == 1) {
370 // X | true -> true
371 // X & false -> false
372 if (I->getOpcode() == Instruction::Or ||
373 I->getOpcode() == Instruction::And) {
374 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
375 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
376
Owen Anderson9ba35362010-08-31 19:24:27 +0000377 if (LHSVals.empty() && RHSVals.empty())
Chris Lattner5729d382009-11-07 08:05:03 +0000378 return false;
379
380 ConstantInt *InterestingVal;
381 if (I->getOpcode() == Instruction::Or)
382 InterestingVal = ConstantInt::getTrue(I->getContext());
383 else
384 InterestingVal = ConstantInt::getFalse(I->getContext());
385
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000386 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
387
Chris Lattner1e452652010-02-11 04:40:44 +0000388 // Scan for the sentinel. If we find an undef, force it to the
389 // interesting value: x|undef -> true and x&undef -> false.
Chris Lattner5729d382009-11-07 08:05:03 +0000390 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000391 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) {
Chris Lattner5729d382009-11-07 08:05:03 +0000392 Result.push_back(LHSVals[i]);
Chris Lattner1e452652010-02-11 04:40:44 +0000393 Result.back().first = InterestingVal;
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000394 LHSKnownBBs.insert(LHSVals[i].second);
Chris Lattner1e452652010-02-11 04:40:44 +0000395 }
Chris Lattner5729d382009-11-07 08:05:03 +0000396 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000397 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) {
Chris Lattner0a961442010-07-12 00:47:34 +0000398 // If we already inferred a value for this block on the LHS, don't
399 // re-add it.
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000400 if (!LHSKnownBBs.count(RHSVals[i].second)) {
Chris Lattner0a961442010-07-12 00:47:34 +0000401 Result.push_back(RHSVals[i]);
402 Result.back().first = InterestingVal;
403 }
Chris Lattner1e452652010-02-11 04:40:44 +0000404 }
Owen Andersoncb211902010-08-31 07:36:34 +0000405
Chris Lattner5729d382009-11-07 08:05:03 +0000406 return !Result.empty();
407 }
408
Chris Lattner055d0462009-11-10 22:39:16 +0000409 // Handle the NOT form of XOR.
410 if (I->getOpcode() == Instruction::Xor &&
411 isa<ConstantInt>(I->getOperand(1)) &&
412 cast<ConstantInt>(I->getOperand(1))->isOne()) {
413 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result);
Owen Anderson9ba35362010-08-31 19:24:27 +0000414 if (Result.empty())
Chris Lattner055d0462009-11-10 22:39:16 +0000415 return false;
416
417 // Invert the known values.
418 for (unsigned i = 0, e = Result.size(); i != e; ++i)
Chris Lattner1fb56302009-11-15 19:57:43 +0000419 if (Result[i].first)
420 Result[i].first =
421 cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
Owen Andersoncb211902010-08-31 07:36:34 +0000422
Chris Lattner055d0462009-11-10 22:39:16 +0000423 return true;
424 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000425
426 // Try to simplify some other binary operator values.
427 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Owen Anderson0eb355a2010-08-31 20:26:04 +0000428 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000429 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
430 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals);
Owen Andersoncb211902010-08-31 07:36:34 +0000431
432 // Try to use constant folding to simplify the binary operator.
433 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Chris Lattner906a6752010-09-05 20:03:09 +0000434 Constant *V = LHSVals[i].first;
435 if (V == 0) V = UndefValue::get(BO->getType());
Owen Anderson0eb355a2010-08-31 20:26:04 +0000436 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
Owen Andersoncb211902010-08-31 07:36:34 +0000437
Owen Anderson0eb355a2010-08-31 20:26:04 +0000438 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Andersoncb211902010-08-31 07:36:34 +0000439 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000440 }
Owen Andersoncb211902010-08-31 07:36:34 +0000441
Owen Andersoncb211902010-08-31 07:36:34 +0000442 return !Result.empty();
Chris Lattner5729d382009-11-07 08:05:03 +0000443 }
444
445 // Handle compare with phi operand, where the PHI is defined in this block.
446 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
447 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
448 if (PN && PN->getParent() == BB) {
449 // We can do this simplification if any comparisons fold to true or false.
450 // See if any do.
451 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
452 BasicBlock *PredBB = PN->getIncomingBlock(i);
453 Value *LHS = PN->getIncomingValue(i);
454 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
455
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000456 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
Chris Lattner66c04c42009-11-12 05:24:05 +0000457 if (Res == 0) {
Owen Andersonc809d902010-09-14 20:57:41 +0000458 if (!isa<Constant>(RHS))
Chris Lattner66c04c42009-11-12 05:24:05 +0000459 continue;
460
461 LazyValueInfo::Tristate
462 ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
463 cast<Constant>(RHS), PredBB, BB);
464 if (ResT == LazyValueInfo::Unknown)
465 continue;
466 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
467 }
Chris Lattner5729d382009-11-07 08:05:03 +0000468
Owen Anderson0eb355a2010-08-31 20:26:04 +0000469 if (Constant *ConstRes = dyn_cast<Constant>(Res))
470 PushConstantIntOrUndef(Result, ConstRes, PredBB);
Chris Lattner5729d382009-11-07 08:05:03 +0000471 }
472
473 return !Result.empty();
474 }
475
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000476
477 // If comparing a live-in value against a constant, see if we know the
478 // live-in value on any predecessors.
Owen Andersonc809d902010-09-14 20:57:41 +0000479 if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000480 if (!isa<Instruction>(Cmp->getOperand(0)) ||
Owen Anderson327ca7b2010-08-30 23:22:36 +0000481 cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000482 Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
Gabor Greifee1f44f2010-07-12 14:10:24 +0000483
Owen Anderson62efd3b2010-08-26 17:40:24 +0000484 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
485 BasicBlock *P = *PI;
486 // If the value is known by LazyValueInfo to be a constant in a
487 // predecessor, use that information to try to thread this block.
488 LazyValueInfo::Tristate Res =
489 LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
490 RHSCst, P, BB);
491 if (Res == LazyValueInfo::Unknown)
492 continue;
Chris Lattner0e0ff292009-11-12 04:37:50 +0000493
Owen Anderson62efd3b2010-08-26 17:40:24 +0000494 Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
495 Result.push_back(std::make_pair(cast<ConstantInt>(ResC), P));
496 }
497
498 return !Result.empty();
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000499 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000500
Owen Andersoncb211902010-08-31 07:36:34 +0000501 // Try to find a constant value for the LHS of a comparison,
Owen Anderson62efd3b2010-08-26 17:40:24 +0000502 // and evaluate it statically if we can.
Owen Anderson327ca7b2010-08-30 23:22:36 +0000503 if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000504 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
505 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
506
Owen Anderson62efd3b2010-08-26 17:40:24 +0000507 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Chris Lattner906a6752010-09-05 20:03:09 +0000508 Constant *V = LHSVals[i].first;
509 if (V == 0) V = UndefValue::get(CmpConst->getType());
Owen Anderson0eb355a2010-08-31 20:26:04 +0000510 Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
511 V, CmpConst);
512 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Anderson62efd3b2010-08-26 17:40:24 +0000513 }
514
515 return !Result.empty();
516 }
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000517 }
Chris Lattner5729d382009-11-07 08:05:03 +0000518 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000519
Owen Andersonc809d902010-09-14 20:57:41 +0000520 // If all else fails, see if LVI can figure out a constant value for us.
521 Constant *CI = LVI->getConstant(V, BB);
522 ConstantInt *CInt = dyn_cast_or_null<ConstantInt>(CI);
523 if (CInt) {
524 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
525 Result.push_back(std::make_pair(CInt, *PI));
Owen Anderson62efd3b2010-08-26 17:40:24 +0000526 }
Owen Andersonc809d902010-09-14 20:57:41 +0000527
528 return !Result.empty();
Chris Lattner5729d382009-11-07 08:05:03 +0000529}
530
531
Chris Lattner6bf77502008-04-22 07:05:46 +0000532
Chris Lattnere33583b2009-10-11 04:18:15 +0000533/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
534/// in an undefined jump, decide which block is best to revector to.
535///
536/// Since we can pick an arbitrary destination, we pick the successor with the
537/// fewest predecessors. This should reduce the in-degree of the others.
538///
539static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
540 TerminatorInst *BBTerm = BB->getTerminator();
541 unsigned MinSucc = 0;
542 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
543 // Compute the successor with the minimum number of predecessors.
544 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
545 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
546 TestBB = BBTerm->getSuccessor(i);
547 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
548 if (NumPreds < MinNumPreds)
549 MinSucc = i;
550 }
551
552 return MinSucc;
553}
554
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000555/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000556/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000557bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner8231fd12010-01-23 18:56:07 +0000558 // If the block is trivially dead, just return and let the caller nuke it.
559 // This simplifies other transformations.
560 if (pred_begin(BB) == pred_end(BB) &&
561 BB != &BB->getParent()->getEntryBlock())
562 return false;
563
Chris Lattner69e067f2008-11-27 05:07:53 +0000564 // If this block has a single predecessor, and if that pred has a single
565 // successor, merge the blocks. This encourages recursive jump threading
566 // because now the condition in this block can be threaded through
567 // predecessors of our predecessor block.
Chris Lattner5729d382009-11-07 08:05:03 +0000568 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000569 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
570 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000571 // If SinglePred was a loop header, BB becomes one.
572 if (LoopHeaders.erase(SinglePred))
573 LoopHeaders.insert(BB);
574
Chris Lattner3d86d242008-11-27 19:25:19 +0000575 // Remember if SinglePred was the entry block of the function. If so, we
576 // will need to move BB back to the entry position.
577 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Owen Andersonc809d902010-09-14 20:57:41 +0000578 LVI->eraseBlock(SinglePred);
Chris Lattner69e067f2008-11-27 05:07:53 +0000579 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000580
581 if (isEntry && BB != &BB->getParent()->getEntryBlock())
582 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000583 return true;
584 }
Chris Lattner5729d382009-11-07 08:05:03 +0000585 }
586
587 // Look to see if the terminator is a branch of switch, if not we can't thread
588 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000589 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000590 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
591 // Can't thread an unconditional jump.
592 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000593 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000594 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000595 Condition = SI->getCondition();
596 else
597 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000598
599 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000600 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000601 // other blocks.
602 if (isa<ConstantInt>(Condition)) {
David Greenefe7fe662010-01-05 01:27:19 +0000603 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000604 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000605 ++NumFolds;
606 ConstantFoldTerminator(BB);
607 return true;
608 }
609
Chris Lattner421fa9e2008-12-03 07:48:08 +0000610 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000611 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000612 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000613 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000614
615 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000616 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000617 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000618 if (i == BestSucc) continue;
Owen Anderson36c4deb2010-09-29 20:34:41 +0000619 BBTerm->getSuccessor(i)->removePredecessor(BB, true);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000620 }
621
David Greenefe7fe662010-01-05 01:27:19 +0000622 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000623 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000624 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000625 BBTerm->eraseFromParent();
626 return true;
627 }
628
629 Instruction *CondInst = dyn_cast<Instruction>(Condition);
630
Chris Lattner421fa9e2008-12-03 07:48:08 +0000631 // All the rest of our checks depend on the condition being an instruction.
Chris Lattner87e9f592009-11-12 01:41:34 +0000632 if (CondInst == 0) {
633 // FIXME: Unify this with code below.
Owen Andersonc809d902010-09-14 20:57:41 +0000634 if (ProcessThreadableEdges(Condition, BB))
Chris Lattner87e9f592009-11-12 01:41:34 +0000635 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000636 return false;
Chris Lattner87e9f592009-11-12 01:41:34 +0000637 }
638
Chris Lattner421fa9e2008-12-03 07:48:08 +0000639
Nick Lewycky9683f182009-06-19 04:56:29 +0000640 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Owen Anderson660cab32010-08-27 17:12:29 +0000641 // For a comparison where the LHS is outside this block, it's possible
Owen Andersonfc2fb172010-08-27 20:32:56 +0000642 // that we've branched on it before. Used LVI to see if we can simplify
Owen Anderson660cab32010-08-27 17:12:29 +0000643 // the branch based on that.
644 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
645 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
Owen Andersonc1bdac62010-08-31 18:48:48 +0000646 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Owen Andersonc809d902010-09-14 20:57:41 +0000647 if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
Owen Anderson660cab32010-08-27 17:12:29 +0000648 (!isa<Instruction>(CondCmp->getOperand(0)) ||
649 cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
650 // For predecessor edge, determine if the comparison is true or false
651 // on that edge. If they're all true or all false, we can simplify the
652 // branch.
653 // FIXME: We could handle mixed true/false by duplicating code.
Owen Andersonc1bdac62010-08-31 18:48:48 +0000654 LazyValueInfo::Tristate Baseline =
655 LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
656 CondConst, *PI, BB);
657 if (Baseline != LazyValueInfo::Unknown) {
658 // Check that all remaining incoming values match the first one.
659 while (++PI != PE) {
Chris Lattnerbdabacd2010-09-05 20:10:47 +0000660 LazyValueInfo::Tristate Ret =
661 LVI->getPredicateOnEdge(CondCmp->getPredicate(),
662 CondCmp->getOperand(0), CondConst, *PI, BB);
Owen Andersonc1bdac62010-08-31 18:48:48 +0000663 if (Ret != Baseline) break;
664 }
665
666 // If we terminated early, then one of the values didn't match.
667 if (PI == PE) {
668 unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
669 unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
Owen Anderson36c4deb2010-09-29 20:34:41 +0000670 CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
Owen Andersonc1bdac62010-08-31 18:48:48 +0000671 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
672 CondBr->eraseFromParent();
673 return true;
674 }
Owen Anderson660cab32010-08-27 17:12:29 +0000675 }
676 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000677 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000678
679 // Check for some cases that are worth simplifying. Right now we want to look
680 // for loads that are used by a switch or by the condition for the branch. If
681 // we see one, check to see if it's partially redundant. If so, insert a PHI
682 // which can then be used to thread the values.
683 //
Chris Lattner421fa9e2008-12-03 07:48:08 +0000684 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000685 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
686 if (isa<Constant>(CondCmp->getOperand(1)))
687 SimplifyValue = CondCmp->getOperand(0);
688
Chris Lattner4e447eb2009-11-15 19:58:31 +0000689 // TODO: There are other places where load PRE would be profitable, such as
690 // more complex comparisons.
Chris Lattner69e067f2008-11-27 05:07:53 +0000691 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
692 if (SimplifyPartiallyRedundantLoad(LI))
693 return true;
694
Chris Lattner5729d382009-11-07 08:05:03 +0000695
696 // Handle a variety of cases where we are branching on something derived from
697 // a PHI node in the current block. If we can prove that any predecessors
698 // compute a predictable value based on a PHI node, thread those predecessors.
699 //
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000700 if (ProcessThreadableEdges(CondInst, BB))
701 return true;
Chris Lattner5729d382009-11-07 08:05:03 +0000702
Chris Lattner77beb472010-01-11 23:41:09 +0000703 // If this is an otherwise-unfoldable branch on a phi node in the current
704 // block, see if we can simplify.
705 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
706 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
707 return ProcessBranchOnPHI(PN);
Chris Lattner5729d382009-11-07 08:05:03 +0000708
Chris Lattner2249a0b2010-01-12 02:07:17 +0000709
710 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
711 if (CondInst->getOpcode() == Instruction::Xor &&
712 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
713 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
714
715
Chris Lattner69e067f2008-11-27 05:07:53 +0000716 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
Chris Lattner77beb472010-01-11 23:41:09 +0000717 // "(X == 4)", thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000718
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000719 return false;
720}
721
Chris Lattner421fa9e2008-12-03 07:48:08 +0000722/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
723/// block that jump on exactly the same condition. This means that we almost
724/// always know the direction of the edge in the DESTBB:
725/// PREDBB:
726/// br COND, DESTBB, BBY
727/// DESTBB:
728/// br COND, BBZ, BBW
729///
730/// If DESTBB has multiple predecessors, we can't just constant fold the branch
731/// in DESTBB, we have to thread over it.
732bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
733 BasicBlock *BB) {
734 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
735
736 // If both successors of PredBB go to DESTBB, we don't know anything. We can
737 // fold the branch to an unconditional one, which allows other recursive
738 // simplifications.
739 bool BranchDir;
740 if (PredBI->getSuccessor(1) != BB)
741 BranchDir = true;
742 else if (PredBI->getSuccessor(0) != BB)
743 BranchDir = false;
744 else {
David Greenefe7fe662010-01-05 01:27:19 +0000745 DEBUG(dbgs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000746 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000747 ++NumFolds;
748 ConstantFoldTerminator(PredBB);
749 return true;
750 }
751
752 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
753
754 // If the dest block has one predecessor, just fix the branch condition to a
755 // constant and fold it.
756 if (BB->getSinglePredecessor()) {
David Greenefe7fe662010-01-05 01:27:19 +0000757 DEBUG(dbgs() << " In block '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000758 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000759 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000760 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000761 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000762 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
763 BranchDir));
Chris Lattner6f285d22010-04-10 18:26:57 +0000764 // Delete dead instructions before we fold the branch. Folding the branch
765 // can eliminate edges from the CFG which can end up deleting OldCond.
Chris Lattner5a06cf62009-10-11 18:39:58 +0000766 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner6f285d22010-04-10 18:26:57 +0000767 ConstantFoldTerminator(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000768 return true;
769 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000770
Chris Lattner421fa9e2008-12-03 07:48:08 +0000771
772 // Next, figure out which successor we are threading to.
773 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
774
Chris Lattner5729d382009-11-07 08:05:03 +0000775 SmallVector<BasicBlock*, 2> Preds;
776 Preds.push_back(PredBB);
777
Mike Stumpfe095f32009-05-04 18:40:41 +0000778 // Ok, try to thread it!
Chris Lattner5729d382009-11-07 08:05:03 +0000779 return ThreadEdge(BB, Preds, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000780}
781
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000782/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
783/// block that switch on exactly the same condition. This means that we almost
784/// always know the direction of the edge in the DESTBB:
785/// PREDBB:
786/// switch COND [... DESTBB, BBY ... ]
787/// DESTBB:
788/// switch COND [... BBZ, BBW ]
789///
790/// Optimizing switches like this is very important, because simplifycfg builds
791/// switches out of repeated 'if' conditions.
792bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
793 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000794 // Can't thread edge to self.
795 if (PredBB == DestBB)
796 return false;
797
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000798 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
799 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
800
801 // There are a variety of optimizations that we can potentially do on these
802 // blocks: we order them from most to least preferable.
803
804 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
805 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000806 // growth. Skip debug info first.
807 BasicBlock::iterator BBI = DestBB->begin();
808 while (isa<DbgInfoIntrinsic>(BBI))
809 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000810
811 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000812 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000813 bool MadeChange = false;
814 // Ignore the default edge for now.
815 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
816 ConstantInt *DestVal = DestSI->getCaseValue(i);
817 BasicBlock *DestSucc = DestSI->getSuccessor(i);
818
819 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
820 // PredSI has an explicit case for it. If so, forward. If it is covered
821 // by the default case, we can't update PredSI.
822 unsigned PredCase = PredSI->findCaseValue(DestVal);
823 if (PredCase == 0) continue;
824
825 // If PredSI doesn't go to DestBB on this value, then it won't reach the
826 // case on this condition.
827 if (PredSI->getSuccessor(PredCase) != DestBB &&
828 DestSI->getSuccessor(i) != DestBB)
829 continue;
Chris Lattner08bc2702009-12-06 17:17:23 +0000830
831 // Do not forward this if it already goes to this destination, this would
832 // be an infinite loop.
833 if (PredSI->getSuccessor(PredCase) == DestSucc)
834 continue;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000835
836 // Otherwise, we're safe to make the change. Make sure that the edge from
837 // DestSI to DestSucc is not critical and has no PHI nodes.
David Greenefe7fe662010-01-05 01:27:19 +0000838 DEBUG(dbgs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
839 DEBUG(dbgs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000840
841 // If the destination has PHI nodes, just split the edge for updating
842 // simplicity.
843 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
844 SplitCriticalEdge(DestSI, i, this);
845 DestSucc = DestSI->getSuccessor(i);
846 }
847 FoldSingleEntryPHINodes(DestSucc);
848 PredSI->setSuccessor(PredCase, DestSucc);
849 MadeChange = true;
850 }
851
852 if (MadeChange)
853 return true;
854 }
855
856 return false;
857}
858
859
Chris Lattner69e067f2008-11-27 05:07:53 +0000860/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
861/// load instruction, eliminate it by replacing it with a PHI node. This is an
862/// important optimization that encourages jump threading, and needs to be run
863/// interlaced with other jump threading tasks.
864bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
865 // Don't hack volatile loads.
866 if (LI->isVolatile()) return false;
867
868 // If the load is defined in a block with exactly one predecessor, it can't be
869 // partially redundant.
870 BasicBlock *LoadBB = LI->getParent();
871 if (LoadBB->getSinglePredecessor())
872 return false;
873
874 Value *LoadedPtr = LI->getOperand(0);
875
876 // If the loaded operand is defined in the LoadBB, it can't be available.
Chris Lattner4e447eb2009-11-15 19:58:31 +0000877 // TODO: Could do simple PHI translation, that would be fun :)
Chris Lattner69e067f2008-11-27 05:07:53 +0000878 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
879 if (PtrOp->getParent() == LoadBB)
880 return false;
881
882 // Scan a few instructions up from the load, to see if it is obviously live at
883 // the entry to its block.
884 BasicBlock::iterator BBIt = LI;
885
Chris Lattner4e447eb2009-11-15 19:58:31 +0000886 if (Value *AvailableVal =
887 FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000888 // If the value if the load is locally available within the block, just use
889 // it. This frequently occurs for reg2mem'd allocas.
890 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000891
892 // If the returned value is the load itself, replace with an undef. This can
893 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000894 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000895 LI->replaceAllUsesWith(AvailableVal);
896 LI->eraseFromParent();
897 return true;
898 }
899
900 // Otherwise, if we scanned the whole block and got to the top of the block,
901 // we know the block is locally transparent to the load. If not, something
902 // might clobber its value.
903 if (BBIt != LoadBB->begin())
904 return false;
905
906
907 SmallPtrSet<BasicBlock*, 8> PredsScanned;
908 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
909 AvailablePredsTy AvailablePreds;
910 BasicBlock *OneUnavailablePred = 0;
911
912 // If we got here, the loaded value is transparent through to the start of the
913 // block. Check to see if it is available in any of the predecessor blocks.
914 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
915 PI != PE; ++PI) {
916 BasicBlock *PredBB = *PI;
917
918 // If we already scanned this predecessor, skip it.
919 if (!PredsScanned.insert(PredBB))
920 continue;
921
922 // Scan the predecessor to see if the value is available in the pred.
923 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000924 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000925 if (!PredAvailable) {
926 OneUnavailablePred = PredBB;
927 continue;
928 }
929
930 // If so, this load is partially redundant. Remember this info so that we
931 // can create a PHI node.
932 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
933 }
934
935 // If the loaded value isn't available in any predecessor, it isn't partially
936 // redundant.
937 if (AvailablePreds.empty()) return false;
938
939 // Okay, the loaded value is available in at least one (and maybe all!)
940 // predecessors. If the value is unavailable in more than one unique
941 // predecessor, we want to insert a merge block for those common predecessors.
942 // This ensures that we only have to insert one reload, thus not increasing
943 // code size.
944 BasicBlock *UnavailablePred = 0;
945
946 // If there is exactly one predecessor where the value is unavailable, the
947 // already computed 'OneUnavailablePred' block is it. If it ends in an
948 // unconditional branch, we know that it isn't a critical edge.
949 if (PredsScanned.size() == AvailablePreds.size()+1 &&
950 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
951 UnavailablePred = OneUnavailablePred;
952 } else if (PredsScanned.size() != AvailablePreds.size()) {
953 // Otherwise, we had multiple unavailable predecessors or we had a critical
954 // edge from the one.
955 SmallVector<BasicBlock*, 8> PredsToSplit;
956 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
957
958 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
959 AvailablePredSet.insert(AvailablePreds[i].first);
960
961 // Add all the unavailable predecessors to the PredsToSplit list.
962 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
Chris Lattnere58867e2010-06-14 19:45:43 +0000963 PI != PE; ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +0000964 BasicBlock *P = *PI;
Chris Lattnere58867e2010-06-14 19:45:43 +0000965 // If the predecessor is an indirect goto, we can't split the edge.
Gabor Greifee1f44f2010-07-12 14:10:24 +0000966 if (isa<IndirectBrInst>(P->getTerminator()))
Chris Lattnere58867e2010-06-14 19:45:43 +0000967 return false;
968
Gabor Greifee1f44f2010-07-12 14:10:24 +0000969 if (!AvailablePredSet.count(P))
970 PredsToSplit.push_back(P);
Chris Lattnere58867e2010-06-14 19:45:43 +0000971 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000972
973 // Split them out to their own block.
974 UnavailablePred =
975 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
Chris Lattner4e447eb2009-11-15 19:58:31 +0000976 "thread-pre-split", this);
Chris Lattner69e067f2008-11-27 05:07:53 +0000977 }
978
979 // If the value isn't available in all predecessors, then there will be
980 // exactly one where it isn't available. Insert a load on that edge and add
981 // it to the AvailablePreds list.
982 if (UnavailablePred) {
983 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
984 "Can't handle critical edge here!");
Chris Lattner4e447eb2009-11-15 19:58:31 +0000985 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
986 LI->getAlignment(),
Chris Lattner69e067f2008-11-27 05:07:53 +0000987 UnavailablePred->getTerminator());
988 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
989 }
990
991 // Now we know that each predecessor of this block has a value in
992 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000993 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000994
995 // Create a PHI node at the start of the block for the PRE'd load value.
996 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
997 PN->takeName(LI);
998
999 // Insert new entries into the PHI for each predecessor. A single block may
1000 // have multiple entries here.
1001 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
1002 ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +00001003 BasicBlock *P = *PI;
Chris Lattner69e067f2008-11-27 05:07:53 +00001004 AvailablePredsTy::iterator I =
1005 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
Gabor Greifee1f44f2010-07-12 14:10:24 +00001006 std::make_pair(P, (Value*)0));
Chris Lattner69e067f2008-11-27 05:07:53 +00001007
Gabor Greifee1f44f2010-07-12 14:10:24 +00001008 assert(I != AvailablePreds.end() && I->first == P &&
Chris Lattner69e067f2008-11-27 05:07:53 +00001009 "Didn't find entry for predecessor!");
1010
1011 PN->addIncoming(I->second, I->first);
1012 }
1013
1014 //cerr << "PRE: " << *LI << *PN << "\n";
1015
1016 LI->replaceAllUsesWith(PN);
1017 LI->eraseFromParent();
1018
1019 return true;
1020}
1021
Chris Lattner5729d382009-11-07 08:05:03 +00001022/// FindMostPopularDest - The specified list contains multiple possible
1023/// threadable destinations. Pick the one that occurs the most frequently in
1024/// the list.
1025static BasicBlock *
1026FindMostPopularDest(BasicBlock *BB,
1027 const SmallVectorImpl<std::pair<BasicBlock*,
1028 BasicBlock*> > &PredToDestList) {
1029 assert(!PredToDestList.empty());
1030
1031 // Determine popularity. If there are multiple possible destinations, we
1032 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1033 // blocks with known and real destinations to threading undef. We'll handle
1034 // them later if interesting.
1035 DenseMap<BasicBlock*, unsigned> DestPopularity;
1036 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1037 if (PredToDestList[i].second)
1038 DestPopularity[PredToDestList[i].second]++;
1039
1040 // Find the most popular dest.
1041 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1042 BasicBlock *MostPopularDest = DPI->first;
1043 unsigned Popularity = DPI->second;
1044 SmallVector<BasicBlock*, 4> SamePopularity;
1045
1046 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1047 // If the popularity of this entry isn't higher than the popularity we've
1048 // seen so far, ignore it.
1049 if (DPI->second < Popularity)
1050 ; // ignore.
1051 else if (DPI->second == Popularity) {
1052 // If it is the same as what we've seen so far, keep track of it.
1053 SamePopularity.push_back(DPI->first);
1054 } else {
1055 // If it is more popular, remember it.
1056 SamePopularity.clear();
1057 MostPopularDest = DPI->first;
1058 Popularity = DPI->second;
1059 }
1060 }
1061
1062 // Okay, now we know the most popular destination. If there is more than
1063 // destination, we need to determine one. This is arbitrary, but we need
1064 // to make a deterministic decision. Pick the first one that appears in the
1065 // successor list.
1066 if (!SamePopularity.empty()) {
1067 SamePopularity.push_back(MostPopularDest);
1068 TerminatorInst *TI = BB->getTerminator();
1069 for (unsigned i = 0; ; ++i) {
1070 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1071
1072 if (std::find(SamePopularity.begin(), SamePopularity.end(),
1073 TI->getSuccessor(i)) == SamePopularity.end())
1074 continue;
1075
1076 MostPopularDest = TI->getSuccessor(i);
1077 break;
1078 }
1079 }
1080
1081 // Okay, we have finally picked the most popular destination.
1082 return MostPopularDest;
1083}
1084
Chris Lattner1c96b412009-11-12 01:37:43 +00001085bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB) {
Chris Lattner5729d382009-11-07 08:05:03 +00001086 // If threading this would thread across a loop header, don't even try to
1087 // thread the edge.
1088 if (LoopHeaders.count(BB))
1089 return false;
1090
Chris Lattner5729d382009-11-07 08:05:03 +00001091 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001092 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
Chris Lattner5729d382009-11-07 08:05:03 +00001093 return false;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001094
Chris Lattner5729d382009-11-07 08:05:03 +00001095 assert(!PredValues.empty() &&
1096 "ComputeValueKnownInPredecessors returned true with no values");
1097
David Greenefe7fe662010-01-05 01:27:19 +00001098 DEBUG(dbgs() << "IN BB: " << *BB;
Chris Lattner5729d382009-11-07 08:05:03 +00001099 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
David Greenefe7fe662010-01-05 01:27:19 +00001100 dbgs() << " BB '" << BB->getName() << "': FOUND condition = ";
Chris Lattner5729d382009-11-07 08:05:03 +00001101 if (PredValues[i].first)
David Greenefe7fe662010-01-05 01:27:19 +00001102 dbgs() << *PredValues[i].first;
Chris Lattner5729d382009-11-07 08:05:03 +00001103 else
David Greenefe7fe662010-01-05 01:27:19 +00001104 dbgs() << "UNDEF";
1105 dbgs() << " for pred '" << PredValues[i].second->getName()
Chris Lattner5729d382009-11-07 08:05:03 +00001106 << "'.\n";
1107 });
1108
1109 // Decide what we want to thread through. Convert our list of known values to
1110 // a list of known destinations for each pred. This also discards duplicate
1111 // predecessors and keeps track of the undefined inputs (which are represented
Chris Lattnere7e63fe2009-11-09 00:41:49 +00001112 // as a null dest in the PredToDestList).
Chris Lattner5729d382009-11-07 08:05:03 +00001113 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1114 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1115
1116 BasicBlock *OnlyDest = 0;
1117 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1118
1119 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1120 BasicBlock *Pred = PredValues[i].second;
1121 if (!SeenPreds.insert(Pred))
1122 continue; // Duplicate predecessor entry.
1123
1124 // If the predecessor ends with an indirect goto, we can't change its
1125 // destination.
1126 if (isa<IndirectBrInst>(Pred->getTerminator()))
1127 continue;
1128
1129 ConstantInt *Val = PredValues[i].first;
1130
1131 BasicBlock *DestBB;
1132 if (Val == 0) // Undef.
1133 DestBB = 0;
1134 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1135 DestBB = BI->getSuccessor(Val->isZero());
1136 else {
1137 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
1138 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
1139 }
1140
1141 // If we have exactly one destination, remember it for efficiency below.
1142 if (i == 0)
1143 OnlyDest = DestBB;
1144 else if (OnlyDest != DestBB)
1145 OnlyDest = MultipleDestSentinel;
1146
1147 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1148 }
1149
1150 // If all edges were unthreadable, we fail.
1151 if (PredToDestList.empty())
1152 return false;
1153
1154 // Determine which is the most common successor. If we have many inputs and
1155 // this block is a switch, we want to start by threading the batch that goes
1156 // to the most popular destination first. If we only know about one
1157 // threadable destination (the common case) we can avoid this.
1158 BasicBlock *MostPopularDest = OnlyDest;
1159
1160 if (MostPopularDest == MultipleDestSentinel)
1161 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1162
1163 // Now that we know what the most popular destination is, factor all
1164 // predecessors that will jump to it into a single predecessor.
1165 SmallVector<BasicBlock*, 16> PredsToFactor;
1166 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1167 if (PredToDestList[i].second == MostPopularDest) {
1168 BasicBlock *Pred = PredToDestList[i].first;
1169
1170 // This predecessor may be a switch or something else that has multiple
1171 // edges to the block. Factor each of these edges by listing them
1172 // according to # occurrences in PredsToFactor.
1173 TerminatorInst *PredTI = Pred->getTerminator();
1174 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1175 if (PredTI->getSuccessor(i) == BB)
1176 PredsToFactor.push_back(Pred);
1177 }
1178
1179 // If the threadable edges are branching on an undefined value, we get to pick
1180 // the destination that these predecessors should get to.
1181 if (MostPopularDest == 0)
1182 MostPopularDest = BB->getTerminator()->
1183 getSuccessor(GetBestDestForJumpOnUndef(BB));
1184
1185 // Ok, try to thread it!
1186 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1187}
Chris Lattner69e067f2008-11-27 05:07:53 +00001188
Chris Lattner77beb472010-01-11 23:41:09 +00001189/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1190/// a PHI node in the current block. See if there are any simplifications we
1191/// can do based on inputs to the phi node.
Chris Lattnerd38c14e2008-04-22 06:36:15 +00001192///
Chris Lattner77beb472010-01-11 23:41:09 +00001193bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +00001194 BasicBlock *BB = PN->getParent();
1195
Chris Lattner2249a0b2010-01-12 02:07:17 +00001196 // TODO: We could make use of this to do it once for blocks with common PHI
1197 // values.
1198 SmallVector<BasicBlock*, 1> PredBBs;
1199 PredBBs.resize(1);
1200
Chris Lattner5729d382009-11-07 08:05:03 +00001201 // If any of the predecessor blocks end in an unconditional branch, we can
Chris Lattner77beb472010-01-11 23:41:09 +00001202 // *duplicate* the conditional branch into that block in order to further
1203 // encourage jump threading and to eliminate cases where we have branch on a
1204 // phi of an icmp (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +00001205 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1206 BasicBlock *PredBB = PN->getIncomingBlock(i);
1207 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
Chris Lattner2249a0b2010-01-12 02:07:17 +00001208 if (PredBr->isUnconditional()) {
1209 PredBBs[0] = PredBB;
1210 // Try to duplicate BB into PredBB.
1211 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1212 return true;
1213 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001214 }
1215
Chris Lattner6b65f472009-10-11 04:40:21 +00001216 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001217}
1218
Chris Lattner2249a0b2010-01-12 02:07:17 +00001219/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1220/// a xor instruction in the current block. See if there are any
1221/// simplifications we can do based on inputs to the xor.
1222///
1223bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
1224 BasicBlock *BB = BO->getParent();
1225
1226 // If either the LHS or RHS of the xor is a constant, don't do this
1227 // optimization.
1228 if (isa<ConstantInt>(BO->getOperand(0)) ||
1229 isa<ConstantInt>(BO->getOperand(1)))
1230 return false;
1231
Chris Lattner2dd76572010-01-23 19:16:25 +00001232 // If the first instruction in BB isn't a phi, we won't be able to infer
1233 // anything special about any particular predecessor.
1234 if (!isa<PHINode>(BB->front()))
1235 return false;
1236
Chris Lattner2249a0b2010-01-12 02:07:17 +00001237 // If we have a xor as the branch input to this block, and we know that the
1238 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1239 // the condition into the predecessor and fix that value to true, saving some
1240 // logical ops on that path and encouraging other paths to simplify.
1241 //
1242 // This copies something like this:
1243 //
1244 // BB:
1245 // %X = phi i1 [1], [%X']
1246 // %Y = icmp eq i32 %A, %B
1247 // %Z = xor i1 %X, %Y
1248 // br i1 %Z, ...
1249 //
1250 // Into:
1251 // BB':
1252 // %Y = icmp ne i32 %A, %B
1253 // br i1 %Z, ...
1254
1255 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> XorOpValues;
1256 bool isLHS = true;
1257 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues)) {
1258 assert(XorOpValues.empty());
1259 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues))
1260 return false;
1261 isLHS = false;
1262 }
1263
1264 assert(!XorOpValues.empty() &&
1265 "ComputeValueKnownInPredecessors returned true with no values");
1266
1267 // Scan the information to see which is most popular: true or false. The
1268 // predecessors can be of the set true, false, or undef.
1269 unsigned NumTrue = 0, NumFalse = 0;
1270 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1271 if (!XorOpValues[i].first) continue; // Ignore undefs for the count.
1272 if (XorOpValues[i].first->isZero())
1273 ++NumFalse;
1274 else
1275 ++NumTrue;
1276 }
1277
1278 // Determine which value to split on, true, false, or undef if neither.
1279 ConstantInt *SplitVal = 0;
1280 if (NumTrue > NumFalse)
1281 SplitVal = ConstantInt::getTrue(BB->getContext());
1282 else if (NumTrue != 0 || NumFalse != 0)
1283 SplitVal = ConstantInt::getFalse(BB->getContext());
1284
1285 // Collect all of the blocks that this can be folded into so that we can
1286 // factor this once and clone it once.
1287 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1288 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1289 if (XorOpValues[i].first != SplitVal && XorOpValues[i].first != 0) continue;
1290
1291 BlocksToFoldInto.push_back(XorOpValues[i].second);
1292 }
1293
Chris Lattner2dd76572010-01-23 19:16:25 +00001294 // If we inferred a value for all of the predecessors, then duplication won't
1295 // help us. However, we can just replace the LHS or RHS with the constant.
1296 if (BlocksToFoldInto.size() ==
1297 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1298 if (SplitVal == 0) {
1299 // If all preds provide undef, just nuke the xor, because it is undef too.
1300 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1301 BO->eraseFromParent();
1302 } else if (SplitVal->isZero()) {
1303 // If all preds provide 0, replace the xor with the other input.
1304 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1305 BO->eraseFromParent();
1306 } else {
1307 // If all preds provide 1, set the computed value to 1.
1308 BO->setOperand(!isLHS, SplitVal);
1309 }
1310
1311 return true;
1312 }
1313
Chris Lattner2249a0b2010-01-12 02:07:17 +00001314 // Try to duplicate BB into PredBB.
Chris Lattner797c4402010-01-12 02:07:50 +00001315 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
Chris Lattner2249a0b2010-01-12 02:07:17 +00001316}
1317
1318
Chris Lattner78c552e2009-10-11 07:24:57 +00001319/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1320/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1321/// NewPred using the entries from OldPred (suitably mapped).
1322static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1323 BasicBlock *OldPred,
1324 BasicBlock *NewPred,
1325 DenseMap<Instruction*, Value*> &ValueMap) {
1326 for (BasicBlock::iterator PNI = PHIBB->begin();
1327 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1328 // Ok, we have a PHI node. Figure out what the incoming value was for the
1329 // DestBlock.
1330 Value *IV = PN->getIncomingValueForBlock(OldPred);
1331
1332 // Remap the value if necessary.
1333 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1334 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1335 if (I != ValueMap.end())
1336 IV = I->second;
1337 }
1338
1339 PN->addIncoming(IV, NewPred);
1340 }
1341}
Chris Lattner6bf77502008-04-22 07:05:46 +00001342
Chris Lattner5729d382009-11-07 08:05:03 +00001343/// ThreadEdge - We have decided that it is safe and profitable to factor the
1344/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1345/// across BB. Transform the IR to reflect this change.
1346bool JumpThreading::ThreadEdge(BasicBlock *BB,
1347 const SmallVectorImpl<BasicBlock*> &PredBBs,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001348 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001349 // If threading to the same block as we come from, we would infinite loop.
1350 if (SuccBB == BB) {
David Greenefe7fe662010-01-05 01:27:19 +00001351 DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001352 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001353 return false;
1354 }
1355
1356 // If threading this would thread across a loop header, don't thread the edge.
1357 // See the comments above FindLoopHeaders for justifications and caveats.
1358 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001359 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001360 << "' to dest BB '" << SuccBB->getName()
1361 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001362 return false;
1363 }
1364
Chris Lattner78c552e2009-10-11 07:24:57 +00001365 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1366 if (JumpThreadCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001367 DEBUG(dbgs() << " Not threading BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001368 << "' - Cost is too high: " << JumpThreadCost << "\n");
1369 return false;
1370 }
1371
Chris Lattner5729d382009-11-07 08:05:03 +00001372 // And finally, do it! Start by factoring the predecessors is needed.
1373 BasicBlock *PredBB;
1374 if (PredBBs.size() == 1)
1375 PredBB = PredBBs[0];
1376 else {
David Greenefe7fe662010-01-05 01:27:19 +00001377 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
Chris Lattner5729d382009-11-07 08:05:03 +00001378 << " common predecessors.\n");
1379 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1380 ".thr_comm", this);
1381 }
1382
Mike Stumpfe095f32009-05-04 18:40:41 +00001383 // And finally, do it!
David Greenefe7fe662010-01-05 01:27:19 +00001384 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001385 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001386 << ", across block:\n "
1387 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001388
Owen Andersonc809d902010-09-14 20:57:41 +00001389 LVI->threadEdge(PredBB, BB, SuccBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001390
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001391 // We are going to have to map operands from the original BB block to the new
1392 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1393 // account for entry from PredBB.
1394 DenseMap<Instruction*, Value*> ValueMapping;
1395
Owen Anderson1d0be152009-08-13 21:58:54 +00001396 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1397 BB->getName()+".thread",
1398 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001399 NewBB->moveAfter(PredBB);
1400
1401 BasicBlock::iterator BI = BB->begin();
1402 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1403 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1404
1405 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1406 // mapping and using it to remap operands in the cloned instructions.
1407 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001408 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001409 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001410 NewBB->getInstList().push_back(New);
1411 ValueMapping[BI] = New;
1412
1413 // Remap operands to patch up intra-block references.
1414 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001415 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1416 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1417 if (I != ValueMapping.end())
1418 New->setOperand(i, I->second);
1419 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001420 }
1421
1422 // We didn't copy the terminator from BB over to NewBB, because there is now
1423 // an unconditional jump to SuccBB. Insert the unconditional jump.
1424 BranchInst::Create(SuccBB, NewBB);
1425
1426 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1427 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001428 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001429
Chris Lattner433a0db2009-10-10 09:05:58 +00001430 // If there were values defined in BB that are used outside the block, then we
1431 // now have to update all uses of the value to use either the original value,
1432 // the cloned value, or some PHI derived value. This can require arbitrary
1433 // PHI insertion, of which we are prepared to do, clean these up now.
1434 SSAUpdater SSAUpdate;
1435 SmallVector<Use*, 16> UsesToRename;
1436 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1437 // Scan all uses of this instruction to see if it is used outside of its
1438 // block, and if so, record them in UsesToRename.
1439 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1440 ++UI) {
1441 Instruction *User = cast<Instruction>(*UI);
1442 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1443 if (UserPN->getIncomingBlock(UI) == BB)
1444 continue;
1445 } else if (User->getParent() == BB)
1446 continue;
1447
1448 UsesToRename.push_back(&UI.getUse());
1449 }
1450
1451 // If there are no uses outside the block, we're done with this instruction.
1452 if (UsesToRename.empty())
1453 continue;
1454
David Greenefe7fe662010-01-05 01:27:19 +00001455 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001456
1457 // We found a use of I outside of BB. Rename all uses of I that are outside
1458 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1459 // with the two values we know.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001460 SSAUpdate.Initialize(I->getType(), I->getName());
Chris Lattner433a0db2009-10-10 09:05:58 +00001461 SSAUpdate.AddAvailableValue(BB, I);
1462 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1463
1464 while (!UsesToRename.empty())
1465 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001466 DEBUG(dbgs() << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001467 }
1468
1469
Chris Lattneref0c6742008-12-01 04:48:07 +00001470 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001471 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1472 // us to simplify any PHI nodes in BB.
1473 TerminatorInst *PredTerm = PredBB->getTerminator();
1474 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1475 if (PredTerm->getSuccessor(i) == BB) {
Owen Anderson36c4deb2010-09-29 20:34:41 +00001476 BB->removePredecessor(PredBB, true);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001477 PredTerm->setSuccessor(i, NewBB);
1478 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001479
1480 // At this point, the IR is fully up to date and consistent. Do a quick scan
1481 // over the new instructions and zap any that are constants or dead. This
1482 // frequently happens because of phi translation.
Chris Lattner972a46c2010-01-12 20:41:47 +00001483 SimplifyInstructionsInBlock(NewBB, TD);
Mike Stumpfe095f32009-05-04 18:40:41 +00001484
1485 // Threaded an edge!
1486 ++NumThreads;
1487 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001488}
Chris Lattner78c552e2009-10-11 07:24:57 +00001489
1490/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1491/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1492/// If we can duplicate the contents of BB up into PredBB do so now, this
1493/// improves the odds that the branch will be on an analyzable instruction like
1494/// a compare.
1495bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
Chris Lattner2249a0b2010-01-12 02:07:17 +00001496 const SmallVectorImpl<BasicBlock *> &PredBBs) {
1497 assert(!PredBBs.empty() && "Can't handle an empty set");
1498
Chris Lattner78c552e2009-10-11 07:24:57 +00001499 // If BB is a loop header, then duplicating this block outside the loop would
1500 // cause us to transform this into an irreducible loop, don't do this.
1501 // See the comments above FindLoopHeaders for justifications and caveats.
1502 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001503 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
Chris Lattner2249a0b2010-01-12 02:07:17 +00001504 << "' into predecessor block '" << PredBBs[0]->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001505 << "' - it might create an irreducible loop!\n");
1506 return false;
1507 }
1508
1509 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1510 if (DuplicationCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001511 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001512 << "' - Cost is too high: " << DuplicationCost << "\n");
1513 return false;
1514 }
1515
Chris Lattner2249a0b2010-01-12 02:07:17 +00001516 // And finally, do it! Start by factoring the predecessors is needed.
1517 BasicBlock *PredBB;
1518 if (PredBBs.size() == 1)
1519 PredBB = PredBBs[0];
1520 else {
1521 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
1522 << " common predecessors.\n");
1523 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1524 ".thr_comm", this);
1525 }
1526
Chris Lattner78c552e2009-10-11 07:24:57 +00001527 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1528 // of PredBB.
David Greenefe7fe662010-01-05 01:27:19 +00001529 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
Chris Lattner78c552e2009-10-11 07:24:57 +00001530 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1531 << DuplicationCost << " block is:" << *BB << "\n");
1532
Chris Lattner2249a0b2010-01-12 02:07:17 +00001533 // Unless PredBB ends with an unconditional branch, split the edge so that we
1534 // can just clone the bits from BB into the end of the new PredBB.
Chris Lattnerd6688392010-01-23 19:21:31 +00001535 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
Chris Lattner2249a0b2010-01-12 02:07:17 +00001536
Chris Lattnerd6688392010-01-23 19:21:31 +00001537 if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
Chris Lattner2249a0b2010-01-12 02:07:17 +00001538 PredBB = SplitEdge(PredBB, BB, this);
1539 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1540 }
1541
Chris Lattner78c552e2009-10-11 07:24:57 +00001542 // We are going to have to map operands from the original BB block into the
1543 // PredBB block. Evaluate PHI nodes in BB.
1544 DenseMap<Instruction*, Value*> ValueMapping;
1545
1546 BasicBlock::iterator BI = BB->begin();
1547 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1548 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1549
Chris Lattner78c552e2009-10-11 07:24:57 +00001550 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1551 // mapping and using it to remap operands in the cloned instructions.
1552 for (; BI != BB->end(); ++BI) {
1553 Instruction *New = BI->clone();
Chris Lattner78c552e2009-10-11 07:24:57 +00001554
1555 // Remap operands to patch up intra-block references.
1556 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1557 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1558 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1559 if (I != ValueMapping.end())
1560 New->setOperand(i, I->second);
1561 }
Chris Lattner972a46c2010-01-12 20:41:47 +00001562
1563 // If this instruction can be simplified after the operands are updated,
1564 // just use the simplified value instead. This frequently happens due to
1565 // phi translation.
1566 if (Value *IV = SimplifyInstruction(New, TD)) {
1567 delete New;
1568 ValueMapping[BI] = IV;
1569 } else {
1570 // Otherwise, insert the new instruction into the block.
1571 New->setName(BI->getName());
1572 PredBB->getInstList().insert(OldPredBranch, New);
1573 ValueMapping[BI] = New;
1574 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001575 }
1576
1577 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1578 // add entries to the PHI nodes for branch from PredBB now.
1579 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1580 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1581 ValueMapping);
1582 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1583 ValueMapping);
1584
1585 // If there were values defined in BB that are used outside the block, then we
1586 // now have to update all uses of the value to use either the original value,
1587 // the cloned value, or some PHI derived value. This can require arbitrary
1588 // PHI insertion, of which we are prepared to do, clean these up now.
1589 SSAUpdater SSAUpdate;
1590 SmallVector<Use*, 16> UsesToRename;
1591 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1592 // Scan all uses of this instruction to see if it is used outside of its
1593 // block, and if so, record them in UsesToRename.
1594 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1595 ++UI) {
1596 Instruction *User = cast<Instruction>(*UI);
1597 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1598 if (UserPN->getIncomingBlock(UI) == BB)
1599 continue;
1600 } else if (User->getParent() == BB)
1601 continue;
1602
1603 UsesToRename.push_back(&UI.getUse());
1604 }
1605
1606 // If there are no uses outside the block, we're done with this instruction.
1607 if (UsesToRename.empty())
1608 continue;
1609
David Greenefe7fe662010-01-05 01:27:19 +00001610 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001611
1612 // We found a use of I outside of BB. Rename all uses of I that are outside
1613 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1614 // with the two values we know.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001615 SSAUpdate.Initialize(I->getType(), I->getName());
Chris Lattner78c552e2009-10-11 07:24:57 +00001616 SSAUpdate.AddAvailableValue(BB, I);
1617 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1618
1619 while (!UsesToRename.empty())
1620 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001621 DEBUG(dbgs() << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001622 }
1623
1624 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1625 // that we nuked.
Owen Anderson36c4deb2010-09-29 20:34:41 +00001626 BB->removePredecessor(PredBB, true);
Chris Lattner78c552e2009-10-11 07:24:57 +00001627
1628 // Remove the unconditional branch at the end of the PredBB block.
1629 OldPredBranch->eraseFromParent();
1630
1631 ++NumDupes;
1632 return true;
1633}
1634
1635