add some missing quotes in debug output
[llvm/avr.git] / lib / Transforms / Scalar / JumpThreading.cpp
blob559b8cb72a9f5b39983c7ac1c7bf461fa99cc7d5
1 //===- 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 //
10 // This file implements the Jump Threading pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jump-threading"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ValueHandle.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
34 STATISTIC(NumThreads, "Number of jumps threaded");
35 STATISTIC(NumFolds, "Number of terminators folded");
37 static cl::opt<unsigned>
38 Threshold("jump-threading-threshold",
39 cl::desc("Max block size to duplicate for jump threading"),
40 cl::init(6), cl::Hidden);
42 namespace {
43 /// This pass performs 'jump threading', which looks at blocks that have
44 /// multiple predecessors and multiple successors. If one or more of the
45 /// predecessors of the block can be proven to always jump to one of the
46 /// successors, we forward the edge from the predecessor to the successor by
47 /// duplicating the contents of this block.
48 ///
49 /// An example of when this can occur is code like this:
50 ///
51 /// if () { ...
52 /// X = 4;
53 /// }
54 /// if (X < 3) {
55 ///
56 /// In this case, the unconditional branch at the end of the first if can be
57 /// revectored to the false side of the second if.
58 ///
59 class JumpThreading : public FunctionPass {
60 TargetData *TD;
61 #ifdef NDEBUG
62 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
63 #else
64 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
65 #endif
66 public:
67 static char ID; // Pass identification
68 JumpThreading() : FunctionPass(&ID) {}
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 bool runOnFunction(Function &F);
74 void FindLoopHeaders(Function &F);
76 bool ProcessBlock(BasicBlock *BB);
77 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB,
78 unsigned JumpThreadCost);
79 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
80 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
81 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
83 bool ProcessJumpOnPHI(PHINode *PN);
84 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
85 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
87 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
91 char JumpThreading::ID = 0;
92 static RegisterPass<JumpThreading>
93 X("jump-threading", "Jump Threading");
95 // Public interface to the Jump Threading pass
96 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
98 /// runOnFunction - Top level algorithm.
99 ///
100 bool JumpThreading::runOnFunction(Function &F) {
101 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
102 TD = getAnalysisIfAvailable<TargetData>();
104 FindLoopHeaders(F);
106 bool AnotherIteration = true, EverChanged = false;
107 while (AnotherIteration) {
108 AnotherIteration = false;
109 bool Changed = false;
110 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
111 BasicBlock *BB = I;
112 while (ProcessBlock(BB))
113 Changed = true;
115 ++I;
117 // If the block is trivially dead, zap it. This eliminates the successor
118 // edges which simplifies the CFG.
119 if (pred_begin(BB) == pred_end(BB) &&
120 BB != &BB->getParent()->getEntryBlock()) {
121 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
122 << "' with terminator: " << *BB->getTerminator());
123 LoopHeaders.erase(BB);
124 DeleteDeadBlock(BB);
125 Changed = true;
128 AnotherIteration = Changed;
129 EverChanged |= Changed;
132 LoopHeaders.clear();
133 return EverChanged;
136 /// FindLoopHeaders - We do not want jump threading to turn proper loop
137 /// structures into irreducible loops. Doing this breaks up the loop nesting
138 /// hierarchy and pessimizes later transformations. To prevent this from
139 /// happening, we first have to find the loop headers. Here we approximate this
140 /// by finding targets of backedges in the CFG.
142 /// Note that there definitely are cases when we want to allow threading of
143 /// edges across a loop header. For example, threading a jump from outside the
144 /// loop (the preheader) to an exit block of the loop is definitely profitable.
145 /// It is also almost always profitable to thread backedges from within the loop
146 /// to exit blocks, and is often profitable to thread backedges to other blocks
147 /// within the loop (forming a nested loop). This simple analysis is not rich
148 /// enough to track all of these properties and keep it up-to-date as the CFG
149 /// mutates, so we don't allow any of these transformations.
151 void JumpThreading::FindLoopHeaders(Function &F) {
152 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
153 FindFunctionBackedges(F, Edges);
155 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
156 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
160 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
161 /// value for the PHI, factor them together so we get one block to thread for
162 /// the whole group.
163 /// This is important for things like "phi i1 [true, true, false, true, x]"
164 /// where we only need to clone the block for the true blocks once.
166 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
167 SmallVector<BasicBlock*, 16> CommonPreds;
168 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
169 if (PN->getIncomingValue(i) == Val)
170 CommonPreds.push_back(PN->getIncomingBlock(i));
172 if (CommonPreds.size() == 1)
173 return CommonPreds[0];
175 DEBUG(errs() << " Factoring out " << CommonPreds.size()
176 << " common predecessors.\n");
177 return SplitBlockPredecessors(PN->getParent(),
178 &CommonPreds[0], CommonPreds.size(),
179 ".thr_comm", this);
183 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
184 /// thread across it.
185 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
186 /// Ignore PHI nodes, these will be flattened when duplication happens.
187 BasicBlock::const_iterator I = BB->getFirstNonPHI();
189 // Sum up the cost of each instruction until we get to the terminator. Don't
190 // include the terminator because the copy won't include it.
191 unsigned Size = 0;
192 for (; !isa<TerminatorInst>(I); ++I) {
193 // Debugger intrinsics don't incur code size.
194 if (isa<DbgInfoIntrinsic>(I)) continue;
196 // If this is a pointer->pointer bitcast, it is free.
197 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
198 continue;
200 // All other instructions count for at least one unit.
201 ++Size;
203 // Calls are more expensive. If they are non-intrinsic calls, we model them
204 // as having cost of 4. If they are a non-vector intrinsic, we model them
205 // as having cost of 2 total, and if they are a vector intrinsic, we model
206 // them as having cost 1.
207 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
208 if (!isa<IntrinsicInst>(CI))
209 Size += 3;
210 else if (!isa<VectorType>(CI->getType()))
211 Size += 1;
215 // Threading through a switch statement is particularly profitable. If this
216 // block ends in a switch, decrease its cost to make it more likely to happen.
217 if (isa<SwitchInst>(I))
218 Size = Size > 6 ? Size-6 : 0;
220 return Size;
223 /// ProcessBlock - If there are any predecessors whose control can be threaded
224 /// through to a successor, transform them now.
225 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
226 // If this block has a single predecessor, and if that pred has a single
227 // successor, merge the blocks. This encourages recursive jump threading
228 // because now the condition in this block can be threaded through
229 // predecessors of our predecessor block.
230 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
231 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
232 SinglePred != BB) {
233 // If SinglePred was a loop header, BB becomes one.
234 if (LoopHeaders.erase(SinglePred))
235 LoopHeaders.insert(BB);
237 // Remember if SinglePred was the entry block of the function. If so, we
238 // will need to move BB back to the entry position.
239 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
240 MergeBasicBlockIntoOnlyPred(BB);
242 if (isEntry && BB != &BB->getParent()->getEntryBlock())
243 BB->moveBefore(&BB->getParent()->getEntryBlock());
244 return true;
247 // See if this block ends with a branch or switch. If so, see if the
248 // condition is a phi node. If so, and if an entry of the phi node is a
249 // constant, we can thread the block.
250 Value *Condition;
251 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
252 // Can't thread an unconditional jump.
253 if (BI->isUnconditional()) return false;
254 Condition = BI->getCondition();
255 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
256 Condition = SI->getCondition();
257 else
258 return false; // Must be an invoke.
260 // If the terminator of this block is branching on a constant, simplify the
261 // terminator to an unconditional branch. This can occur due to threading in
262 // other blocks.
263 if (isa<ConstantInt>(Condition)) {
264 DEBUG(errs() << " In block '" << BB->getName()
265 << "' folding terminator: " << *BB->getTerminator());
266 ++NumFolds;
267 ConstantFoldTerminator(BB);
268 return true;
271 // If the terminator is branching on an undef, we can pick any of the
272 // successors to branch to. Since this is arbitrary, we pick the successor
273 // with the fewest predecessors. This should reduce the in-degree of the
274 // others.
275 if (isa<UndefValue>(Condition)) {
276 TerminatorInst *BBTerm = BB->getTerminator();
277 unsigned MinSucc = 0;
278 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
279 // Compute the successor with the minimum number of predecessors.
280 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
281 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
282 TestBB = BBTerm->getSuccessor(i);
283 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
284 if (NumPreds < MinNumPreds)
285 MinSucc = i;
288 // Fold the branch/switch.
289 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
290 if (i == MinSucc) continue;
291 BBTerm->getSuccessor(i)->removePredecessor(BB);
294 DEBUG(errs() << " In block '" << BB->getName()
295 << "' folding undef terminator: " << *BBTerm);
296 BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
297 BBTerm->eraseFromParent();
298 return true;
301 Instruction *CondInst = dyn_cast<Instruction>(Condition);
303 // If the condition is an instruction defined in another block, see if a
304 // predecessor has the same condition:
305 // br COND, BBX, BBY
306 // BBX:
307 // br COND, BBZ, BBW
308 if (!Condition->hasOneUse() && // Multiple uses.
309 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
310 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
311 if (isa<BranchInst>(BB->getTerminator())) {
312 for (; PI != E; ++PI)
313 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
314 if (PBI->isConditional() && PBI->getCondition() == Condition &&
315 ProcessBranchOnDuplicateCond(*PI, BB))
316 return true;
317 } else {
318 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
319 for (; PI != E; ++PI)
320 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
321 if (PSI->getCondition() == Condition &&
322 ProcessSwitchOnDuplicateCond(*PI, BB))
323 return true;
327 // All the rest of our checks depend on the condition being an instruction.
328 if (CondInst == 0)
329 return false;
331 // See if this is a phi node in the current block.
332 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
333 if (PN->getParent() == BB)
334 return ProcessJumpOnPHI(PN);
336 // If this is a conditional branch whose condition is and/or of a phi, try to
337 // simplify it.
338 if ((CondInst->getOpcode() == Instruction::And ||
339 CondInst->getOpcode() == Instruction::Or) &&
340 isa<BranchInst>(BB->getTerminator()) &&
341 ProcessBranchOnLogical(CondInst, BB,
342 CondInst->getOpcode() == Instruction::And))
343 return true;
345 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
346 if (isa<PHINode>(CondCmp->getOperand(0))) {
347 // If we have "br (phi != 42)" and the phi node has any constant values
348 // as operands, we can thread through this block.
350 // If we have "br (cmp phi, x)" and the phi node contains x such that the
351 // comparison uniquely identifies the branch target, we can thread
352 // through this block.
354 if (ProcessBranchOnCompare(CondCmp, BB))
355 return true;
358 // If we have a comparison, loop over the predecessors to see if there is
359 // a condition with the same value.
360 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
361 for (; PI != E; ++PI)
362 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
363 if (PBI->isConditional() && *PI != BB) {
364 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
365 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
366 CI->getOperand(1) == CondCmp->getOperand(1) &&
367 CI->getPredicate() == CondCmp->getPredicate()) {
368 // TODO: Could handle things like (x != 4) --> (x == 17)
369 if (ProcessBranchOnDuplicateCond(*PI, BB))
370 return true;
376 // Check for some cases that are worth simplifying. Right now we want to look
377 // for loads that are used by a switch or by the condition for the branch. If
378 // we see one, check to see if it's partially redundant. If so, insert a PHI
379 // which can then be used to thread the values.
381 // This is particularly important because reg2mem inserts loads and stores all
382 // over the place, and this blocks jump threading if we don't zap them.
383 Value *SimplifyValue = CondInst;
384 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
385 if (isa<Constant>(CondCmp->getOperand(1)))
386 SimplifyValue = CondCmp->getOperand(0);
388 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
389 if (SimplifyPartiallyRedundantLoad(LI))
390 return true;
392 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
393 // "(X == 4)" thread through this block.
395 return false;
398 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
399 /// block that jump on exactly the same condition. This means that we almost
400 /// always know the direction of the edge in the DESTBB:
401 /// PREDBB:
402 /// br COND, DESTBB, BBY
403 /// DESTBB:
404 /// br COND, BBZ, BBW
406 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
407 /// in DESTBB, we have to thread over it.
408 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
409 BasicBlock *BB) {
410 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
412 // If both successors of PredBB go to DESTBB, we don't know anything. We can
413 // fold the branch to an unconditional one, which allows other recursive
414 // simplifications.
415 bool BranchDir;
416 if (PredBI->getSuccessor(1) != BB)
417 BranchDir = true;
418 else if (PredBI->getSuccessor(0) != BB)
419 BranchDir = false;
420 else {
421 DEBUG(errs() << " In block '" << PredBB->getName()
422 << "' folding terminator: " << *PredBB->getTerminator());
423 ++NumFolds;
424 ConstantFoldTerminator(PredBB);
425 return true;
428 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
430 // If the dest block has one predecessor, just fix the branch condition to a
431 // constant and fold it.
432 if (BB->getSinglePredecessor()) {
433 DEBUG(errs() << " In block '" << BB->getName()
434 << "' folding condition to '" << BranchDir << "': "
435 << *BB->getTerminator());
436 ++NumFolds;
437 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
438 BranchDir));
439 ConstantFoldTerminator(BB);
440 return true;
443 // Otherwise we need to thread from PredBB to DestBB's successor which
444 // involves code duplication. Check to see if it is worth it.
445 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
446 if (JumpThreadCost > Threshold) {
447 DEBUG(errs() << " Not threading BB '" << BB->getName()
448 << "' - Cost is too high: " << JumpThreadCost << "\n");
449 return false;
452 // Next, figure out which successor we are threading to.
453 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
455 // Ok, try to thread it!
456 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
459 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
460 /// block that switch on exactly the same condition. This means that we almost
461 /// always know the direction of the edge in the DESTBB:
462 /// PREDBB:
463 /// switch COND [... DESTBB, BBY ... ]
464 /// DESTBB:
465 /// switch COND [... BBZ, BBW ]
467 /// Optimizing switches like this is very important, because simplifycfg builds
468 /// switches out of repeated 'if' conditions.
469 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
470 BasicBlock *DestBB) {
471 // Can't thread edge to self.
472 if (PredBB == DestBB)
473 return false;
476 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
477 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
479 // There are a variety of optimizations that we can potentially do on these
480 // blocks: we order them from most to least preferable.
482 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
483 // directly to their destination. This does not introduce *any* code size
484 // growth. Skip debug info first.
485 BasicBlock::iterator BBI = DestBB->begin();
486 while (isa<DbgInfoIntrinsic>(BBI))
487 BBI++;
489 // FIXME: Thread if it just contains a PHI.
490 if (isa<SwitchInst>(BBI)) {
491 bool MadeChange = false;
492 // Ignore the default edge for now.
493 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
494 ConstantInt *DestVal = DestSI->getCaseValue(i);
495 BasicBlock *DestSucc = DestSI->getSuccessor(i);
497 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
498 // PredSI has an explicit case for it. If so, forward. If it is covered
499 // by the default case, we can't update PredSI.
500 unsigned PredCase = PredSI->findCaseValue(DestVal);
501 if (PredCase == 0) continue;
503 // If PredSI doesn't go to DestBB on this value, then it won't reach the
504 // case on this condition.
505 if (PredSI->getSuccessor(PredCase) != DestBB &&
506 DestSI->getSuccessor(i) != DestBB)
507 continue;
509 // Otherwise, we're safe to make the change. Make sure that the edge from
510 // DestSI to DestSucc is not critical and has no PHI nodes.
511 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
512 DEBUG(errs() << "THROUGH: " << *DestSI);
514 // If the destination has PHI nodes, just split the edge for updating
515 // simplicity.
516 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
517 SplitCriticalEdge(DestSI, i, this);
518 DestSucc = DestSI->getSuccessor(i);
520 FoldSingleEntryPHINodes(DestSucc);
521 PredSI->setSuccessor(PredCase, DestSucc);
522 MadeChange = true;
525 if (MadeChange)
526 return true;
529 return false;
533 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
534 /// load instruction, eliminate it by replacing it with a PHI node. This is an
535 /// important optimization that encourages jump threading, and needs to be run
536 /// interlaced with other jump threading tasks.
537 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
538 // Don't hack volatile loads.
539 if (LI->isVolatile()) return false;
541 // If the load is defined in a block with exactly one predecessor, it can't be
542 // partially redundant.
543 BasicBlock *LoadBB = LI->getParent();
544 if (LoadBB->getSinglePredecessor())
545 return false;
547 Value *LoadedPtr = LI->getOperand(0);
549 // If the loaded operand is defined in the LoadBB, it can't be available.
550 // FIXME: Could do PHI translation, that would be fun :)
551 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
552 if (PtrOp->getParent() == LoadBB)
553 return false;
555 // Scan a few instructions up from the load, to see if it is obviously live at
556 // the entry to its block.
557 BasicBlock::iterator BBIt = LI;
559 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
560 BBIt, 6)) {
561 // If the value if the load is locally available within the block, just use
562 // it. This frequently occurs for reg2mem'd allocas.
563 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
565 // If the returned value is the load itself, replace with an undef. This can
566 // only happen in dead loops.
567 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
568 LI->replaceAllUsesWith(AvailableVal);
569 LI->eraseFromParent();
570 return true;
573 // Otherwise, if we scanned the whole block and got to the top of the block,
574 // we know the block is locally transparent to the load. If not, something
575 // might clobber its value.
576 if (BBIt != LoadBB->begin())
577 return false;
580 SmallPtrSet<BasicBlock*, 8> PredsScanned;
581 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
582 AvailablePredsTy AvailablePreds;
583 BasicBlock *OneUnavailablePred = 0;
585 // If we got here, the loaded value is transparent through to the start of the
586 // block. Check to see if it is available in any of the predecessor blocks.
587 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
588 PI != PE; ++PI) {
589 BasicBlock *PredBB = *PI;
591 // If we already scanned this predecessor, skip it.
592 if (!PredsScanned.insert(PredBB))
593 continue;
595 // Scan the predecessor to see if the value is available in the pred.
596 BBIt = PredBB->end();
597 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
598 if (!PredAvailable) {
599 OneUnavailablePred = PredBB;
600 continue;
603 // If so, this load is partially redundant. Remember this info so that we
604 // can create a PHI node.
605 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
608 // If the loaded value isn't available in any predecessor, it isn't partially
609 // redundant.
610 if (AvailablePreds.empty()) return false;
612 // Okay, the loaded value is available in at least one (and maybe all!)
613 // predecessors. If the value is unavailable in more than one unique
614 // predecessor, we want to insert a merge block for those common predecessors.
615 // This ensures that we only have to insert one reload, thus not increasing
616 // code size.
617 BasicBlock *UnavailablePred = 0;
619 // If there is exactly one predecessor where the value is unavailable, the
620 // already computed 'OneUnavailablePred' block is it. If it ends in an
621 // unconditional branch, we know that it isn't a critical edge.
622 if (PredsScanned.size() == AvailablePreds.size()+1 &&
623 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
624 UnavailablePred = OneUnavailablePred;
625 } else if (PredsScanned.size() != AvailablePreds.size()) {
626 // Otherwise, we had multiple unavailable predecessors or we had a critical
627 // edge from the one.
628 SmallVector<BasicBlock*, 8> PredsToSplit;
629 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
631 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
632 AvailablePredSet.insert(AvailablePreds[i].first);
634 // Add all the unavailable predecessors to the PredsToSplit list.
635 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
636 PI != PE; ++PI)
637 if (!AvailablePredSet.count(*PI))
638 PredsToSplit.push_back(*PI);
640 // Split them out to their own block.
641 UnavailablePred =
642 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
643 "thread-split", this);
646 // If the value isn't available in all predecessors, then there will be
647 // exactly one where it isn't available. Insert a load on that edge and add
648 // it to the AvailablePreds list.
649 if (UnavailablePred) {
650 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
651 "Can't handle critical edge here!");
652 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
653 UnavailablePred->getTerminator());
654 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
657 // Now we know that each predecessor of this block has a value in
658 // AvailablePreds, sort them for efficient access as we're walking the preds.
659 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
661 // Create a PHI node at the start of the block for the PRE'd load value.
662 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
663 PN->takeName(LI);
665 // Insert new entries into the PHI for each predecessor. A single block may
666 // have multiple entries here.
667 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
668 ++PI) {
669 AvailablePredsTy::iterator I =
670 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
671 std::make_pair(*PI, (Value*)0));
673 assert(I != AvailablePreds.end() && I->first == *PI &&
674 "Didn't find entry for predecessor!");
676 PN->addIncoming(I->second, I->first);
679 //cerr << "PRE: " << *LI << *PN << "\n";
681 LI->replaceAllUsesWith(PN);
682 LI->eraseFromParent();
684 return true;
688 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
689 /// the current block. See if there are any simplifications we can do based on
690 /// inputs to the phi node.
691 ///
692 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
693 // See if the phi node has any constant values. If so, we can determine where
694 // the corresponding predecessor will branch.
695 ConstantInt *PredCst = 0;
696 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
697 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
698 break;
700 // If no incoming value has a constant, we don't know the destination of any
701 // predecessors.
702 if (PredCst == 0)
703 return false;
705 // See if the cost of duplicating this block is low enough.
706 BasicBlock *BB = PN->getParent();
707 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
708 if (JumpThreadCost > Threshold) {
709 DEBUG(errs() << " Not threading BB '" << BB->getName()
710 << "' - Cost is too high: " << JumpThreadCost << "\n");
711 return false;
714 // If so, we can actually do this threading. Merge any common predecessors
715 // that will act the same.
716 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
718 // Next, figure out which successor we are threading to.
719 BasicBlock *SuccBB;
720 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
721 SuccBB = BI->getSuccessor(PredCst ==
722 ConstantInt::getFalse(PredBB->getContext()));
723 else {
724 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
725 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
728 // Ok, try to thread it!
729 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
732 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
733 /// whose condition is an AND/OR where one side is PN. If PN has constant
734 /// operands that permit us to evaluate the condition for some operand, thread
735 /// through the block. For example with:
736 /// br (and X, phi(Y, Z, false))
737 /// the predecessor corresponding to the 'false' will always jump to the false
738 /// destination of the branch.
740 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
741 bool isAnd) {
742 // If this is a binary operator tree of the same AND/OR opcode, check the
743 // LHS/RHS.
744 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
745 if ((isAnd && BO->getOpcode() == Instruction::And) ||
746 (!isAnd && BO->getOpcode() == Instruction::Or)) {
747 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
748 return true;
749 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
750 return true;
753 // If this isn't a PHI node, we can't handle it.
754 PHINode *PN = dyn_cast<PHINode>(V);
755 if (!PN || PN->getParent() != BB) return false;
757 // We can only do the simplification for phi nodes of 'false' with AND or
758 // 'true' with OR. See if we have any entries in the phi for this.
759 unsigned PredNo = ~0U;
760 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
761 !isAnd);
762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
763 if (PN->getIncomingValue(i) == PredCst) {
764 PredNo = i;
765 break;
769 // If no match, bail out.
770 if (PredNo == ~0U)
771 return false;
773 // See if the cost of duplicating this block is low enough.
774 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
775 if (JumpThreadCost > Threshold) {
776 DEBUG(errs() << " Not threading BB '" << BB->getName()
777 << "' - Cost is too high: " << JumpThreadCost << "\n");
778 return false;
781 // If so, we can actually do this threading. Merge any common predecessors
782 // that will act the same.
783 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
785 // Next, figure out which successor we are threading to. If this was an AND,
786 // the constant must be FALSE, and we must be targeting the 'false' block.
787 // If this is an OR, the constant must be TRUE, and we must be targeting the
788 // 'true' block.
789 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
791 // Ok, try to thread it!
792 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
795 /// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
796 /// hand sides of the compare instruction, try to determine the result. If the
797 /// result can not be determined, a null pointer is returned.
798 static Constant *GetResultOfComparison(CmpInst::Predicate pred,
799 Value *LHS, Value *RHS,
800 LLVMContext &Context) {
801 if (Constant *CLHS = dyn_cast<Constant>(LHS))
802 if (Constant *CRHS = dyn_cast<Constant>(RHS))
803 return ConstantExpr::getCompare(pred, CLHS, CRHS);
805 if (LHS == RHS)
806 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
807 return ICmpInst::isTrueWhenEqual(pred) ?
808 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
810 return 0;
813 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
814 /// node and a value. If we can identify when the comparison is true between
815 /// the phi inputs and the value, we can fold the compare for that edge and
816 /// thread through it.
817 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
818 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
819 Value *RHS = Cmp->getOperand(1);
821 // If the phi isn't in the current block, an incoming edge to this block
822 // doesn't control the destination.
823 if (PN->getParent() != BB)
824 return false;
826 // We can do this simplification if any comparisons fold to true or false.
827 // See if any do.
828 Value *PredVal = 0;
829 bool TrueDirection = false;
830 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
831 PredVal = PN->getIncomingValue(i);
833 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
834 RHS, Cmp->getContext());
835 if (!Res) {
836 PredVal = 0;
837 continue;
840 // If this folded to a constant expr, we can't do anything.
841 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
842 TrueDirection = ResC->getZExtValue();
843 break;
845 // If this folded to undef, just go the false way.
846 if (isa<UndefValue>(Res)) {
847 TrueDirection = false;
848 break;
851 // Otherwise, we can't fold this input.
852 PredVal = 0;
855 // If no match, bail out.
856 if (PredVal == 0)
857 return false;
859 // See if the cost of duplicating this block is low enough.
860 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
861 if (JumpThreadCost > Threshold) {
862 DEBUG(errs() << " Not threading BB '" << BB->getName()
863 << "' - Cost is too high: " << JumpThreadCost << "\n");
864 return false;
867 // If so, we can actually do this threading. Merge any common predecessors
868 // that will act the same.
869 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
871 // Next, get our successor.
872 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
874 // Ok, try to thread it!
875 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
879 /// ThreadEdge - We have decided that it is safe and profitable to thread an
880 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
881 /// change.
882 bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
883 BasicBlock *SuccBB, unsigned JumpThreadCost) {
885 // If threading to the same block as we come from, we would infinite loop.
886 if (SuccBB == BB) {
887 DEBUG(errs() << " Not threading across BB '" << BB->getName()
888 << "' - would thread to self!\n");
889 return false;
892 // If threading this would thread across a loop header, don't thread the edge.
893 // See the comments above FindLoopHeaders for justifications and caveats.
894 if (LoopHeaders.count(BB)) {
895 DEBUG(errs() << " Not threading from '" << PredBB->getName()
896 << "' across loop header BB '" << BB->getName()
897 << "' to dest BB '" << SuccBB->getName()
898 << "' - it might create an irreducible loop!\n");
899 return false;
902 // And finally, do it!
903 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
904 << SuccBB->getName() << "' with cost: " << JumpThreadCost
905 << ", across block:\n "
906 << *BB << "\n");
908 // Jump Threading can not update SSA properties correctly if the values
909 // defined in the duplicated block are used outside of the block itself. For
910 // this reason, we spill all values that are used outside of BB to the stack.
911 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
912 if (!I->isUsedOutsideOfBlock(BB))
913 continue;
915 // We found a use of I outside of BB. Create a new stack slot to
916 // break this inter-block usage pattern.
917 DemoteRegToStack(*I);
920 // We are going to have to map operands from the original BB block to the new
921 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
922 // account for entry from PredBB.
923 DenseMap<Instruction*, Value*> ValueMapping;
925 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
926 BB->getName()+".thread",
927 BB->getParent(), BB);
928 NewBB->moveAfter(PredBB);
930 BasicBlock::iterator BI = BB->begin();
931 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
932 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
934 // Clone the non-phi instructions of BB into NewBB, keeping track of the
935 // mapping and using it to remap operands in the cloned instructions.
936 for (; !isa<TerminatorInst>(BI); ++BI) {
937 Instruction *New = BI->clone(BI->getContext());
938 New->setName(BI->getName());
939 NewBB->getInstList().push_back(New);
940 ValueMapping[BI] = New;
942 // Remap operands to patch up intra-block references.
943 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
944 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
945 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
946 if (I != ValueMapping.end())
947 New->setOperand(i, I->second);
951 // We didn't copy the terminator from BB over to NewBB, because there is now
952 // an unconditional jump to SuccBB. Insert the unconditional jump.
953 BranchInst::Create(SuccBB, NewBB);
955 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
956 // PHI nodes for NewBB now.
957 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
958 PHINode *PN = cast<PHINode>(PNI);
959 // Ok, we have a PHI node. Figure out what the incoming value was for the
960 // DestBlock.
961 Value *IV = PN->getIncomingValueForBlock(BB);
963 // Remap the value if necessary.
964 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
965 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
966 if (I != ValueMapping.end())
967 IV = I->second;
969 PN->addIncoming(IV, NewBB);
972 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
973 // NewBB instead of BB. This eliminates predecessors from BB, which requires
974 // us to simplify any PHI nodes in BB.
975 TerminatorInst *PredTerm = PredBB->getTerminator();
976 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
977 if (PredTerm->getSuccessor(i) == BB) {
978 BB->removePredecessor(PredBB);
979 PredTerm->setSuccessor(i, NewBB);
982 // At this point, the IR is fully up to date and consistent. Do a quick scan
983 // over the new instructions and zap any that are constants or dead. This
984 // frequently happens because of phi translation.
985 BI = NewBB->begin();
986 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
987 Instruction *Inst = BI++;
988 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
989 Inst->replaceAllUsesWith(C);
990 Inst->eraseFromParent();
991 continue;
994 RecursivelyDeleteTriviallyDeadInstructions(Inst);
997 // Threaded an edge!
998 ++NumThreads;
999 return true;