blob: 7cd1602e92c4cce1e912addfa130e78624f48d91 [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 Lattneref0c6742008-12-01 04:48:07 +000019#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner433a0db2009-10-10 09:05:58 +000022#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000023#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/SmallSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner177480b2008-04-20 21:13:06 +000030#include "llvm/Support/Debug.h"
Daniel Dunbar93b67e42009-07-26 07:49:05 +000031#include "llvm/Support/raw_ostream.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000032using namespace llvm;
33
Chris Lattnerbd3401f2008-04-20 22:39:42 +000034STATISTIC(NumThreads, "Number of jumps threaded");
35STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner78c552e2009-10-11 07:24:57 +000036STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
Chris Lattner8383a7b2008-04-20 20:35:01 +000037
Chris Lattner177480b2008-04-20 21:13:06 +000038static cl::opt<unsigned>
39Threshold("jump-threading-threshold",
40 cl::desc("Max block size to duplicate for jump threading"),
41 cl::init(6), cl::Hidden);
42
Chris Lattner8383a7b2008-04-20 20:35:01 +000043namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000044 /// This pass performs 'jump threading', which looks at blocks that have
45 /// multiple predecessors and multiple successors. If one or more of the
46 /// predecessors of the block can be proven to always jump to one of the
47 /// successors, we forward the edge from the predecessor to the successor by
48 /// duplicating the contents of this block.
49 ///
50 /// An example of when this can occur is code like this:
51 ///
52 /// if () { ...
53 /// X = 4;
54 /// }
55 /// if (X < 3) {
56 ///
57 /// In this case, the unconditional branch at the end of the first if can be
58 /// revectored to the false side of the second if.
59 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 class JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000061 TargetData *TD;
Mike Stumpfe095f32009-05-04 18:40:41 +000062#ifdef NDEBUG
63 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64#else
65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66#endif
Chris Lattner8383a7b2008-04-20 20:35:01 +000067 public:
68 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000069 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000070
71 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000072 void FindLoopHeaders(Function &F);
73
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000074 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbdbf1a12009-10-11 04:33:43 +000075 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +000076 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
77 BasicBlock *PredBB);
Chris Lattner78567252009-11-06 18:15:14 +000078
79 typedef SmallVectorImpl<std::pair<ConstantInt*,
80 BasicBlock*> > PredValueInfo;
81
82 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
83 PredValueInfo &Result);
84 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
85
86
Chris Lattner421fa9e2008-12-03 07:48:08 +000087 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000088 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000089
Chris Lattnerd38c14e2008-04-22 06:36:15 +000090 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattner69e067f2008-11-27 05:07:53 +000091
92 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000093 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000094}
95
Dan Gohman844731a2008-05-13 00:00:25 +000096char JumpThreading::ID = 0;
97static RegisterPass<JumpThreading>
98X("jump-threading", "Jump Threading");
99
Chris Lattner8383a7b2008-04-20 20:35:01 +0000100// Public interface to the Jump Threading pass
101FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
102
103/// runOnFunction - Top level algorithm.
104///
105bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000106 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000107 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000108
Mike Stumpfe095f32009-05-04 18:40:41 +0000109 FindLoopHeaders(F);
110
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000111 bool AnotherIteration = true, EverChanged = false;
112 while (AnotherIteration) {
113 AnotherIteration = false;
114 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000115 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
116 BasicBlock *BB = I;
117 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000118 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000119
120 ++I;
121
122 // If the block is trivially dead, zap it. This eliminates the successor
123 // edges which simplifies the CFG.
124 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000125 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000126 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000127 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000128 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000129 DeleteDeadBlock(BB);
130 Changed = true;
131 }
132 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000133 AnotherIteration = Changed;
134 EverChanged |= Changed;
135 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000136
137 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000138 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000139}
Chris Lattner177480b2008-04-20 21:13:06 +0000140
Chris Lattner78c552e2009-10-11 07:24:57 +0000141/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
142/// thread across it.
143static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
144 /// Ignore PHI nodes, these will be flattened when duplication happens.
145 BasicBlock::const_iterator I = BB->getFirstNonPHI();
146
147 // Sum up the cost of each instruction until we get to the terminator. Don't
148 // include the terminator because the copy won't include it.
149 unsigned Size = 0;
150 for (; !isa<TerminatorInst>(I); ++I) {
151 // Debugger intrinsics don't incur code size.
152 if (isa<DbgInfoIntrinsic>(I)) continue;
153
154 // If this is a pointer->pointer bitcast, it is free.
155 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
156 continue;
157
158 // All other instructions count for at least one unit.
159 ++Size;
160
161 // Calls are more expensive. If they are non-intrinsic calls, we model them
162 // as having cost of 4. If they are a non-vector intrinsic, we model them
163 // as having cost of 2 total, and if they are a vector intrinsic, we model
164 // them as having cost 1.
165 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
166 if (!isa<IntrinsicInst>(CI))
167 Size += 3;
168 else if (!isa<VectorType>(CI->getType()))
169 Size += 1;
170 }
171 }
172
173 // Threading through a switch statement is particularly profitable. If this
174 // block ends in a switch, decrease its cost to make it more likely to happen.
175 if (isa<SwitchInst>(I))
176 Size = Size > 6 ? Size-6 : 0;
177
178 return Size;
179}
180
181
182
Mike Stumpfe095f32009-05-04 18:40:41 +0000183/// FindLoopHeaders - We do not want jump threading to turn proper loop
184/// structures into irreducible loops. Doing this breaks up the loop nesting
185/// hierarchy and pessimizes later transformations. To prevent this from
186/// happening, we first have to find the loop headers. Here we approximate this
187/// by finding targets of backedges in the CFG.
188///
189/// Note that there definitely are cases when we want to allow threading of
190/// edges across a loop header. For example, threading a jump from outside the
191/// loop (the preheader) to an exit block of the loop is definitely profitable.
192/// It is also almost always profitable to thread backedges from within the loop
193/// to exit blocks, and is often profitable to thread backedges to other blocks
194/// within the loop (forming a nested loop). This simple analysis is not rich
195/// enough to track all of these properties and keep it up-to-date as the CFG
196/// mutates, so we don't allow any of these transformations.
197///
198void JumpThreading::FindLoopHeaders(Function &F) {
199 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
200 FindFunctionBackedges(F, Edges);
201
202 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
203 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
204}
205
Chris Lattner78567252009-11-06 18:15:14 +0000206/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
207/// hand sides of the compare instruction, try to determine the result. If the
208/// result can not be determined, a null pointer is returned.
209static Constant *GetResultOfComparison(CmpInst::Predicate pred,
210 Value *LHS, Value *RHS) {
211 if (Constant *CLHS = dyn_cast<Constant>(LHS))
212 if (Constant *CRHS = dyn_cast<Constant>(RHS))
213 return ConstantExpr::getCompare(pred, CLHS, CRHS);
Chris Lattner6bf77502008-04-22 07:05:46 +0000214
Chris Lattner78567252009-11-06 18:15:14 +0000215 if (LHS == RHS)
Jeffrey Yasskin9beab3f2009-11-07 00:26:47 +0000216 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType())) {
Chris Lattner78567252009-11-06 18:15:14 +0000217 if (ICmpInst::isTrueWhenEqual(pred))
218 return ConstantInt::getTrue(LHS->getContext());
219 else
220 return ConstantInt::getFalse(LHS->getContext());
Jeffrey Yasskin9beab3f2009-11-07 00:26:47 +0000221 }
Chris Lattner78567252009-11-06 18:15:14 +0000222 return 0;
223}
224
225
226/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
227/// if we can infer that the value is a known ConstantInt in any of our
228/// predecessors. If so, return the known the list of value and pred BB in the
229/// result vector. If a value is known to be undef, it is returned as null.
230///
231/// The BB basic block is known to start with a PHI node.
232///
233/// This returns true if there were any known values.
234///
235///
236/// TODO: Per PR2563, we could infer value range information about a predecessor
237/// based on its terminator.
238bool JumpThreading::
239ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
240 PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
241
242 // If V is a constantint, then it is known in all predecessors.
243 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
244 ConstantInt *CI = dyn_cast<ConstantInt>(V);
245 Result.resize(TheFirstPHI->getNumIncomingValues());
246 for (unsigned i = 0, e = Result.size(); i != e; ++i)
Chris Lattner82114b92009-11-06 19:21:48 +0000247 Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
Chris Lattner78567252009-11-06 18:15:14 +0000248 return true;
249 }
250
251 // If V is a non-instruction value, or an instruction in a different block,
252 // then it can't be derived from a PHI.
253 Instruction *I = dyn_cast<Instruction>(V);
254 if (I == 0 || I->getParent() != BB)
255 return false;
256
257 /// If I is a PHI node, then we know the incoming values for any constants.
258 if (PHINode *PN = dyn_cast<PHINode>(I)) {
259 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
260 Value *InVal = PN->getIncomingValue(i);
261 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
262 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
263 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
264 }
265 }
266 return !Result.empty();
267 }
268
269 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
270
271 // Handle some boolean conditions.
272 if (I->getType()->getPrimitiveSizeInBits() == 1) {
273 // X | true -> true
274 // X & false -> false
275 if (I->getOpcode() == Instruction::Or ||
276 I->getOpcode() == Instruction::And) {
277 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
278 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
279
280 if (LHSVals.empty() && RHSVals.empty())
281 return false;
282
283 ConstantInt *InterestingVal;
284 if (I->getOpcode() == Instruction::Or)
285 InterestingVal = ConstantInt::getTrue(I->getContext());
286 else
287 InterestingVal = ConstantInt::getFalse(I->getContext());
288
289 // Scan for the sentinel.
290 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
291 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
292 Result.push_back(LHSVals[i]);
293 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
294 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
295 Result.push_back(RHSVals[i]);
296 return !Result.empty();
297 }
298
299 // TODO: Should handle the NOT form of XOR.
300
301 }
302
303 // Handle compare with phi operand, where the PHI is defined in this block.
304 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
305 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
306 if (PN && PN->getParent() == BB) {
307 // We can do this simplification if any comparisons fold to true or false.
308 // See if any do.
309 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
310 BasicBlock *PredBB = PN->getIncomingBlock(i);
311 Value *LHS = PN->getIncomingValue(i);
312 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
313
314 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), LHS, RHS);
315 if (Res == 0) continue;
316
317 if (isa<UndefValue>(Res))
318 Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
319 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
320 Result.push_back(std::make_pair(CI, PredBB));
321 }
322
323 return !Result.empty();
324 }
325
326 // TODO: We could also recurse to see if we can determine constants another
327 // way.
328 }
329 return false;
330}
331
332
Chris Lattner6bf77502008-04-22 07:05:46 +0000333
Chris Lattnere33583b2009-10-11 04:18:15 +0000334/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
335/// in an undefined jump, decide which block is best to revector to.
336///
337/// Since we can pick an arbitrary destination, we pick the successor with the
338/// fewest predecessors. This should reduce the in-degree of the others.
339///
340static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
341 TerminatorInst *BBTerm = BB->getTerminator();
342 unsigned MinSucc = 0;
343 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
344 // Compute the successor with the minimum number of predecessors.
345 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
346 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
347 TestBB = BBTerm->getSuccessor(i);
348 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
349 if (NumPreds < MinNumPreds)
350 MinSucc = i;
351 }
352
353 return MinSucc;
354}
355
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000356/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000357/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000358bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000359 // If this block has a single predecessor, and if that pred has a single
360 // successor, merge the blocks. This encourages recursive jump threading
361 // because now the condition in this block can be threaded through
362 // predecessors of our predecessor block.
Chris Lattner78567252009-11-06 18:15:14 +0000363 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000364 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
365 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000366 // If SinglePred was a loop header, BB becomes one.
367 if (LoopHeaders.erase(SinglePred))
368 LoopHeaders.insert(BB);
369
Chris Lattner3d86d242008-11-27 19:25:19 +0000370 // Remember if SinglePred was the entry block of the function. If so, we
371 // will need to move BB back to the entry position.
372 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000373 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000374
375 if (isEntry && BB != &BB->getParent()->getEntryBlock())
376 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000377 return true;
378 }
Chris Lattner78567252009-11-06 18:15:14 +0000379 }
380
381 // Look to see if the terminator is a branch of switch, if not we can't thread
382 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000383 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000384 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
385 // Can't thread an unconditional jump.
386 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000387 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000388 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000389 Condition = SI->getCondition();
390 else
391 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000392
393 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000394 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000395 // other blocks.
396 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000397 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000398 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000399 ++NumFolds;
400 ConstantFoldTerminator(BB);
401 return true;
402 }
403
Chris Lattner421fa9e2008-12-03 07:48:08 +0000404 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000405 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000406 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000407 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000408
409 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000410 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000411 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000412 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000413 BBTerm->getSuccessor(i)->removePredecessor(BB);
414 }
415
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000416 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000417 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000418 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000419 BBTerm->eraseFromParent();
420 return true;
421 }
422
423 Instruction *CondInst = dyn_cast<Instruction>(Condition);
424
425 // If the condition is an instruction defined in another block, see if a
426 // predecessor has the same condition:
427 // br COND, BBX, BBY
428 // BBX:
429 // br COND, BBZ, BBW
430 if (!Condition->hasOneUse() && // Multiple uses.
431 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
432 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
433 if (isa<BranchInst>(BB->getTerminator())) {
434 for (; PI != E; ++PI)
435 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
436 if (PBI->isConditional() && PBI->getCondition() == Condition &&
437 ProcessBranchOnDuplicateCond(*PI, BB))
438 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000439 } else {
440 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
441 for (; PI != E; ++PI)
442 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
443 if (PSI->getCondition() == Condition &&
444 ProcessSwitchOnDuplicateCond(*PI, BB))
445 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000446 }
447 }
448
Chris Lattner421fa9e2008-12-03 07:48:08 +0000449 // All the rest of our checks depend on the condition being an instruction.
450 if (CondInst == 0)
451 return false;
452
Chris Lattner177480b2008-04-20 21:13:06 +0000453 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000454 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
455 if (PN->getParent() == BB)
456 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000457
Nick Lewycky9683f182009-06-19 04:56:29 +0000458 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Chris Lattner90b92472009-11-06 18:24:32 +0000459 if (!isa<PHINode>(CondCmp->getOperand(0)) ||
460 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
461 // If we have a comparison, loop over the predecessors to see if there is
462 // a condition with a lexically identical value.
463 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
464 for (; PI != E; ++PI)
465 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
466 if (PBI->isConditional() && *PI != BB) {
467 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
468 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
469 CI->getOperand(1) == CondCmp->getOperand(1) &&
470 CI->getPredicate() == CondCmp->getPredicate()) {
471 // TODO: Could handle things like (x != 4) --> (x == 17)
472 if (ProcessBranchOnDuplicateCond(*PI, BB))
473 return true;
474 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000475 }
476 }
Chris Lattner90b92472009-11-06 18:24:32 +0000477 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000478 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000479
480 // Check for some cases that are worth simplifying. Right now we want to look
481 // for loads that are used by a switch or by the condition for the branch. If
482 // we see one, check to see if it's partially redundant. If so, insert a PHI
483 // which can then be used to thread the values.
484 //
485 // This is particularly important because reg2mem inserts loads and stores all
486 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000487 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000488 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
489 if (isa<Constant>(CondCmp->getOperand(1)))
490 SimplifyValue = CondCmp->getOperand(0);
491
492 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
493 if (SimplifyPartiallyRedundantLoad(LI))
494 return true;
495
Chris Lattner78567252009-11-06 18:15:14 +0000496
497 // Handle a variety of cases where we are branching on something derived from
498 // a PHI node in the current block. If we can prove that any predecessors
499 // compute a predictable value based on a PHI node, thread those predecessors.
500 //
501 // We only bother doing this if the current block has a PHI node and if the
502 // conditional instruction lives in the current block. If either condition
503 // fail, this won't be a computable value anyway.
504 if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
505 if (ProcessThreadableEdges(CondInst, BB))
506 return true;
507
508
Chris Lattner69e067f2008-11-27 05:07:53 +0000509 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
510 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000511
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000512 return false;
513}
514
Chris Lattner421fa9e2008-12-03 07:48:08 +0000515/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
516/// block that jump on exactly the same condition. This means that we almost
517/// always know the direction of the edge in the DESTBB:
518/// PREDBB:
519/// br COND, DESTBB, BBY
520/// DESTBB:
521/// br COND, BBZ, BBW
522///
523/// If DESTBB has multiple predecessors, we can't just constant fold the branch
524/// in DESTBB, we have to thread over it.
525bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
526 BasicBlock *BB) {
527 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
528
529 // If both successors of PredBB go to DESTBB, we don't know anything. We can
530 // fold the branch to an unconditional one, which allows other recursive
531 // simplifications.
532 bool BranchDir;
533 if (PredBI->getSuccessor(1) != BB)
534 BranchDir = true;
535 else if (PredBI->getSuccessor(0) != BB)
536 BranchDir = false;
537 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000538 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000539 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000540 ++NumFolds;
541 ConstantFoldTerminator(PredBB);
542 return true;
543 }
544
545 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
546
547 // If the dest block has one predecessor, just fix the branch condition to a
548 // constant and fold it.
549 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000550 DEBUG(errs() << " In block '" << BB->getName()
551 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000552 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000553 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000554 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
556 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000557 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000558 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000559 return true;
560 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000561
Chris Lattner421fa9e2008-12-03 07:48:08 +0000562
563 // Next, figure out which successor we are threading to.
564 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
565
Mike Stumpfe095f32009-05-04 18:40:41 +0000566 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000567 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000568}
569
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000570/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
571/// block that switch on exactly the same condition. This means that we almost
572/// always know the direction of the edge in the DESTBB:
573/// PREDBB:
574/// switch COND [... DESTBB, BBY ... ]
575/// DESTBB:
576/// switch COND [... BBZ, BBW ]
577///
578/// Optimizing switches like this is very important, because simplifycfg builds
579/// switches out of repeated 'if' conditions.
580bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
581 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000582 // Can't thread edge to self.
583 if (PredBB == DestBB)
584 return false;
585
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000586 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
587 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
588
589 // There are a variety of optimizations that we can potentially do on these
590 // blocks: we order them from most to least preferable.
591
592 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
593 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000594 // growth. Skip debug info first.
595 BasicBlock::iterator BBI = DestBB->begin();
596 while (isa<DbgInfoIntrinsic>(BBI))
597 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000598
599 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000600 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000601 bool MadeChange = false;
602 // Ignore the default edge for now.
603 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
604 ConstantInt *DestVal = DestSI->getCaseValue(i);
605 BasicBlock *DestSucc = DestSI->getSuccessor(i);
606
607 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
608 // PredSI has an explicit case for it. If so, forward. If it is covered
609 // by the default case, we can't update PredSI.
610 unsigned PredCase = PredSI->findCaseValue(DestVal);
611 if (PredCase == 0) continue;
612
613 // If PredSI doesn't go to DestBB on this value, then it won't reach the
614 // case on this condition.
615 if (PredSI->getSuccessor(PredCase) != DestBB &&
616 DestSI->getSuccessor(i) != DestBB)
617 continue;
618
619 // Otherwise, we're safe to make the change. Make sure that the edge from
620 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000621 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
622 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000623
624 // If the destination has PHI nodes, just split the edge for updating
625 // simplicity.
626 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
627 SplitCriticalEdge(DestSI, i, this);
628 DestSucc = DestSI->getSuccessor(i);
629 }
630 FoldSingleEntryPHINodes(DestSucc);
631 PredSI->setSuccessor(PredCase, DestSucc);
632 MadeChange = true;
633 }
634
635 if (MadeChange)
636 return true;
637 }
638
639 return false;
640}
641
642
Chris Lattner69e067f2008-11-27 05:07:53 +0000643/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
644/// load instruction, eliminate it by replacing it with a PHI node. This is an
645/// important optimization that encourages jump threading, and needs to be run
646/// interlaced with other jump threading tasks.
647bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
648 // Don't hack volatile loads.
649 if (LI->isVolatile()) return false;
650
651 // If the load is defined in a block with exactly one predecessor, it can't be
652 // partially redundant.
653 BasicBlock *LoadBB = LI->getParent();
654 if (LoadBB->getSinglePredecessor())
655 return false;
656
657 Value *LoadedPtr = LI->getOperand(0);
658
659 // If the loaded operand is defined in the LoadBB, it can't be available.
660 // FIXME: Could do PHI translation, that would be fun :)
661 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
662 if (PtrOp->getParent() == LoadBB)
663 return false;
664
665 // Scan a few instructions up from the load, to see if it is obviously live at
666 // the entry to its block.
667 BasicBlock::iterator BBIt = LI;
668
Chris Lattner52c95852008-11-27 08:10:05 +0000669 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
670 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000671 // If the value if the load is locally available within the block, just use
672 // it. This frequently occurs for reg2mem'd allocas.
673 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000674
675 // If the returned value is the load itself, replace with an undef. This can
676 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000677 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000678 LI->replaceAllUsesWith(AvailableVal);
679 LI->eraseFromParent();
680 return true;
681 }
682
683 // Otherwise, if we scanned the whole block and got to the top of the block,
684 // we know the block is locally transparent to the load. If not, something
685 // might clobber its value.
686 if (BBIt != LoadBB->begin())
687 return false;
688
689
690 SmallPtrSet<BasicBlock*, 8> PredsScanned;
691 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
692 AvailablePredsTy AvailablePreds;
693 BasicBlock *OneUnavailablePred = 0;
694
695 // If we got here, the loaded value is transparent through to the start of the
696 // block. Check to see if it is available in any of the predecessor blocks.
697 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
698 PI != PE; ++PI) {
699 BasicBlock *PredBB = *PI;
700
701 // If we already scanned this predecessor, skip it.
702 if (!PredsScanned.insert(PredBB))
703 continue;
704
705 // Scan the predecessor to see if the value is available in the pred.
706 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000707 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000708 if (!PredAvailable) {
709 OneUnavailablePred = PredBB;
710 continue;
711 }
712
713 // If so, this load is partially redundant. Remember this info so that we
714 // can create a PHI node.
715 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
716 }
717
718 // If the loaded value isn't available in any predecessor, it isn't partially
719 // redundant.
720 if (AvailablePreds.empty()) return false;
721
722 // Okay, the loaded value is available in at least one (and maybe all!)
723 // predecessors. If the value is unavailable in more than one unique
724 // predecessor, we want to insert a merge block for those common predecessors.
725 // This ensures that we only have to insert one reload, thus not increasing
726 // code size.
727 BasicBlock *UnavailablePred = 0;
728
729 // If there is exactly one predecessor where the value is unavailable, the
730 // already computed 'OneUnavailablePred' block is it. If it ends in an
731 // unconditional branch, we know that it isn't a critical edge.
732 if (PredsScanned.size() == AvailablePreds.size()+1 &&
733 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
734 UnavailablePred = OneUnavailablePred;
735 } else if (PredsScanned.size() != AvailablePreds.size()) {
736 // Otherwise, we had multiple unavailable predecessors or we had a critical
737 // edge from the one.
738 SmallVector<BasicBlock*, 8> PredsToSplit;
739 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
740
741 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
742 AvailablePredSet.insert(AvailablePreds[i].first);
743
744 // Add all the unavailable predecessors to the PredsToSplit list.
745 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
746 PI != PE; ++PI)
747 if (!AvailablePredSet.count(*PI))
748 PredsToSplit.push_back(*PI);
749
750 // Split them out to their own block.
751 UnavailablePred =
752 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
753 "thread-split", this);
754 }
755
756 // If the value isn't available in all predecessors, then there will be
757 // exactly one where it isn't available. Insert a load on that edge and add
758 // it to the AvailablePreds list.
759 if (UnavailablePred) {
760 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
761 "Can't handle critical edge here!");
762 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
763 UnavailablePred->getTerminator());
764 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
765 }
766
767 // Now we know that each predecessor of this block has a value in
768 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000769 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000770
771 // Create a PHI node at the start of the block for the PRE'd load value.
772 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
773 PN->takeName(LI);
774
775 // Insert new entries into the PHI for each predecessor. A single block may
776 // have multiple entries here.
777 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
778 ++PI) {
779 AvailablePredsTy::iterator I =
780 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
781 std::make_pair(*PI, (Value*)0));
782
783 assert(I != AvailablePreds.end() && I->first == *PI &&
784 "Didn't find entry for predecessor!");
785
786 PN->addIncoming(I->second, I->first);
787 }
788
789 //cerr << "PRE: " << *LI << *PN << "\n";
790
791 LI->replaceAllUsesWith(PN);
792 LI->eraseFromParent();
793
794 return true;
795}
796
Chris Lattner78567252009-11-06 18:15:14 +0000797/// FindMostPopularDest - The specified list contains multiple possible
798/// threadable destinations. Pick the one that occurs the most frequently in
799/// the list.
800static BasicBlock *
801FindMostPopularDest(BasicBlock *BB,
802 const SmallVectorImpl<std::pair<BasicBlock*,
803 BasicBlock*> > &PredToDestList) {
804 assert(!PredToDestList.empty());
805
806 // Determine popularity. If there are multiple possible destinations, we
807 // explicitly choose to ignore 'undef' destinations. We prefer to thread
808 // blocks with known and real destinations to threading undef. We'll handle
809 // them later if interesting.
810 DenseMap<BasicBlock*, unsigned> DestPopularity;
811 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
812 if (PredToDestList[i].second)
813 DestPopularity[PredToDestList[i].second]++;
814
815 // Find the most popular dest.
816 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
817 BasicBlock *MostPopularDest = DPI->first;
818 unsigned Popularity = DPI->second;
819 SmallVector<BasicBlock*, 4> SamePopularity;
820
821 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
822 // If the popularity of this entry isn't higher than the popularity we've
823 // seen so far, ignore it.
824 if (DPI->second < Popularity)
825 ; // ignore.
826 else if (DPI->second == Popularity) {
827 // If it is the same as what we've seen so far, keep track of it.
828 SamePopularity.push_back(DPI->first);
829 } else {
830 // If it is more popular, remember it.
831 SamePopularity.clear();
832 MostPopularDest = DPI->first;
833 Popularity = DPI->second;
834 }
835 }
836
837 // Okay, now we know the most popular destination. If there is more than
838 // destination, we need to determine one. This is arbitrary, but we need
839 // to make a deterministic decision. Pick the first one that appears in the
840 // successor list.
841 if (!SamePopularity.empty()) {
842 SamePopularity.push_back(MostPopularDest);
843 TerminatorInst *TI = BB->getTerminator();
844 for (unsigned i = 0; ; ++i) {
845 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
846
847 if (std::find(SamePopularity.begin(), SamePopularity.end(),
848 TI->getSuccessor(i)) == SamePopularity.end())
849 continue;
850
851 MostPopularDest = TI->getSuccessor(i);
852 break;
853 }
854 }
855
856 // Okay, we have finally picked the most popular destination.
857 return MostPopularDest;
858}
859
860bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
861 BasicBlock *BB) {
862 // If threading this would thread across a loop header, don't even try to
863 // thread the edge.
864 if (LoopHeaders.count(BB))
865 return false;
866
867
868
869 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
870 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
871 return false;
872 assert(!PredValues.empty() &&
873 "ComputeValueKnownInPredecessors returned true with no values");
874
875 DEBUG(errs() << "IN BB: " << *BB;
876 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
877 errs() << " BB '" << BB->getName() << "': FOUND condition = ";
878 if (PredValues[i].first)
879 errs() << *PredValues[i].first;
880 else
881 errs() << "UNDEF";
882 errs() << " for pred '" << PredValues[i].second->getName()
883 << "'.\n";
884 });
885
886 // Decide what we want to thread through. Convert our list of known values to
887 // a list of known destinations for each pred. This also discards duplicate
888 // predecessors and keeps track of the undefined inputs (which are represented
889 // as a null dest in the PredToDestList.
890 SmallPtrSet<BasicBlock*, 16> SeenPreds;
891 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
892
893 BasicBlock *OnlyDest = 0;
894 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
895
896 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
897 BasicBlock *Pred = PredValues[i].second;
898 if (!SeenPreds.insert(Pred))
899 continue; // Duplicate predecessor entry.
900
901 // If the predecessor ends with an indirect goto, we can't change its
902 // destination.
903 if (isa<IndirectBrInst>(Pred->getTerminator()))
904 continue;
905
906 ConstantInt *Val = PredValues[i].first;
907
908 BasicBlock *DestBB;
909 if (Val == 0) // Undef.
910 DestBB = 0;
911 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
912 DestBB = BI->getSuccessor(Val->isZero());
913 else {
914 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
915 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
916 }
917
918 // If we have exactly one destination, remember it for efficiency below.
919 if (i == 0)
920 OnlyDest = DestBB;
921 else if (OnlyDest != DestBB)
922 OnlyDest = MultipleDestSentinel;
923
924 PredToDestList.push_back(std::make_pair(Pred, DestBB));
925 }
926
927 // If all edges were unthreadable, we fail.
928 if (PredToDestList.empty())
929 return false;
930
931 // Determine which is the most common successor. If we have many inputs and
932 // this block is a switch, we want to start by threading the batch that goes
933 // to the most popular destination first. If we only know about one
934 // threadable destination (the common case) we can avoid this.
935 BasicBlock *MostPopularDest = OnlyDest;
936
937 if (MostPopularDest == MultipleDestSentinel)
938 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
939
940 // Now that we know what the most popular destination is, factor all
941 // predecessors that will jump to it into a single predecessor.
942 SmallVector<BasicBlock*, 16> PredsToFactor;
943 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
Chris Lattner79f03322009-11-06 23:19:58 +0000944 if (PredToDestList[i].second == MostPopularDest) {
945 BasicBlock *Pred = PredToDestList[i].first;
946
947 // This predecessor may be a switch or something else that has multiple
948 // edges to the block. Factor each of these edges by listing them
949 // according to # occurrences in PredsToFactor.
950 TerminatorInst *PredTI = Pred->getTerminator();
951 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
952 if (PredTI->getSuccessor(i) == BB)
953 PredsToFactor.push_back(Pred);
954 }
Chris Lattner78567252009-11-06 18:15:14 +0000955
956 BasicBlock *PredToThread;
957 if (PredsToFactor.size() == 1)
958 PredToThread = PredsToFactor[0];
959 else {
960 DEBUG(errs() << " Factoring out " << PredsToFactor.size()
961 << " common predecessors.\n");
962 PredToThread = SplitBlockPredecessors(BB, &PredsToFactor[0],
963 PredsToFactor.size(),
964 ".thr_comm", this);
965 }
966
967 // If the threadable edges are branching on an undefined value, we get to pick
968 // the destination that these predecessors should get to.
969 if (MostPopularDest == 0)
970 MostPopularDest = BB->getTerminator()->
971 getSuccessor(GetBestDestForJumpOnUndef(BB));
972
973 // Ok, try to thread it!
974 return ThreadEdge(BB, PredToThread, MostPopularDest);
975}
Chris Lattner69e067f2008-11-27 05:07:53 +0000976
Chris Lattnere33583b2009-10-11 04:18:15 +0000977/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000978/// the current block. See if there are any simplifications we can do based on
979/// inputs to the phi node.
980///
981bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000982 BasicBlock *BB = PN->getParent();
983
Chris Lattnerf7807f62009-11-06 18:22:54 +0000984 // If any of the predecessor blocks end in an unconditional branch, we can
985 // *duplicate* the jump into that block in order to further encourage jump
986 // threading and to eliminate cases where we have branch on a phi of an icmp
987 // (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +0000988
989 // We don't want to do this tranformation for switches, because we don't
990 // really want to duplicate a switch.
991 if (isa<SwitchInst>(BB->getTerminator()))
992 return false;
993
994 // Look for unconditional branch predecessors.
995 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
996 BasicBlock *PredBB = PN->getIncomingBlock(i);
997 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
998 if (PredBr->isUnconditional() &&
999 // Try to duplicate BB into PredBB.
1000 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
1001 return true;
1002 }
1003
Chris Lattner6b65f472009-10-11 04:40:21 +00001004 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001005}
1006
Chris Lattnera5ddb592008-04-22 21:40:39 +00001007
Chris Lattner78c552e2009-10-11 07:24:57 +00001008/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1009/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1010/// NewPred using the entries from OldPred (suitably mapped).
1011static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1012 BasicBlock *OldPred,
1013 BasicBlock *NewPred,
1014 DenseMap<Instruction*, Value*> &ValueMap) {
1015 for (BasicBlock::iterator PNI = PHIBB->begin();
1016 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1017 // Ok, we have a PHI node. Figure out what the incoming value was for the
1018 // DestBlock.
1019 Value *IV = PN->getIncomingValueForBlock(OldPred);
1020
1021 // Remap the value if necessary.
1022 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1023 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1024 if (I != ValueMap.end())
1025 IV = I->second;
1026 }
1027
1028 PN->addIncoming(IV, NewPred);
1029 }
1030}
Chris Lattner6bf77502008-04-22 07:05:46 +00001031
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001032/// ThreadEdge - We have decided that it is safe and profitable to thread an
1033/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
1034/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +00001035bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001036 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001037 // If threading to the same block as we come from, we would infinite loop.
1038 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001039 DEBUG(errs() << " Not threading across BB '" << BB->getName()
1040 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001041 return false;
1042 }
1043
1044 // If threading this would thread across a loop header, don't thread the edge.
1045 // See the comments above FindLoopHeaders for justifications and caveats.
1046 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001047 DEBUG(errs() << " Not threading from '" << PredBB->getName()
1048 << "' across loop header BB '" << BB->getName()
1049 << "' to dest BB '" << SuccBB->getName()
1050 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001051 return false;
1052 }
1053
Chris Lattner78c552e2009-10-11 07:24:57 +00001054 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1055 if (JumpThreadCost > Threshold) {
1056 DEBUG(errs() << " Not threading BB '" << BB->getName()
1057 << "' - Cost is too high: " << JumpThreadCost << "\n");
1058 return false;
1059 }
1060
Mike Stumpfe095f32009-05-04 18:40:41 +00001061 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001062 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001063 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001064 << ", across block:\n "
1065 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001066
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001067 // We are going to have to map operands from the original BB block to the new
1068 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1069 // account for entry from PredBB.
1070 DenseMap<Instruction*, Value*> ValueMapping;
1071
Owen Anderson1d0be152009-08-13 21:58:54 +00001072 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1073 BB->getName()+".thread",
1074 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001075 NewBB->moveAfter(PredBB);
1076
1077 BasicBlock::iterator BI = BB->begin();
1078 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1079 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1080
1081 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1082 // mapping and using it to remap operands in the cloned instructions.
1083 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001084 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001085 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001086 NewBB->getInstList().push_back(New);
1087 ValueMapping[BI] = New;
1088
1089 // Remap operands to patch up intra-block references.
1090 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001091 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1092 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1093 if (I != ValueMapping.end())
1094 New->setOperand(i, I->second);
1095 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001096 }
1097
1098 // We didn't copy the terminator from BB over to NewBB, because there is now
1099 // an unconditional jump to SuccBB. Insert the unconditional jump.
1100 BranchInst::Create(SuccBB, NewBB);
1101
1102 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1103 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001104 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001105
Chris Lattner433a0db2009-10-10 09:05:58 +00001106 // If there were values defined in BB that are used outside the block, then we
1107 // now have to update all uses of the value to use either the original value,
1108 // the cloned value, or some PHI derived value. This can require arbitrary
1109 // PHI insertion, of which we are prepared to do, clean these up now.
1110 SSAUpdater SSAUpdate;
1111 SmallVector<Use*, 16> UsesToRename;
1112 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1113 // Scan all uses of this instruction to see if it is used outside of its
1114 // block, and if so, record them in UsesToRename.
1115 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1116 ++UI) {
1117 Instruction *User = cast<Instruction>(*UI);
1118 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1119 if (UserPN->getIncomingBlock(UI) == BB)
1120 continue;
1121 } else if (User->getParent() == BB)
1122 continue;
1123
1124 UsesToRename.push_back(&UI.getUse());
1125 }
1126
1127 // If there are no uses outside the block, we're done with this instruction.
1128 if (UsesToRename.empty())
1129 continue;
1130
1131 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1132
1133 // We found a use of I outside of BB. Rename all uses of I that are outside
1134 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1135 // with the two values we know.
1136 SSAUpdate.Initialize(I);
1137 SSAUpdate.AddAvailableValue(BB, I);
1138 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1139
1140 while (!UsesToRename.empty())
1141 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1142 DEBUG(errs() << "\n");
1143 }
1144
1145
Chris Lattneref0c6742008-12-01 04:48:07 +00001146 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001147 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1148 // us to simplify any PHI nodes in BB.
1149 TerminatorInst *PredTerm = PredBB->getTerminator();
1150 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1151 if (PredTerm->getSuccessor(i) == BB) {
1152 BB->removePredecessor(PredBB);
1153 PredTerm->setSuccessor(i, NewBB);
1154 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001155
1156 // At this point, the IR is fully up to date and consistent. Do a quick scan
1157 // over the new instructions and zap any that are constants or dead. This
1158 // frequently happens because of phi translation.
1159 BI = NewBB->begin();
1160 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1161 Instruction *Inst = BI++;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001162 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001163 Inst->replaceAllUsesWith(C);
1164 Inst->eraseFromParent();
1165 continue;
1166 }
1167
1168 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1169 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001170
1171 // Threaded an edge!
1172 ++NumThreads;
1173 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001174}
Chris Lattner78c552e2009-10-11 07:24:57 +00001175
1176/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1177/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1178/// If we can duplicate the contents of BB up into PredBB do so now, this
1179/// improves the odds that the branch will be on an analyzable instruction like
1180/// a compare.
1181bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1182 BasicBlock *PredBB) {
1183 // If BB is a loop header, then duplicating this block outside the loop would
1184 // cause us to transform this into an irreducible loop, don't do this.
1185 // See the comments above FindLoopHeaders for justifications and caveats.
1186 if (LoopHeaders.count(BB)) {
1187 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1188 << "' into predecessor block '" << PredBB->getName()
1189 << "' - it might create an irreducible loop!\n");
1190 return false;
1191 }
1192
1193 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1194 if (DuplicationCost > Threshold) {
1195 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1196 << "' - Cost is too high: " << DuplicationCost << "\n");
1197 return false;
1198 }
1199
1200 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1201 // of PredBB.
1202 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1203 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1204 << DuplicationCost << " block is:" << *BB << "\n");
1205
1206 // We are going to have to map operands from the original BB block into the
1207 // PredBB block. Evaluate PHI nodes in BB.
1208 DenseMap<Instruction*, Value*> ValueMapping;
1209
1210 BasicBlock::iterator BI = BB->begin();
1211 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1212 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1213
1214 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1215
1216 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1217 // mapping and using it to remap operands in the cloned instructions.
1218 for (; BI != BB->end(); ++BI) {
1219 Instruction *New = BI->clone();
1220 New->setName(BI->getName());
1221 PredBB->getInstList().insert(OldPredBranch, New);
1222 ValueMapping[BI] = New;
1223
1224 // Remap operands to patch up intra-block references.
1225 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1226 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1227 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1228 if (I != ValueMapping.end())
1229 New->setOperand(i, I->second);
1230 }
1231 }
1232
1233 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1234 // add entries to the PHI nodes for branch from PredBB now.
1235 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1236 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1237 ValueMapping);
1238 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1239 ValueMapping);
1240
1241 // If there were values defined in BB that are used outside the block, then we
1242 // now have to update all uses of the value to use either the original value,
1243 // the cloned value, or some PHI derived value. This can require arbitrary
1244 // PHI insertion, of which we are prepared to do, clean these up now.
1245 SSAUpdater SSAUpdate;
1246 SmallVector<Use*, 16> UsesToRename;
1247 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1248 // Scan all uses of this instruction to see if it is used outside of its
1249 // block, and if so, record them in UsesToRename.
1250 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1251 ++UI) {
1252 Instruction *User = cast<Instruction>(*UI);
1253 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1254 if (UserPN->getIncomingBlock(UI) == BB)
1255 continue;
1256 } else if (User->getParent() == BB)
1257 continue;
1258
1259 UsesToRename.push_back(&UI.getUse());
1260 }
1261
1262 // If there are no uses outside the block, we're done with this instruction.
1263 if (UsesToRename.empty())
1264 continue;
1265
1266 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1267
1268 // We found a use of I outside of BB. Rename all uses of I that are outside
1269 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1270 // with the two values we know.
1271 SSAUpdate.Initialize(I);
1272 SSAUpdate.AddAvailableValue(BB, I);
1273 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1274
1275 while (!UsesToRename.empty())
1276 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1277 DEBUG(errs() << "\n");
1278 }
1279
1280 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1281 // that we nuked.
1282 BB->removePredecessor(PredBB);
1283
1284 // Remove the unconditional branch at the end of the PredBB block.
1285 OldPredBranch->eraseFromParent();
1286
1287 ++NumDupes;
1288 return true;
1289}
1290
1291