1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/PostOrderIterator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
59 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60 cl::init(10), cl::Hidden);
62 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63 LoopInfo *LI; // Loop information
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector<Loop*> LoopProcessWorklist;
69 SmallPtrSet<Value *,8> UnswitchedVals;
72 bool runOnLoop(Loop *L, LPPassManager &LPM);
74 /// This transformation requires natural loop information & requires that
75 /// loop preheaders be inserted into the CFG...
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addPreservedID(LoopSimplifyID);
80 AU.addRequired<LoopInfo>();
81 AU.addPreserved<LoopInfo>();
82 AU.addRequiredID(LCSSAID);
83 AU.addPreservedID(LCSSAID);
87 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
89 void RemoveLoopFromWorklist(Loop *L) {
90 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
91 LoopProcessWorklist.end(), L);
92 if (I != LoopProcessWorklist.end())
93 LoopProcessWorklist.erase(I);
96 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
97 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
98 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
99 BasicBlock *ExitBlock);
100 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
101 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
102 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
104 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
105 Constant *Val, bool isEqual);
107 void SimplifyCode(std::vector<Instruction*> &Worklist);
108 void RemoveBlockIfDead(BasicBlock *BB,
109 std::vector<Instruction*> &Worklist);
110 void RemoveLoopFromHierarchy(Loop *L);
112 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
115 LoopPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
117 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
118 /// invariant in the loop, or has an invariant piece, return the invariant.
119 /// Otherwise, return null.
120 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
121 // Constants should be folded, not unswitched on!
122 if (isa<Constant>(Cond)) return false;
124 // TODO: Handle: br (VARIANT|INVARIANT).
125 // TODO: Hoist simple expressions out of loops.
126 if (L->isLoopInvariant(Cond)) return Cond;
128 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
129 if (BO->getOpcode() == Instruction::And ||
130 BO->getOpcode() == Instruction::Or) {
131 // If either the left or right side is invariant, we can unswitch on this,
132 // which will cause the branch to go away in one loop and the condition to
133 // simplify in the other one.
134 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
136 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
143 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
144 assert(L->isLCSSAForm());
145 LI = &getAnalysis<LoopInfo>();
147 bool Changed = false;
149 // Loop over all of the basic blocks in the loop. If we find an interior
150 // block that is branching on a loop-invariant condition, we can unswitch this
152 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
154 TerminatorInst *TI = (*I)->getTerminator();
155 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
156 // If this isn't branching on an invariant condition, we can't unswitch
158 if (BI->isConditional()) {
159 // See if this, or some part of it, is loop invariant. If so, we can
160 // unswitch on it if we desire.
161 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
162 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
168 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
169 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
170 if (LoopCond && SI->getNumCases() > 1) {
171 // Find a value to unswitch on:
172 // FIXME: this should chose the most expensive case!
173 Constant *UnswitchVal = SI->getCaseValue(1);
174 // Do not process same value again and again.
175 if (!UnswitchedVals.insert(UnswitchVal))
178 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
185 // Scan the instructions to check for unswitchable values.
186 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
188 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
189 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
190 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
198 assert(L->isLCSSAForm());
203 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
204 /// 1. Exit the loop with no side effects.
205 /// 2. Branch to the latch block with no side-effects.
207 /// If these conditions are true, we return true and set ExitBB to the block we
210 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
212 std::set<BasicBlock*> &Visited) {
213 if (!Visited.insert(BB).second) {
214 // Already visited and Ok, end of recursion.
216 } else if (!L->contains(BB)) {
217 // Otherwise, this is a loop exit, this is fine so long as this is the
219 if (ExitBB != 0) return false;
224 // Otherwise, this is an unvisited intra-loop node. Check all successors.
225 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
226 // Check to see if the successor is a trivial loop exit.
227 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
231 // Okay, everything after this looks good, check to make sure that this block
232 // doesn't include any side effects.
233 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
234 if (I->mayWriteToMemory())
240 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
241 /// leads to an exit from the specified loop, and has no side-effects in the
242 /// process. If so, return the block that is exited to, otherwise return null.
243 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
244 std::set<BasicBlock*> Visited;
245 Visited.insert(L->getHeader()); // Branches to header are ok.
246 BasicBlock *ExitBB = 0;
247 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
252 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
253 /// trivial: that is, that the condition controls whether or not the loop does
254 /// anything at all. If this is a trivial condition, unswitching produces no
255 /// code duplications (equivalently, it produces a simpler loop and a new empty
256 /// loop, which gets deleted).
258 /// If this is a trivial condition, return true, otherwise return false. When
259 /// returning true, this sets Cond and Val to the condition that controls the
260 /// trivial condition: when Cond dynamically equals Val, the loop is known to
261 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
264 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
265 BasicBlock **LoopExit = 0) {
266 BasicBlock *Header = L->getHeader();
267 TerminatorInst *HeaderTerm = Header->getTerminator();
269 BasicBlock *LoopExitBB = 0;
270 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
271 // If the header block doesn't end with a conditional branch on Cond, we
273 if (!BI->isConditional() || BI->getCondition() != Cond)
276 // Check to see if a successor of the branch is guaranteed to go to the
277 // latch block or exit through a one exit block without having any
278 // side-effects. If so, determine the value of Cond that causes it to do
280 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
281 if (Val) *Val = ConstantInt::getTrue();
282 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
283 if (Val) *Val = ConstantInt::getFalse();
285 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
286 // If this isn't a switch on Cond, we can't handle it.
287 if (SI->getCondition() != Cond) return false;
289 // Check to see if a successor of the switch is guaranteed to go to the
290 // latch block or exit through a one exit block without having any
291 // side-effects. If so, determine the value of Cond that causes it to do
292 // this. Note that we can't trivially unswitch on the default case.
293 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
294 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
295 // Okay, we found a trivial case, remember the value that is trivial.
296 if (Val) *Val = SI->getCaseValue(i);
301 // If we didn't find a single unique LoopExit block, or if the loop exit block
302 // contains phi nodes, this isn't trivial.
303 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
304 return false; // Can't handle this.
306 if (LoopExit) *LoopExit = LoopExitBB;
308 // We already know that nothing uses any scalar values defined inside of this
309 // loop. As such, we just have to check to see if this loop will execute any
310 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
311 // part of the loop that the code *would* execute. We already checked the
312 // tail, check the header now.
313 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
314 if (I->mayWriteToMemory())
319 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
320 /// we choose to unswitch the specified loop on the specified value.
322 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
323 // If the condition is trivial, always unswitch. There is no code growth for
325 if (IsTrivialUnswitchCondition(L, LIC))
328 // FIXME: This is really overly conservative. However, more liberal
329 // estimations have thus far resulted in excessive unswitching, which is bad
330 // both in compile time and in code size. This should be replaced once
331 // someone figures out how a good estimation.
332 return L->getBlocks().size();
335 // FIXME: this is brain dead. It should take into consideration code
337 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
340 // Do not include empty blocks in the cost calculation. This happen due to
341 // loop canonicalization and will be removed.
342 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
345 // Count basic blocks.
352 /// UnswitchIfProfitable - We have found that we can unswitch L when
353 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
354 /// unswitch the loop, reprocess the pieces, then return true.
355 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
356 // Check to see if it would be profitable to unswitch this loop.
357 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
358 if (Cost > Threshold) {
359 // FIXME: this should estimate growth by the amount of code shared by the
360 // resultant unswitched loops.
362 DOUT << "NOT unswitching loop %"
363 << L->getHeader()->getName() << ", cost too high: "
364 << L->getBlocks().size() << "\n";
368 // If this is a trivial condition to unswitch (which results in no code
369 // duplication), do it now.
371 BasicBlock *ExitBlock;
372 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
373 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
375 UnswitchNontrivialCondition(LoopCond, Val, L);
381 /// SplitBlock - Split the specified block at the specified instruction - every
382 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
383 /// to a new block. The two blocks are joined by an unconditional branch and
384 /// the loop info is updated.
386 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
387 BasicBlock::iterator SplitIt = SplitPt;
388 while (isa<PHINode>(SplitIt))
390 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
392 // The new block lives in whichever loop the old one did.
393 if (Loop *L = LI->getLoopFor(Old))
394 L->addBasicBlockToLoop(New, *LI);
400 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
401 TerminatorInst *LatchTerm = BB->getTerminator();
402 unsigned SuccNum = 0;
403 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
404 assert(i != e && "Didn't find edge?");
405 if (LatchTerm->getSuccessor(i) == Succ) {
411 // If this is a critical edge, let SplitCriticalEdge do it.
412 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
413 return LatchTerm->getSuccessor(SuccNum);
415 // If the edge isn't critical, then BB has a single successor or Succ has a
416 // single pred. Split the block.
417 BasicBlock::iterator SplitPoint;
418 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
419 // If the successor only has a single pred, split the top of the successor
421 assert(SP == BB && "CFG broken");
422 return SplitBlock(Succ, Succ->begin());
424 // Otherwise, if BB has a single successor, split it at the bottom of the
426 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
427 "Should have a single succ!");
428 return SplitBlock(BB, BB->getTerminator());
434 // RemapInstruction - Convert the instruction operands from referencing the
435 // current values into those specified by ValueMap.
437 static inline void RemapInstruction(Instruction *I,
438 DenseMap<const Value *, Value*> &ValueMap) {
439 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
440 Value *Op = I->getOperand(op);
441 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
442 if (It != ValueMap.end()) Op = It->second;
443 I->setOperand(op, Op);
447 /// CloneLoop - Recursively clone the specified loop and all of its children,
448 /// mapping the blocks with the specified map.
449 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
450 LoopInfo *LI, LPPassManager *LPM) {
451 Loop *New = new Loop();
453 LPM->insertLoop(New, PL);
455 // Add all of the blocks in L to the new loop.
456 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
458 if (LI->getLoopFor(*I) == L)
459 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
461 // Add all of the subloops to the new loop.
462 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
463 CloneLoop(*I, New, VM, LI, LPM);
468 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
469 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
470 /// code immediately before InsertPt.
471 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
472 BasicBlock *TrueDest,
473 BasicBlock *FalseDest,
474 Instruction *InsertPt) {
475 // Insert a conditional branch on LIC to the two preheaders. The original
476 // code is the true version and the new code is the false version.
477 Value *BranchVal = LIC;
478 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
479 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
480 else if (Val != ConstantInt::getTrue())
481 // We want to enter the new loop when the condition is true.
482 std::swap(TrueDest, FalseDest);
484 // Insert the new branch.
485 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
489 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
490 /// condition in it (a cond branch from its header block to its latch block,
491 /// where the path through the loop that doesn't execute its body has no
492 /// side-effects), unswitch it. This doesn't involve any code duplication, just
493 /// moving the conditional branch outside of the loop and updating loop info.
494 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
496 BasicBlock *ExitBlock) {
497 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
498 << L->getHeader()->getName() << " [" << L->getBlocks().size()
499 << " blocks] in Function " << L->getHeader()->getParent()->getName()
500 << " on cond: " << *Val << " == " << *Cond << "\n";
502 // First step, split the preheader, so that we know that there is a safe place
503 // to insert the conditional branch. We will change 'OrigPH' to have a
504 // conditional branch on Cond.
505 BasicBlock *OrigPH = L->getLoopPreheader();
506 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
508 // Now that we have a place to insert the conditional branch, create a place
509 // to branch to: this is the exit block out of the loop that we should
512 // Split this block now, so that the loop maintains its exit block, and so
513 // that the jump from the preheader can execute the contents of the exit block
514 // without actually branching to it (the exit block should be dominated by the
515 // loop header, not the preheader).
516 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
517 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
519 // Okay, now we have a position to branch from and a position to branch to,
520 // insert the new conditional branch.
521 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
522 OrigPH->getTerminator());
523 OrigPH->getTerminator()->eraseFromParent();
525 // We need to reprocess this loop, it could be unswitched again.
528 // Now that we know that the loop is never entered when this condition is a
529 // particular value, rewrite the loop with this info. We know that this will
530 // at least eliminate the old branch.
531 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
536 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
537 /// equal Val. Split it into loop versions and test the condition outside of
538 /// either loop. Return the loops created as Out1/Out2.
539 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
541 Function *F = L->getHeader()->getParent();
542 DOUT << "loop-unswitch: Unswitching loop %"
543 << L->getHeader()->getName() << " [" << L->getBlocks().size()
544 << " blocks] in Function " << F->getName()
545 << " when '" << *Val << "' == " << *LIC << "\n";
547 // LoopBlocks contains all of the basic blocks of the loop, including the
548 // preheader of the loop, the body of the loop, and the exit blocks of the
549 // loop, in that order.
550 std::vector<BasicBlock*> LoopBlocks;
552 // First step, split the preheader and exit blocks, and add these blocks to
553 // the LoopBlocks list.
554 BasicBlock *OrigPreheader = L->getLoopPreheader();
555 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
557 // We want the loop to come after the preheader, but before the exit blocks.
558 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
560 std::vector<BasicBlock*> ExitBlocks;
561 L->getUniqueExitBlocks(ExitBlocks);
563 // Split all of the edges from inside the loop to their exit blocks. Update
564 // the appropriate Phi nodes as we do so.
565 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
566 BasicBlock *ExitBlock = ExitBlocks[i];
567 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
569 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
570 assert(L->contains(Preds[j]) &&
571 "All preds of loop exit blocks must be the same loop!");
572 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
573 BasicBlock* StartBlock = Preds[j];
574 BasicBlock* EndBlock;
575 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
576 EndBlock = MiddleBlock;
577 MiddleBlock = EndBlock->getSinglePredecessor();;
579 EndBlock = ExitBlock;
582 std::set<PHINode*> InsertedPHIs;
583 PHINode* OldLCSSA = 0;
584 for (BasicBlock::iterator I = EndBlock->begin();
585 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
586 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
587 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
588 OldLCSSA->getName() + ".us-lcssa",
589 MiddleBlock->getTerminator());
590 NewLCSSA->addIncoming(OldValue, StartBlock);
591 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
593 InsertedPHIs.insert(NewLCSSA);
596 BasicBlock::iterator InsertPt = EndBlock->begin();
597 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
598 for (BasicBlock::iterator I = MiddleBlock->begin();
599 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
601 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
602 OldLCSSA->getName() + ".us-lcssa",
604 OldLCSSA->replaceAllUsesWith(NewLCSSA);
605 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
610 // The exit blocks may have been changed due to edge splitting, recompute.
612 L->getUniqueExitBlocks(ExitBlocks);
614 // Add exit blocks to the loop blocks.
615 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
617 // Next step, clone all of the basic blocks that make up the loop (including
618 // the loop preheader and exit blocks), keeping track of the mapping between
619 // the instructions and blocks.
620 std::vector<BasicBlock*> NewBlocks;
621 NewBlocks.reserve(LoopBlocks.size());
622 DenseMap<const Value*, Value*> ValueMap;
623 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
624 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
625 NewBlocks.push_back(New);
626 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
629 // Splice the newly inserted blocks into the function right before the
630 // original preheader.
631 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
632 NewBlocks[0], F->end());
634 // Now we create the new Loop object for the versioned loop.
635 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
636 Loop *ParentLoop = L->getParentLoop();
638 // Make sure to add the cloned preheader and exit blocks to the parent loop
640 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
643 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
644 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
645 // The new exit block should be in the same loop as the old one.
646 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
647 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
649 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
650 "Exit block should have been split to have one successor!");
651 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
653 // If the successor of the exit block had PHI nodes, add an entry for
656 for (BasicBlock::iterator I = ExitSucc->begin();
657 (PN = dyn_cast<PHINode>(I)); ++I) {
658 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
659 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
660 if (It != ValueMap.end()) V = It->second;
661 PN->addIncoming(V, NewExit);
665 // Rewrite the code to refer to itself.
666 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
667 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
668 E = NewBlocks[i]->end(); I != E; ++I)
669 RemapInstruction(I, ValueMap);
671 // Rewrite the original preheader to select between versions of the loop.
672 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
673 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
674 "Preheader splitting did not work correctly!");
676 // Emit the new branch that selects between the two versions of this loop.
677 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
678 OldBR->eraseFromParent();
680 LoopProcessWorklist.push_back(NewLoop);
683 // Now we rewrite the original code to know that the condition is true and the
684 // new code to know that the condition is false.
685 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
687 // It's possible that simplifying one loop could cause the other to be
688 // deleted. If so, don't simplify it.
689 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
690 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
693 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
695 static void RemoveFromWorklist(Instruction *I,
696 std::vector<Instruction*> &Worklist) {
697 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
699 while (WI != Worklist.end()) {
700 unsigned Offset = WI-Worklist.begin();
702 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
706 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
707 /// program, replacing all uses with V and update the worklist.
708 static void ReplaceUsesOfWith(Instruction *I, Value *V,
709 std::vector<Instruction*> &Worklist) {
710 DOUT << "Replace with '" << *V << "': " << *I;
712 // Add uses to the worklist, which may be dead now.
713 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
714 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
715 Worklist.push_back(Use);
717 // Add users to the worklist which may be simplified now.
718 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
720 Worklist.push_back(cast<Instruction>(*UI));
721 I->replaceAllUsesWith(V);
722 I->eraseFromParent();
723 RemoveFromWorklist(I, Worklist);
727 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
728 /// information, and remove any dead successors it has.
730 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
731 std::vector<Instruction*> &Worklist) {
732 if (pred_begin(BB) != pred_end(BB)) {
733 // This block isn't dead, since an edge to BB was just removed, see if there
734 // are any easy simplifications we can do now.
735 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
736 // If it has one pred, fold phi nodes in BB.
737 while (isa<PHINode>(BB->begin()))
738 ReplaceUsesOfWith(BB->begin(),
739 cast<PHINode>(BB->begin())->getIncomingValue(0),
742 // If this is the header of a loop and the only pred is the latch, we now
743 // have an unreachable loop.
744 if (Loop *L = LI->getLoopFor(BB))
745 if (L->getHeader() == BB && L->contains(Pred)) {
746 // Remove the branch from the latch to the header block, this makes
747 // the header dead, which will make the latch dead (because the header
748 // dominates the latch).
749 Pred->getTerminator()->eraseFromParent();
750 new UnreachableInst(Pred);
752 // The loop is now broken, remove it from LI.
753 RemoveLoopFromHierarchy(L);
755 // Reprocess the header, which now IS dead.
756 RemoveBlockIfDead(BB, Worklist);
760 // If pred ends in a uncond branch, add uncond branch to worklist so that
761 // the two blocks will get merged.
762 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
763 if (BI->isUnconditional())
764 Worklist.push_back(BI);
769 DOUT << "Nuking dead block: " << *BB;
771 // Remove the instructions in the basic block from the worklist.
772 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
773 RemoveFromWorklist(I, Worklist);
775 // Anything that uses the instructions in this basic block should have their
776 // uses replaced with undefs.
778 I->replaceAllUsesWith(UndefValue::get(I->getType()));
781 // If this is the edge to the header block for a loop, remove the loop and
782 // promote all subloops.
783 if (Loop *BBLoop = LI->getLoopFor(BB)) {
784 if (BBLoop->getLoopLatch() == BB)
785 RemoveLoopFromHierarchy(BBLoop);
788 // Remove the block from the loop info, which removes it from any loops it
793 // Remove phi node entries in successors for this block.
794 TerminatorInst *TI = BB->getTerminator();
795 std::vector<BasicBlock*> Succs;
796 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
797 Succs.push_back(TI->getSuccessor(i));
798 TI->getSuccessor(i)->removePredecessor(BB);
801 // Unique the successors, remove anything with multiple uses.
802 std::sort(Succs.begin(), Succs.end());
803 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
805 // Remove the basic block, including all of the instructions contained in it.
806 BB->eraseFromParent();
808 // Remove successor blocks here that are not dead, so that we know we only
809 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
810 // then getting removed before we revisit them, which is badness.
812 for (unsigned i = 0; i != Succs.size(); ++i)
813 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
814 // One exception is loop headers. If this block was the preheader for a
815 // loop, then we DO want to visit the loop so the loop gets deleted.
816 // We know that if the successor is a loop header, that this loop had to
817 // be the preheader: the case where this was the latch block was handled
818 // above and headers can only have two predecessors.
819 if (!LI->isLoopHeader(Succs[i])) {
820 Succs.erase(Succs.begin()+i);
825 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
826 RemoveBlockIfDead(Succs[i], Worklist);
829 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
830 /// become unwrapped, either because the backedge was deleted, or because the
831 /// edge into the header was removed. If the edge into the header from the
832 /// latch block was removed, the loop is unwrapped but subloops are still alive,
833 /// so they just reparent loops. If the loops are actually dead, they will be
835 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
836 LPM->deleteLoopFromQueue(L);
837 RemoveLoopFromWorklist(L);
842 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
843 // the value specified by Val in the specified loop, or we know it does NOT have
844 // that value. Rewrite any uses of LIC or of properties correlated to it.
845 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
848 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
850 // FIXME: Support correlated properties, like:
857 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
858 // selects, switches.
859 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
860 std::vector<Instruction*> Worklist;
862 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
863 // in the loop with the appropriate one directly.
864 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
869 Replacement = ConstantInt::get(Type::Int1Ty,
870 !cast<ConstantInt>(Val)->getZExtValue());
872 for (unsigned i = 0, e = Users.size(); i != e; ++i)
873 if (Instruction *U = cast<Instruction>(Users[i])) {
874 if (!L->contains(U->getParent()))
876 U->replaceUsesOfWith(LIC, Replacement);
877 Worklist.push_back(U);
880 // Otherwise, we don't know the precise value of LIC, but we do know that it
881 // is certainly NOT "Val". As such, simplify any uses in the loop that we
882 // can. This case occurs when we unswitch switch statements.
883 for (unsigned i = 0, e = Users.size(); i != e; ++i)
884 if (Instruction *U = cast<Instruction>(Users[i])) {
885 if (!L->contains(U->getParent()))
888 Worklist.push_back(U);
890 // If we know that LIC is not Val, use this info to simplify code.
891 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
892 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
893 if (SI->getCaseValue(i) == Val) {
894 // Found a dead case value. Don't remove PHI nodes in the
895 // successor if they become single-entry, those PHI nodes may
896 // be in the Users list.
898 // FIXME: This is a hack. We need to keep the successor around
899 // and hooked up so as to preserve the loop structure, because
900 // trying to update it is complicated. So instead we preserve the
901 // loop structure and put the block on an dead code path.
903 BasicBlock* Old = SI->getParent();
904 BasicBlock* Split = SplitBlock(Old, SI);
906 Instruction* OldTerm = Old->getTerminator();
907 new BranchInst(Split, SI->getSuccessor(i),
908 ConstantInt::getTrue(), OldTerm);
910 Old->getTerminator()->eraseFromParent();
914 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
915 (PN = dyn_cast<PHINode>(II)); ++II) {
916 Value *InVal = PN->removeIncomingValue(Split, false);
917 PN->addIncoming(InVal, Old);
926 // TODO: We could do other simplifications, for example, turning
927 // LIC == Val -> false.
931 SimplifyCode(Worklist);
934 /// SimplifyCode - Okay, now that we have simplified some instructions in the
935 /// loop, walk over it and constant prop, dce, and fold control flow where
936 /// possible. Note that this is effectively a very simple loop-structure-aware
937 /// optimizer. During processing of this loop, L could very well be deleted, so
938 /// it must not be used.
940 /// FIXME: When the loop optimizer is more mature, separate this out to a new
943 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
944 while (!Worklist.empty()) {
945 Instruction *I = Worklist.back();
948 // Simple constant folding.
949 if (Constant *C = ConstantFoldInstruction(I)) {
950 ReplaceUsesOfWith(I, C, Worklist);
955 if (isInstructionTriviallyDead(I)) {
956 DOUT << "Remove dead instruction '" << *I;
958 // Add uses to the worklist, which may be dead now.
959 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
960 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
961 Worklist.push_back(Use);
962 I->eraseFromParent();
963 RemoveFromWorklist(I, Worklist);
968 // Special case hacks that appear commonly in unswitched code.
969 switch (I->getOpcode()) {
970 case Instruction::Select:
971 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
972 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
976 case Instruction::And:
977 if (isa<ConstantInt>(I->getOperand(0)) &&
978 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
979 cast<BinaryOperator>(I)->swapOperands();
980 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
981 if (CB->getType() == Type::Int1Ty) {
982 if (CB->isOne()) // X & 1 -> X
983 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
985 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
989 case Instruction::Or:
990 if (isa<ConstantInt>(I->getOperand(0)) &&
991 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
992 cast<BinaryOperator>(I)->swapOperands();
993 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
994 if (CB->getType() == Type::Int1Ty) {
995 if (CB->isOne()) // X | 1 -> 1
996 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
998 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1002 case Instruction::Br: {
1003 BranchInst *BI = cast<BranchInst>(I);
1004 if (BI->isUnconditional()) {
1005 // If BI's parent is the only pred of the successor, fold the two blocks
1007 BasicBlock *Pred = BI->getParent();
1008 BasicBlock *Succ = BI->getSuccessor(0);
1009 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1010 if (!SinglePred) continue; // Nothing to do.
1011 assert(SinglePred == Pred && "CFG broken");
1013 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1014 << Succ->getName() << "\n";
1016 // Resolve any single entry PHI nodes in Succ.
1017 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1018 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1020 // Move all of the successor contents from Succ to Pred.
1021 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1023 BI->eraseFromParent();
1024 RemoveFromWorklist(BI, Worklist);
1026 // If Succ has any successors with PHI nodes, update them to have
1027 // entries coming from Pred instead of Succ.
1028 Succ->replaceAllUsesWith(Pred);
1030 // Remove Succ from the loop tree.
1031 LI->removeBlock(Succ);
1032 Succ->eraseFromParent();
1034 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1035 // Conditional branch. Turn it into an unconditional branch, then
1036 // remove dead blocks.
1037 break; // FIXME: Enable.
1039 DOUT << "Folded branch: " << *BI;
1040 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1041 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1042 DeadSucc->removePredecessor(BI->getParent(), true);
1043 Worklist.push_back(new BranchInst(LiveSucc, BI));
1044 BI->eraseFromParent();
1045 RemoveFromWorklist(BI, Worklist);
1048 RemoveBlockIfDead(DeadSucc, Worklist);