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/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/PostOrderIterator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
49 STATISTIC(NumBranches, "Number of branches unswitched");
50 STATISTIC(NumSwitches, "Number of switches unswitched");
51 STATISTIC(NumSelects , "Number of selects unswitched");
52 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
53 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
58 cl::init(10), cl::Hidden);
60 class VISIBILITY_HIDDEN LoopUnswitch : public FunctionPass {
61 LoopInfo *LI; // Loop information
63 // LoopProcessWorklist - List of loops we need to process.
64 std::vector<Loop*> LoopProcessWorklist;
66 virtual bool runOnFunction(Function &F);
67 bool visitLoop(Loop *L);
69 /// This transformation requires natural loop information & requires that
70 /// loop preheaders be inserted into the CFG...
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequiredID(LoopSimplifyID);
74 AU.addPreservedID(LoopSimplifyID);
75 AU.addRequired<LoopInfo>();
76 AU.addPreserved<LoopInfo>();
77 AU.addRequiredID(LCSSAID);
78 AU.addPreservedID(LCSSAID);
82 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
84 void RemoveLoopFromWorklist(Loop *L) {
85 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
86 LoopProcessWorklist.end(), L);
87 if (I != LoopProcessWorklist.end())
88 LoopProcessWorklist.erase(I);
91 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
92 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
93 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
94 BasicBlock *ExitBlock);
95 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
96 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
97 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
99 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
100 Constant *Val, bool isEqual);
102 void SimplifyCode(std::vector<Instruction*> &Worklist);
103 void RemoveBlockIfDead(BasicBlock *BB,
104 std::vector<Instruction*> &Worklist);
105 void RemoveLoopFromHierarchy(Loop *L);
107 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
110 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
112 bool LoopUnswitch::runOnFunction(Function &F) {
113 bool Changed = false;
114 LI = &getAnalysis<LoopInfo>();
116 // Populate the worklist of loops to process in post-order.
117 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
118 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
119 LoopProcessWorklist.push_back(*LI);
121 // Process the loops in worklist order, this is a post-order visitation of
122 // the loops. We use a worklist of loops so that loops can be removed at any
123 // time if they are deleted (e.g. the backedge of a loop is removed).
124 while (!LoopProcessWorklist.empty()) {
125 Loop *L = LoopProcessWorklist.back();
126 LoopProcessWorklist.pop_back();
127 Changed |= visitLoop(L);
133 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
134 /// invariant in the loop, or has an invariant piece, return the invariant.
135 /// Otherwise, return null.
136 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
137 // Constants should be folded, not unswitched on!
138 if (isa<Constant>(Cond)) return false;
140 // TODO: Handle: br (VARIANT|INVARIANT).
141 // TODO: Hoist simple expressions out of loops.
142 if (L->isLoopInvariant(Cond)) return Cond;
144 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
145 if (BO->getOpcode() == Instruction::And ||
146 BO->getOpcode() == Instruction::Or) {
147 // If either the left or right side is invariant, we can unswitch on this,
148 // which will cause the branch to go away in one loop and the condition to
149 // simplify in the other one.
150 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
152 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
159 bool LoopUnswitch::visitLoop(Loop *L) {
160 assert(L->isLCSSAForm());
162 bool Changed = false;
164 // Loop over all of the basic blocks in the loop. If we find an interior
165 // block that is branching on a loop-invariant condition, we can unswitch this
167 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
169 TerminatorInst *TI = (*I)->getTerminator();
170 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
171 // If this isn't branching on an invariant condition, we can't unswitch
173 if (BI->isConditional()) {
174 // See if this, or some part of it, is loop invariant. If so, we can
175 // unswitch on it if we desire.
176 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
177 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
183 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
184 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
185 if (LoopCond && SI->getNumCases() > 1) {
186 // Find a value to unswitch on:
187 // FIXME: this should chose the most expensive case!
188 Constant *UnswitchVal = SI->getCaseValue(1);
189 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
196 // Scan the instructions to check for unswitchable values.
197 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
199 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
200 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
201 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
209 assert(L->isLCSSAForm());
214 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
215 /// 1. Exit the loop with no side effects.
216 /// 2. Branch to the latch block with no side-effects.
218 /// If these conditions are true, we return true and set ExitBB to the block we
221 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
223 std::set<BasicBlock*> &Visited) {
224 if (!Visited.insert(BB).second) {
225 // Already visited and Ok, end of recursion.
227 } else if (!L->contains(BB)) {
228 // Otherwise, this is a loop exit, this is fine so long as this is the
230 if (ExitBB != 0) return false;
235 // Otherwise, this is an unvisited intra-loop node. Check all successors.
236 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
237 // Check to see if the successor is a trivial loop exit.
238 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
242 // Okay, everything after this looks good, check to make sure that this block
243 // doesn't include any side effects.
244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245 if (I->mayWriteToMemory())
251 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
252 /// leads to an exit from the specified loop, and has no side-effects in the
253 /// process. If so, return the block that is exited to, otherwise return null.
254 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
255 std::set<BasicBlock*> Visited;
256 Visited.insert(L->getHeader()); // Branches to header are ok.
257 BasicBlock *ExitBB = 0;
258 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
263 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
264 /// trivial: that is, that the condition controls whether or not the loop does
265 /// anything at all. If this is a trivial condition, unswitching produces no
266 /// code duplications (equivalently, it produces a simpler loop and a new empty
267 /// loop, which gets deleted).
269 /// If this is a trivial condition, return true, otherwise return false. When
270 /// returning true, this sets Cond and Val to the condition that controls the
271 /// trivial condition: when Cond dynamically equals Val, the loop is known to
272 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
275 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
276 BasicBlock **LoopExit = 0) {
277 BasicBlock *Header = L->getHeader();
278 TerminatorInst *HeaderTerm = Header->getTerminator();
280 BasicBlock *LoopExitBB = 0;
281 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
282 // If the header block doesn't end with a conditional branch on Cond, we
284 if (!BI->isConditional() || BI->getCondition() != Cond)
287 // Check to see if a successor of the branch is guaranteed to go to the
288 // latch block or exit through a one exit block without having any
289 // side-effects. If so, determine the value of Cond that causes it to do
291 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
292 if (Val) *Val = ConstantInt::getTrue();
293 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
294 if (Val) *Val = ConstantInt::getFalse();
296 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
297 // If this isn't a switch on Cond, we can't handle it.
298 if (SI->getCondition() != Cond) return false;
300 // Check to see if a successor of the switch is guaranteed to go to the
301 // latch block or exit through a one exit block without having any
302 // side-effects. If so, determine the value of Cond that causes it to do
303 // this. Note that we can't trivially unswitch on the default case.
304 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
305 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
306 // Okay, we found a trivial case, remember the value that is trivial.
307 if (Val) *Val = SI->getCaseValue(i);
312 // If we didn't find a single unique LoopExit block, or if the loop exit block
313 // contains phi nodes, this isn't trivial.
314 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
315 return false; // Can't handle this.
317 if (LoopExit) *LoopExit = LoopExitBB;
319 // We already know that nothing uses any scalar values defined inside of this
320 // loop. As such, we just have to check to see if this loop will execute any
321 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
322 // part of the loop that the code *would* execute. We already checked the
323 // tail, check the header now.
324 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
325 if (I->mayWriteToMemory())
330 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
331 /// we choose to unswitch the specified loop on the specified value.
333 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
334 // If the condition is trivial, always unswitch. There is no code growth for
336 if (IsTrivialUnswitchCondition(L, LIC))
339 // FIXME: This is really overly conservative. However, more liberal
340 // estimations have thus far resulted in excessive unswitching, which is bad
341 // both in compile time and in code size. This should be replaced once
342 // someone figures out how a good estimation.
343 return L->getBlocks().size();
346 // FIXME: this is brain dead. It should take into consideration code
348 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
351 // Do not include empty blocks in the cost calculation. This happen due to
352 // loop canonicalization and will be removed.
353 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
356 // Count basic blocks.
363 /// UnswitchIfProfitable - We have found that we can unswitch L when
364 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
365 /// unswitch the loop, reprocess the pieces, then return true.
366 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
367 // Check to see if it would be profitable to unswitch this loop.
368 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
369 if (Cost > Threshold) {
370 // FIXME: this should estimate growth by the amount of code shared by the
371 // resultant unswitched loops.
373 DOUT << "NOT unswitching loop %"
374 << L->getHeader()->getName() << ", cost too high: "
375 << L->getBlocks().size() << "\n";
379 // If this is a trivial condition to unswitch (which results in no code
380 // duplication), do it now.
382 BasicBlock *ExitBlock;
383 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
384 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
386 UnswitchNontrivialCondition(LoopCond, Val, L);
392 /// SplitBlock - Split the specified block at the specified instruction - every
393 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
394 /// to a new block. The two blocks are joined by an unconditional branch and
395 /// the loop info is updated.
397 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
398 BasicBlock::iterator SplitIt = SplitPt;
399 while (isa<PHINode>(SplitIt))
401 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
403 // The new block lives in whichever loop the old one did.
404 if (Loop *L = LI->getLoopFor(Old))
405 L->addBasicBlockToLoop(New, *LI);
411 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
412 TerminatorInst *LatchTerm = BB->getTerminator();
413 unsigned SuccNum = 0;
414 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
415 assert(i != e && "Didn't find edge?");
416 if (LatchTerm->getSuccessor(i) == Succ) {
422 // If this is a critical edge, let SplitCriticalEdge do it.
423 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
424 return LatchTerm->getSuccessor(SuccNum);
426 // If the edge isn't critical, then BB has a single successor or Succ has a
427 // single pred. Split the block.
428 BasicBlock::iterator SplitPoint;
429 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
430 // If the successor only has a single pred, split the top of the successor
432 assert(SP == BB && "CFG broken");
433 return SplitBlock(Succ, Succ->begin());
435 // Otherwise, if BB has a single successor, split it at the bottom of the
437 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
438 "Should have a single succ!");
439 return SplitBlock(BB, BB->getTerminator());
445 // RemapInstruction - Convert the instruction operands from referencing the
446 // current values into those specified by ValueMap.
448 static inline void RemapInstruction(Instruction *I,
449 DenseMap<const Value *, Value*> &ValueMap) {
450 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
451 Value *Op = I->getOperand(op);
452 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
453 if (It != ValueMap.end()) Op = It->second;
454 I->setOperand(op, Op);
458 /// CloneLoop - Recursively clone the specified loop and all of its children,
459 /// mapping the blocks with the specified map.
460 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
462 Loop *New = new Loop();
465 PL->addChildLoop(New);
467 LI->addTopLevelLoop(New);
469 // Add all of the blocks in L to the new loop.
470 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
472 if (LI->getLoopFor(*I) == L)
473 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
475 // Add all of the subloops to the new loop.
476 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
477 CloneLoop(*I, New, VM, LI);
482 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
483 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
484 /// code immediately before InsertPt.
485 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
486 BasicBlock *TrueDest,
487 BasicBlock *FalseDest,
488 Instruction *InsertPt) {
489 // Insert a conditional branch on LIC to the two preheaders. The original
490 // code is the true version and the new code is the false version.
491 Value *BranchVal = LIC;
492 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
493 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
494 else if (Val != ConstantInt::getTrue())
495 // We want to enter the new loop when the condition is true.
496 std::swap(TrueDest, FalseDest);
498 // Insert the new branch.
499 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
503 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
504 /// condition in it (a cond branch from its header block to its latch block,
505 /// where the path through the loop that doesn't execute its body has no
506 /// side-effects), unswitch it. This doesn't involve any code duplication, just
507 /// moving the conditional branch outside of the loop and updating loop info.
508 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
510 BasicBlock *ExitBlock) {
511 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
512 << L->getHeader()->getName() << " [" << L->getBlocks().size()
513 << " blocks] in Function " << L->getHeader()->getParent()->getName()
514 << " on cond: " << *Val << " == " << *Cond << "\n";
516 // First step, split the preheader, so that we know that there is a safe place
517 // to insert the conditional branch. We will change 'OrigPH' to have a
518 // conditional branch on Cond.
519 BasicBlock *OrigPH = L->getLoopPreheader();
520 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
522 // Now that we have a place to insert the conditional branch, create a place
523 // to branch to: this is the exit block out of the loop that we should
526 // Split this block now, so that the loop maintains its exit block, and so
527 // that the jump from the preheader can execute the contents of the exit block
528 // without actually branching to it (the exit block should be dominated by the
529 // loop header, not the preheader).
530 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
531 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
533 // Okay, now we have a position to branch from and a position to branch to,
534 // insert the new conditional branch.
535 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
536 OrigPH->getTerminator());
537 OrigPH->getTerminator()->eraseFromParent();
539 // We need to reprocess this loop, it could be unswitched again.
540 LoopProcessWorklist.push_back(L);
542 // Now that we know that the loop is never entered when this condition is a
543 // particular value, rewrite the loop with this info. We know that this will
544 // at least eliminate the old branch.
545 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
550 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
551 /// equal Val. Split it into loop versions and test the condition outside of
552 /// either loop. Return the loops created as Out1/Out2.
553 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
555 Function *F = L->getHeader()->getParent();
556 DOUT << "loop-unswitch: Unswitching loop %"
557 << L->getHeader()->getName() << " [" << L->getBlocks().size()
558 << " blocks] in Function " << F->getName()
559 << " when '" << *Val << "' == " << *LIC << "\n";
561 // LoopBlocks contains all of the basic blocks of the loop, including the
562 // preheader of the loop, the body of the loop, and the exit blocks of the
563 // loop, in that order.
564 std::vector<BasicBlock*> LoopBlocks;
566 // First step, split the preheader and exit blocks, and add these blocks to
567 // the LoopBlocks list.
568 BasicBlock *OrigPreheader = L->getLoopPreheader();
569 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
571 // We want the loop to come after the preheader, but before the exit blocks.
572 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
574 std::vector<BasicBlock*> ExitBlocks;
575 L->getUniqueExitBlocks(ExitBlocks);
577 // Split all of the edges from inside the loop to their exit blocks. Update
578 // the appropriate Phi nodes as we do so.
579 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
580 BasicBlock *ExitBlock = ExitBlocks[i];
581 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
583 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
584 assert(L->contains(Preds[j]) &&
585 "All preds of loop exit blocks must be the same loop!");
586 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
587 BasicBlock* StartBlock = Preds[j];
588 BasicBlock* EndBlock;
589 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
590 EndBlock = MiddleBlock;
591 MiddleBlock = EndBlock->getSinglePredecessor();;
593 EndBlock = ExitBlock;
596 std::set<PHINode*> InsertedPHIs;
597 PHINode* OldLCSSA = 0;
598 for (BasicBlock::iterator I = EndBlock->begin();
599 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
600 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
601 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
602 OldLCSSA->getName() + ".us-lcssa",
603 MiddleBlock->getTerminator());
604 NewLCSSA->addIncoming(OldValue, StartBlock);
605 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
607 InsertedPHIs.insert(NewLCSSA);
610 BasicBlock::iterator InsertPt = EndBlock->begin();
611 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
612 for (BasicBlock::iterator I = MiddleBlock->begin();
613 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
615 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
616 OldLCSSA->getName() + ".us-lcssa",
618 OldLCSSA->replaceAllUsesWith(NewLCSSA);
619 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
624 // The exit blocks may have been changed due to edge splitting, recompute.
626 L->getUniqueExitBlocks(ExitBlocks);
628 // Add exit blocks to the loop blocks.
629 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
631 // Next step, clone all of the basic blocks that make up the loop (including
632 // the loop preheader and exit blocks), keeping track of the mapping between
633 // the instructions and blocks.
634 std::vector<BasicBlock*> NewBlocks;
635 NewBlocks.reserve(LoopBlocks.size());
636 DenseMap<const Value*, Value*> ValueMap;
637 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
638 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
639 NewBlocks.push_back(New);
640 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
643 // Splice the newly inserted blocks into the function right before the
644 // original preheader.
645 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
646 NewBlocks[0], F->end());
648 // Now we create the new Loop object for the versioned loop.
649 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
650 Loop *ParentLoop = L->getParentLoop();
652 // Make sure to add the cloned preheader and exit blocks to the parent loop
654 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
657 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
658 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
659 // The new exit block should be in the same loop as the old one.
660 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
661 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
663 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
664 "Exit block should have been split to have one successor!");
665 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
667 // If the successor of the exit block had PHI nodes, add an entry for
670 for (BasicBlock::iterator I = ExitSucc->begin();
671 (PN = dyn_cast<PHINode>(I)); ++I) {
672 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
673 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
674 if (It != ValueMap.end()) V = It->second;
675 PN->addIncoming(V, NewExit);
679 // Rewrite the code to refer to itself.
680 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
681 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
682 E = NewBlocks[i]->end(); I != E; ++I)
683 RemapInstruction(I, ValueMap);
685 // Rewrite the original preheader to select between versions of the loop.
686 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
687 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
688 "Preheader splitting did not work correctly!");
690 // Emit the new branch that selects between the two versions of this loop.
691 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
692 OldBR->eraseFromParent();
694 LoopProcessWorklist.push_back(L);
695 LoopProcessWorklist.push_back(NewLoop);
697 // Now we rewrite the original code to know that the condition is true and the
698 // new code to know that the condition is false.
699 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
701 // It's possible that simplifying one loop could cause the other to be
702 // deleted. If so, don't simplify it.
703 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
704 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
707 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
709 static void RemoveFromWorklist(Instruction *I,
710 std::vector<Instruction*> &Worklist) {
711 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
713 while (WI != Worklist.end()) {
714 unsigned Offset = WI-Worklist.begin();
716 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
720 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
721 /// program, replacing all uses with V and update the worklist.
722 static void ReplaceUsesOfWith(Instruction *I, Value *V,
723 std::vector<Instruction*> &Worklist) {
724 DOUT << "Replace with '" << *V << "': " << *I;
726 // Add uses to the worklist, which may be dead now.
727 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
728 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
729 Worklist.push_back(Use);
731 // Add users to the worklist which may be simplified now.
732 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
734 Worklist.push_back(cast<Instruction>(*UI));
735 I->replaceAllUsesWith(V);
736 I->eraseFromParent();
737 RemoveFromWorklist(I, Worklist);
741 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
742 /// information, and remove any dead successors it has.
744 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
745 std::vector<Instruction*> &Worklist) {
746 if (pred_begin(BB) != pred_end(BB)) {
747 // This block isn't dead, since an edge to BB was just removed, see if there
748 // are any easy simplifications we can do now.
749 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
750 // If it has one pred, fold phi nodes in BB.
751 while (isa<PHINode>(BB->begin()))
752 ReplaceUsesOfWith(BB->begin(),
753 cast<PHINode>(BB->begin())->getIncomingValue(0),
756 // If this is the header of a loop and the only pred is the latch, we now
757 // have an unreachable loop.
758 if (Loop *L = LI->getLoopFor(BB))
759 if (L->getHeader() == BB && L->contains(Pred)) {
760 // Remove the branch from the latch to the header block, this makes
761 // the header dead, which will make the latch dead (because the header
762 // dominates the latch).
763 Pred->getTerminator()->eraseFromParent();
764 new UnreachableInst(Pred);
766 // The loop is now broken, remove it from LI.
767 RemoveLoopFromHierarchy(L);
769 // Reprocess the header, which now IS dead.
770 RemoveBlockIfDead(BB, Worklist);
774 // If pred ends in a uncond branch, add uncond branch to worklist so that
775 // the two blocks will get merged.
776 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
777 if (BI->isUnconditional())
778 Worklist.push_back(BI);
783 DOUT << "Nuking dead block: " << *BB;
785 // Remove the instructions in the basic block from the worklist.
786 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
787 RemoveFromWorklist(I, Worklist);
789 // Anything that uses the instructions in this basic block should have their
790 // uses replaced with undefs.
792 I->replaceAllUsesWith(UndefValue::get(I->getType()));
795 // If this is the edge to the header block for a loop, remove the loop and
796 // promote all subloops.
797 if (Loop *BBLoop = LI->getLoopFor(BB)) {
798 if (BBLoop->getLoopLatch() == BB)
799 RemoveLoopFromHierarchy(BBLoop);
802 // Remove the block from the loop info, which removes it from any loops it
807 // Remove phi node entries in successors for this block.
808 TerminatorInst *TI = BB->getTerminator();
809 std::vector<BasicBlock*> Succs;
810 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
811 Succs.push_back(TI->getSuccessor(i));
812 TI->getSuccessor(i)->removePredecessor(BB);
815 // Unique the successors, remove anything with multiple uses.
816 std::sort(Succs.begin(), Succs.end());
817 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
819 // Remove the basic block, including all of the instructions contained in it.
820 BB->eraseFromParent();
822 // Remove successor blocks here that are not dead, so that we know we only
823 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
824 // then getting removed before we revisit them, which is badness.
826 for (unsigned i = 0; i != Succs.size(); ++i)
827 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
828 // One exception is loop headers. If this block was the preheader for a
829 // loop, then we DO want to visit the loop so the loop gets deleted.
830 // We know that if the successor is a loop header, that this loop had to
831 // be the preheader: the case where this was the latch block was handled
832 // above and headers can only have two predecessors.
833 if (!LI->isLoopHeader(Succs[i])) {
834 Succs.erase(Succs.begin()+i);
839 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
840 RemoveBlockIfDead(Succs[i], Worklist);
843 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
844 /// become unwrapped, either because the backedge was deleted, or because the
845 /// edge into the header was removed. If the edge into the header from the
846 /// latch block was removed, the loop is unwrapped but subloops are still alive,
847 /// so they just reparent loops. If the loops are actually dead, they will be
849 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
850 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
851 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
852 // they are now all in it.
853 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
855 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
856 LI->changeLoopFor(*I, ParentLoop);
858 // Remove the loop from its parent loop.
859 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
861 assert(I != E && "Couldn't find loop");
863 ParentLoop->removeChildLoop(I);
868 // Move all subloops into the parent loop.
869 while (L->begin() != L->end())
870 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
872 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
873 // they no longer in a loop at all.
875 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
876 // Don't change blocks in subloops.
877 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
878 LI->removeBlock(L->getBlocks()[i]);
883 // Remove the loop from the top-level LoopInfo object.
884 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
885 assert(I != E && "Couldn't find loop");
892 // Move all of the subloops to the top-level.
893 while (L->begin() != L->end())
894 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
898 RemoveLoopFromWorklist(L);
903 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
904 // the value specified by Val in the specified loop, or we know it does NOT have
905 // that value. Rewrite any uses of LIC or of properties correlated to it.
906 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
909 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
911 // FIXME: Support correlated properties, like:
918 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
919 // selects, switches.
920 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
921 std::vector<Instruction*> Worklist;
923 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
924 // in the loop with the appropriate one directly.
925 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
930 Replacement = ConstantInt::get(Type::Int1Ty,
931 !cast<ConstantInt>(Val)->getZExtValue());
933 for (unsigned i = 0, e = Users.size(); i != e; ++i)
934 if (Instruction *U = cast<Instruction>(Users[i])) {
935 if (!L->contains(U->getParent()))
937 U->replaceUsesOfWith(LIC, Replacement);
938 Worklist.push_back(U);
941 // Otherwise, we don't know the precise value of LIC, but we do know that it
942 // is certainly NOT "Val". As such, simplify any uses in the loop that we
943 // can. This case occurs when we unswitch switch statements.
944 for (unsigned i = 0, e = Users.size(); i != e; ++i)
945 if (Instruction *U = cast<Instruction>(Users[i])) {
946 if (!L->contains(U->getParent()))
949 Worklist.push_back(U);
951 // If we know that LIC is not Val, use this info to simplify code.
952 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
953 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
954 if (SI->getCaseValue(i) == Val) {
955 // Found a dead case value. Don't remove PHI nodes in the
956 // successor if they become single-entry, those PHI nodes may
957 // be in the Users list.
959 // FIXME: This is a hack. We need to keep the successor around
960 // and hooked up so as to preserve the loop structure, because
961 // trying to update it is complicated. So instead we preserve the
962 // loop structure and put the block on an dead code path.
964 BasicBlock* Old = SI->getParent();
965 BasicBlock* Split = SplitBlock(Old, SI);
967 Instruction* OldTerm = Old->getTerminator();
968 new BranchInst(Split, SI->getSuccessor(i),
969 ConstantInt::getTrue(), OldTerm);
971 Old->getTerminator()->eraseFromParent();
975 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
976 (PN = dyn_cast<PHINode>(II)); ++II) {
977 Value *InVal = PN->removeIncomingValue(Split, false);
978 PN->addIncoming(InVal, Old);
987 // TODO: We could do other simplifications, for example, turning
988 // LIC == Val -> false.
992 SimplifyCode(Worklist);
995 /// SimplifyCode - Okay, now that we have simplified some instructions in the
996 /// loop, walk over it and constant prop, dce, and fold control flow where
997 /// possible. Note that this is effectively a very simple loop-structure-aware
998 /// optimizer. During processing of this loop, L could very well be deleted, so
999 /// it must not be used.
1001 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1004 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
1005 while (!Worklist.empty()) {
1006 Instruction *I = Worklist.back();
1007 Worklist.pop_back();
1009 // Simple constant folding.
1010 if (Constant *C = ConstantFoldInstruction(I)) {
1011 ReplaceUsesOfWith(I, C, Worklist);
1016 if (isInstructionTriviallyDead(I)) {
1017 DOUT << "Remove dead instruction '" << *I;
1019 // Add uses to the worklist, which may be dead now.
1020 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1021 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1022 Worklist.push_back(Use);
1023 I->eraseFromParent();
1024 RemoveFromWorklist(I, Worklist);
1029 // Special case hacks that appear commonly in unswitched code.
1030 switch (I->getOpcode()) {
1031 case Instruction::Select:
1032 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1033 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1037 case Instruction::And:
1038 if (isa<ConstantInt>(I->getOperand(0)) &&
1039 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1040 cast<BinaryOperator>(I)->swapOperands();
1041 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1042 if (CB->getType() == Type::Int1Ty) {
1043 if (CB->getZExtValue()) // X & 1 -> X
1044 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1046 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1050 case Instruction::Or:
1051 if (isa<ConstantInt>(I->getOperand(0)) &&
1052 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1053 cast<BinaryOperator>(I)->swapOperands();
1054 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1055 if (CB->getType() == Type::Int1Ty) {
1056 if (CB->getZExtValue()) // X | 1 -> 1
1057 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1059 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1063 case Instruction::Br: {
1064 BranchInst *BI = cast<BranchInst>(I);
1065 if (BI->isUnconditional()) {
1066 // If BI's parent is the only pred of the successor, fold the two blocks
1068 BasicBlock *Pred = BI->getParent();
1069 BasicBlock *Succ = BI->getSuccessor(0);
1070 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1071 if (!SinglePred) continue; // Nothing to do.
1072 assert(SinglePred == Pred && "CFG broken");
1074 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1075 << Succ->getName() << "\n";
1077 // Resolve any single entry PHI nodes in Succ.
1078 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1079 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1081 // Move all of the successor contents from Succ to Pred.
1082 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1084 BI->eraseFromParent();
1085 RemoveFromWorklist(BI, Worklist);
1087 // If Succ has any successors with PHI nodes, update them to have
1088 // entries coming from Pred instead of Succ.
1089 Succ->replaceAllUsesWith(Pred);
1091 // Remove Succ from the loop tree.
1092 LI->removeBlock(Succ);
1093 Succ->eraseFromParent();
1095 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1096 // Conditional branch. Turn it into an unconditional branch, then
1097 // remove dead blocks.
1098 break; // FIXME: Enable.
1100 DOUT << "Folded branch: " << *BI;
1101 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1102 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1103 DeadSucc->removePredecessor(BI->getParent(), true);
1104 Worklist.push_back(new BranchInst(LiveSucc, BI));
1105 BI->eraseFromParent();
1106 RemoveFromWorklist(BI, Worklist);
1109 RemoveBlockIfDead(DeadSucc, Worklist);