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/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/PostOrderIterator.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/CommandLine.h"
48 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
49 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
50 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
51 Statistic<> NumTrivial ("loop-unswitch",
52 "Number of unswitches that are trivial");
53 Statistic<> NumSimplify("loop-unswitch",
54 "Number of simplifications of unswitched code");
56 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
57 cl::init(10), cl::Hidden);
59 class LoopUnswitch : public FunctionPass {
60 LoopInfo *LI; // Loop information
62 // LoopProcessWorklist - List of loops we need to process.
63 std::vector<Loop*> LoopProcessWorklist;
65 virtual bool runOnFunction(Function &F);
66 bool visitLoop(Loop *L);
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredID(LoopSimplifyID);
73 AU.addPreservedID(LoopSimplifyID);
74 AU.addRequired<LoopInfo>();
75 AU.addPreserved<LoopInfo>();
76 AU.addRequiredID(LCSSAID);
77 AU.addPreservedID(LCSSAID);
81 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
83 void RemoveLoopFromWorklist(Loop *L) {
84 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
85 LoopProcessWorklist.end(), L);
86 if (I != LoopProcessWorklist.end())
87 LoopProcessWorklist.erase(I);
90 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
91 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
92 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
93 BasicBlock *ExitBlock);
94 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
95 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
96 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
98 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
99 Constant *Val, bool isEqual);
101 void SimplifyCode(std::vector<Instruction*> &Worklist);
102 void RemoveBlockIfDead(BasicBlock *BB,
103 std::vector<Instruction*> &Worklist);
104 void RemoveLoopFromHierarchy(Loop *L);
106 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
109 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
111 bool LoopUnswitch::runOnFunction(Function &F) {
112 bool Changed = false;
113 LI = &getAnalysis<LoopInfo>();
115 // Populate the worklist of loops to process in post-order.
116 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
117 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
118 LoopProcessWorklist.push_back(*LI);
120 // Process the loops in worklist order, this is a post-order visitation of
121 // the loops. We use a worklist of loops so that loops can be removed at any
122 // time if they are deleted (e.g. the backedge of a loop is removed).
123 while (!LoopProcessWorklist.empty()) {
124 Loop *L = LoopProcessWorklist.back();
125 LoopProcessWorklist.pop_back();
126 Changed |= visitLoop(L);
132 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
133 /// invariant in the loop, or has an invariant piece, return the invariant.
134 /// Otherwise, return null.
135 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
136 // Constants should be folded, not unswitched on!
137 if (isa<Constant>(Cond)) return false;
139 // TODO: Handle: br (VARIANT|INVARIANT).
140 // TODO: Hoist simple expressions out of loops.
141 if (L->isLoopInvariant(Cond)) return Cond;
143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
144 if (BO->getOpcode() == Instruction::And ||
145 BO->getOpcode() == Instruction::Or) {
146 // If either the left or right side is invariant, we can unswitch on this,
147 // which will cause the branch to go away in one loop and the condition to
148 // simplify in the other one.
149 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
151 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
158 bool LoopUnswitch::visitLoop(Loop *L) {
159 bool Changed = false;
161 // Loop over all of the basic blocks in the loop. If we find an interior
162 // block that is branching on a loop-invariant condition, we can unswitch this
164 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
166 TerminatorInst *TI = (*I)->getTerminator();
167 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
168 // If this isn't branching on an invariant condition, we can't unswitch
170 if (BI->isConditional()) {
171 // See if this, or some part of it, is loop invariant. If so, we can
172 // unswitch on it if we desire.
173 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
174 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
179 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
180 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
181 if (LoopCond && SI->getNumCases() > 1) {
182 // Find a value to unswitch on:
183 // FIXME: this should chose the most expensive case!
184 Constant *UnswitchVal = SI->getCaseValue(1);
185 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
192 // Scan the instructions to check for unswitchable values.
193 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
195 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
196 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
197 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
204 assert(L->isLCSSAForm());
210 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
211 /// the loop that are used by instructions outside of it.
212 static bool LoopValuesUsedOutsideLoop(Loop *L) {
213 // We will be doing lots of "loop contains block" queries. Loop::contains is
214 // linear time, use a set to speed this up.
215 std::set<BasicBlock*> LoopBlocks;
217 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
219 LoopBlocks.insert(*BB);
221 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
223 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
224 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
226 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
227 if (!LoopBlocks.count(UserBB))
234 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
235 /// 1. Exit the loop with no side effects.
236 /// 2. Branch to the latch block with no side-effects.
238 /// If these conditions are true, we return true and set ExitBB to the block we
241 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
243 std::set<BasicBlock*> &Visited) {
244 if (!Visited.insert(BB).second) {
245 // Already visited and Ok, end of recursion.
247 } else if (!L->contains(BB)) {
248 // Otherwise, this is a loop exit, this is fine so long as this is the
250 if (ExitBB != 0) return false;
255 // Otherwise, this is an unvisited intra-loop node. Check all successors.
256 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
257 // Check to see if the successor is a trivial loop exit.
258 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
262 // Okay, everything after this looks good, check to make sure that this block
263 // doesn't include any side effects.
264 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
265 if (I->mayWriteToMemory())
271 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
272 /// leads to an exit from the specified loop, and has no side-effects in the
273 /// process. If so, return the block that is exited to, otherwise return null.
274 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
275 std::set<BasicBlock*> Visited;
276 Visited.insert(L->getHeader()); // Branches to header are ok.
277 BasicBlock *ExitBB = 0;
278 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
283 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
284 /// trivial: that is, that the condition controls whether or not the loop does
285 /// anything at all. If this is a trivial condition, unswitching produces no
286 /// code duplications (equivalently, it produces a simpler loop and a new empty
287 /// loop, which gets deleted).
289 /// If this is a trivial condition, return true, otherwise return false. When
290 /// returning true, this sets Cond and Val to the condition that controls the
291 /// trivial condition: when Cond dynamically equals Val, the loop is known to
292 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
295 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
296 BasicBlock **LoopExit = 0) {
297 BasicBlock *Header = L->getHeader();
298 TerminatorInst *HeaderTerm = Header->getTerminator();
300 BasicBlock *LoopExitBB = 0;
301 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
302 // If the header block doesn't end with a conditional branch on Cond, we
304 if (!BI->isConditional() || BI->getCondition() != Cond)
307 // Check to see if a successor of the branch is guaranteed to go to the
308 // latch block or exit through a one exit block without having any
309 // side-effects. If so, determine the value of Cond that causes it to do
311 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
312 if (Val) *Val = ConstantBool::True;
313 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
314 if (Val) *Val = ConstantBool::False;
316 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
317 // If this isn't a switch on Cond, we can't handle it.
318 if (SI->getCondition() != Cond) return false;
320 // Check to see if a successor of the switch is guaranteed to go to the
321 // latch block or exit through a one exit block without having any
322 // side-effects. If so, determine the value of Cond that causes it to do
323 // this. Note that we can't trivially unswitch on the default case.
324 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
325 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
326 // Okay, we found a trivial case, remember the value that is trivial.
327 if (Val) *Val = SI->getCaseValue(i);
332 // If we didn't find a single unique LoopExit block, or if the loop exit block
333 // contains phi nodes, this isn't trivial.
334 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
335 return false; // Can't handle this.
337 if (LoopExit) *LoopExit = LoopExitBB;
339 // We already know that nothing uses any scalar values defined inside of this
340 // loop. As such, we just have to check to see if this loop will execute any
341 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
342 // part of the loop that the code *would* execute. We already checked the
343 // tail, check the header now.
344 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
345 if (I->mayWriteToMemory())
350 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
351 /// we choose to unswitch the specified loop on the specified value.
353 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
354 // If the condition is trivial, always unswitch. There is no code growth for
356 if (IsTrivialUnswitchCondition(L, LIC))
360 // FIXME: this is brain dead. It should take into consideration code
362 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
365 // Do not include empty blocks in the cost calculation. This happen due to
366 // loop canonicalization and will be removed.
367 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
370 // Count basic blocks.
377 /// UnswitchIfProfitable - We have found that we can unswitch L when
378 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
379 /// unswitch the loop, reprocess the pieces, then return true.
380 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
381 // Check to see if it would be profitable to unswitch this loop.
382 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
383 if (Cost > Threshold) {
384 // FIXME: this should estimate growth by the amount of code shared by the
385 // resultant unswitched loops.
387 DEBUG(std::cerr << "NOT unswitching loop %"
388 << L->getHeader()->getName() << ", cost too high: "
389 << L->getBlocks().size() << "\n");
393 // If this loop has live-out values, we can't unswitch it. We need something
394 // like loop-closed SSA form in order to know how to insert PHI nodes for
396 if (LoopValuesUsedOutsideLoop(L)) {
397 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
398 << ", a loop value is used outside loop! Cost: "
403 // If this is a trivial condition to unswitch (which results in no code
404 // duplication), do it now.
406 BasicBlock *ExitBlock;
407 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
408 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
410 UnswitchNontrivialCondition(LoopCond, Val, L);
416 /// SplitBlock - Split the specified block at the specified instruction - every
417 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
418 /// to a new block. The two blocks are joined by an unconditional branch and
419 /// the loop info is updated.
421 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
422 BasicBlock::iterator SplitIt = SplitPt;
423 while (isa<PHINode>(SplitIt))
425 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
427 // The new block lives in whichever loop the old one did.
428 if (Loop *L = LI->getLoopFor(Old))
429 L->addBasicBlockToLoop(New, *LI);
435 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
436 TerminatorInst *LatchTerm = BB->getTerminator();
437 unsigned SuccNum = 0;
438 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
439 assert(i != e && "Didn't find edge?");
440 if (LatchTerm->getSuccessor(i) == Succ) {
446 // If this is a critical edge, let SplitCriticalEdge do it.
447 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
448 return LatchTerm->getSuccessor(SuccNum);
450 // If the edge isn't critical, then BB has a single successor or Succ has a
451 // single pred. Split the block.
452 BasicBlock::iterator SplitPoint;
453 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
454 // If the successor only has a single pred, split the top of the successor
456 assert(SP == BB && "CFG broken");
457 return SplitBlock(Succ, Succ->begin());
459 // Otherwise, if BB has a single successor, split it at the bottom of the
461 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
462 "Should have a single succ!");
463 return SplitBlock(BB, BB->getTerminator());
469 // RemapInstruction - Convert the instruction operands from referencing the
470 // current values into those specified by ValueMap.
472 static inline void RemapInstruction(Instruction *I,
473 std::map<const Value *, Value*> &ValueMap) {
474 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
475 Value *Op = I->getOperand(op);
476 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
477 if (It != ValueMap.end()) Op = It->second;
478 I->setOperand(op, Op);
482 /// CloneLoop - Recursively clone the specified loop and all of its children,
483 /// mapping the blocks with the specified map.
484 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
486 Loop *New = new Loop();
489 PL->addChildLoop(New);
491 LI->addTopLevelLoop(New);
493 // Add all of the blocks in L to the new loop.
494 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
496 if (LI->getLoopFor(*I) == L)
497 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
499 // Add all of the subloops to the new loop.
500 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
501 CloneLoop(*I, New, VM, LI);
506 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
507 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
508 /// code immediately before InsertPt.
509 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
510 BasicBlock *TrueDest,
511 BasicBlock *FalseDest,
512 Instruction *InsertPt) {
513 // Insert a conditional branch on LIC to the two preheaders. The original
514 // code is the true version and the new code is the false version.
515 Value *BranchVal = LIC;
516 if (!isa<ConstantBool>(Val)) {
517 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
518 } else if (Val != ConstantBool::True) {
519 // We want to enter the new loop when the condition is true.
520 std::swap(TrueDest, FalseDest);
523 // Insert the new branch.
524 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
528 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
529 /// condition in it (a cond branch from its header block to its latch block,
530 /// where the path through the loop that doesn't execute its body has no
531 /// side-effects), unswitch it. This doesn't involve any code duplication, just
532 /// moving the conditional branch outside of the loop and updating loop info.
533 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
535 BasicBlock *ExitBlock) {
536 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
537 << L->getHeader()->getName() << " [" << L->getBlocks().size()
538 << " blocks] in Function " << L->getHeader()->getParent()->getName()
539 << " on cond: " << *Val << " == " << *Cond << "\n");
541 // First step, split the preheader, so that we know that there is a safe place
542 // to insert the conditional branch. We will change 'OrigPH' to have a
543 // conditional branch on Cond.
544 BasicBlock *OrigPH = L->getLoopPreheader();
545 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
547 // Now that we have a place to insert the conditional branch, create a place
548 // to branch to: this is the exit block out of the loop that we should
551 // Split this block now, so that the loop maintains its exit block, and so
552 // that the jump from the preheader can execute the contents of the exit block
553 // without actually branching to it (the exit block should be dominated by the
554 // loop header, not the preheader).
555 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
556 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
558 // Okay, now we have a position to branch from and a position to branch to,
559 // insert the new conditional branch.
560 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
561 OrigPH->getTerminator());
562 OrigPH->getTerminator()->eraseFromParent();
564 // We need to reprocess this loop, it could be unswitched again.
565 LoopProcessWorklist.push_back(L);
567 // Now that we know that the loop is never entered when this condition is a
568 // particular value, rewrite the loop with this info. We know that this will
569 // at least eliminate the old branch.
570 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
575 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
576 /// equal Val. Split it into loop versions and test the condition outside of
577 /// either loop. Return the loops created as Out1/Out2.
578 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
580 Function *F = L->getHeader()->getParent();
581 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
582 << L->getHeader()->getName() << " [" << L->getBlocks().size()
583 << " blocks] in Function " << F->getName()
584 << " when '" << *Val << "' == " << *LIC << "\n");
586 // LoopBlocks contains all of the basic blocks of the loop, including the
587 // preheader of the loop, the body of the loop, and the exit blocks of the
588 // loop, in that order.
589 std::vector<BasicBlock*> LoopBlocks;
591 // First step, split the preheader and exit blocks, and add these blocks to
592 // the LoopBlocks list.
593 BasicBlock *OrigPreheader = L->getLoopPreheader();
594 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
596 // We want the loop to come after the preheader, but before the exit blocks.
597 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
599 std::vector<BasicBlock*> ExitBlocks;
600 L->getExitBlocks(ExitBlocks);
601 std::sort(ExitBlocks.begin(), ExitBlocks.end());
602 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
605 // Split all of the edges from inside the loop to their exit blocks. This
606 // unswitching trivial: no phi nodes to update.
607 unsigned NumBlocks = L->getBlocks().size();
609 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
610 BasicBlock *ExitBlock = ExitBlocks[i];
611 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
613 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
614 assert(L->contains(Preds[j]) &&
615 "All preds of loop exit blocks must be the same loop!");
616 SplitEdge(Preds[j], ExitBlock);
620 // The exit blocks may have been changed due to edge splitting, recompute.
622 L->getExitBlocks(ExitBlocks);
623 std::sort(ExitBlocks.begin(), ExitBlocks.end());
624 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
627 // Add exit blocks to the loop blocks.
628 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
630 // Next step, clone all of the basic blocks that make up the loop (including
631 // the loop preheader and exit blocks), keeping track of the mapping between
632 // the instructions and blocks.
633 std::vector<BasicBlock*> NewBlocks;
634 NewBlocks.reserve(LoopBlocks.size());
635 std::map<const Value*, Value*> ValueMap;
636 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
637 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
638 NewBlocks.push_back(New);
639 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
642 // Splice the newly inserted blocks into the function right before the
643 // original preheader.
644 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
645 NewBlocks[0], F->end());
647 // Now we create the new Loop object for the versioned loop.
648 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
649 Loop *ParentLoop = L->getParentLoop();
651 // Make sure to add the cloned preheader and exit blocks to the parent loop
653 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
656 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
657 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
658 // The new exit block should be in the same loop as the old one.
659 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
660 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
662 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
663 "Exit block should have been split to have one successor!");
664 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
666 // If the successor of the exit block had PHI nodes, add an entry for
669 for (BasicBlock::iterator I = ExitSucc->begin();
670 (PN = dyn_cast<PHINode>(I)); ++I) {
671 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
672 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
673 if (It != ValueMap.end()) V = It->second;
674 PN->addIncoming(V, NewExit);
678 // Rewrite the code to refer to itself.
679 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
680 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
681 E = NewBlocks[i]->end(); I != E; ++I)
682 RemapInstruction(I, ValueMap);
684 // Rewrite the original preheader to select between versions of the loop.
685 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
686 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
687 "Preheader splitting did not work correctly!");
689 // Emit the new branch that selects between the two versions of this loop.
690 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
691 OldBR->eraseFromParent();
693 LoopProcessWorklist.push_back(L);
694 LoopProcessWorklist.push_back(NewLoop);
696 // Now we rewrite the original code to know that the condition is true and the
697 // new code to know that the condition is false.
698 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
700 // It's possible that simplifying one loop could cause the other to be
701 // deleted. If so, don't simplify it.
702 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
703 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
706 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
708 static void RemoveFromWorklist(Instruction *I,
709 std::vector<Instruction*> &Worklist) {
710 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
712 while (WI != Worklist.end()) {
713 unsigned Offset = WI-Worklist.begin();
715 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
719 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
720 /// program, replacing all uses with V and update the worklist.
721 static void ReplaceUsesOfWith(Instruction *I, Value *V,
722 std::vector<Instruction*> &Worklist) {
723 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
725 // Add uses to the worklist, which may be dead now.
726 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
727 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
728 Worklist.push_back(Use);
730 // Add users to the worklist which may be simplified now.
731 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
733 Worklist.push_back(cast<Instruction>(*UI));
734 I->replaceAllUsesWith(V);
735 I->eraseFromParent();
736 RemoveFromWorklist(I, Worklist);
740 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
741 /// information, and remove any dead successors it has.
743 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
744 std::vector<Instruction*> &Worklist) {
745 if (pred_begin(BB) != pred_end(BB)) {
746 // This block isn't dead, since an edge to BB was just removed, see if there
747 // are any easy simplifications we can do now.
748 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
749 // If it has one pred, fold phi nodes in BB.
750 while (isa<PHINode>(BB->begin()))
751 ReplaceUsesOfWith(BB->begin(),
752 cast<PHINode>(BB->begin())->getIncomingValue(0),
755 // If this is the header of a loop and the only pred is the latch, we now
756 // have an unreachable loop.
757 if (Loop *L = LI->getLoopFor(BB))
758 if (L->getHeader() == BB && L->contains(Pred)) {
759 // Remove the branch from the latch to the header block, this makes
760 // the header dead, which will make the latch dead (because the header
761 // dominates the latch).
762 Pred->getTerminator()->eraseFromParent();
763 new UnreachableInst(Pred);
765 // The loop is now broken, remove it from LI.
766 RemoveLoopFromHierarchy(L);
768 // Reprocess the header, which now IS dead.
769 RemoveBlockIfDead(BB, Worklist);
773 // If pred ends in a uncond branch, add uncond branch to worklist so that
774 // the two blocks will get merged.
775 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
776 if (BI->isUnconditional())
777 Worklist.push_back(BI);
782 DEBUG(std::cerr << "Nuking dead block: " << *BB);
784 // Remove the instructions in the basic block from the worklist.
785 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
786 RemoveFromWorklist(I, Worklist);
788 // Anything that uses the instructions in this basic block should have their
789 // uses replaced with undefs.
791 I->replaceAllUsesWith(UndefValue::get(I->getType()));
794 // If this is the edge to the header block for a loop, remove the loop and
795 // promote all subloops.
796 if (Loop *BBLoop = LI->getLoopFor(BB)) {
797 if (BBLoop->getLoopLatch() == BB)
798 RemoveLoopFromHierarchy(BBLoop);
801 // Remove the block from the loop info, which removes it from any loops it
806 // Remove phi node entries in successors for this block.
807 TerminatorInst *TI = BB->getTerminator();
808 std::vector<BasicBlock*> Succs;
809 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
810 Succs.push_back(TI->getSuccessor(i));
811 TI->getSuccessor(i)->removePredecessor(BB);
814 // Unique the successors, remove anything with multiple uses.
815 std::sort(Succs.begin(), Succs.end());
816 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
818 // Remove the basic block, including all of the instructions contained in it.
819 BB->eraseFromParent();
821 // Remove successor blocks here that are not dead, so that we know we only
822 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
823 // then getting removed before we revisit them, which is badness.
825 for (unsigned i = 0; i != Succs.size(); ++i)
826 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
827 // One exception is loop headers. If this block was the preheader for a
828 // loop, then we DO want to visit the loop so the loop gets deleted.
829 // We know that if the successor is a loop header, that this loop had to
830 // be the preheader: the case where this was the latch block was handled
831 // above and headers can only have two predecessors.
832 if (!LI->isLoopHeader(Succs[i])) {
833 Succs.erase(Succs.begin()+i);
838 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
839 RemoveBlockIfDead(Succs[i], Worklist);
842 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
843 /// become unwrapped, either because the backedge was deleted, or because the
844 /// edge into the header was removed. If the edge into the header from the
845 /// latch block was removed, the loop is unwrapped but subloops are still alive,
846 /// so they just reparent loops. If the loops are actually dead, they will be
848 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
849 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
850 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
851 // they are now all in it.
852 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
854 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
855 LI->changeLoopFor(*I, ParentLoop);
857 // Remove the loop from its parent loop.
858 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
860 assert(I != E && "Couldn't find loop");
862 ParentLoop->removeChildLoop(I);
867 // Move all subloops into the parent loop.
868 while (L->begin() != L->end())
869 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
871 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
872 // they no longer in a loop at all.
874 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
875 // Don't change blocks in subloops.
876 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
877 LI->removeBlock(L->getBlocks()[i]);
882 // Remove the loop from the top-level LoopInfo object.
883 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
884 assert(I != E && "Couldn't find loop");
891 // Move all of the subloops to the top-level.
892 while (L->begin() != L->end())
893 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
897 RemoveLoopFromWorklist(L);
902 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
903 // the value specified by Val in the specified loop, or we know it does NOT have
904 // that value. Rewrite any uses of LIC or of properties correlated to it.
905 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
908 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
910 // FIXME: Support correlated properties, like:
917 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
918 // selects, switches.
919 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
920 std::vector<Instruction*> Worklist;
922 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
923 // in the loop with the appropriate one directly.
924 if (IsEqual || isa<ConstantBool>(Val)) {
929 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
931 for (unsigned i = 0, e = Users.size(); i != e; ++i)
932 if (Instruction *U = cast<Instruction>(Users[i])) {
933 if (!L->contains(U->getParent()))
935 U->replaceUsesOfWith(LIC, Replacement);
936 Worklist.push_back(U);
939 // Otherwise, we don't know the precise value of LIC, but we do know that it
940 // is certainly NOT "Val". As such, simplify any uses in the loop that we
941 // can. This case occurs when we unswitch switch statements.
942 for (unsigned i = 0, e = Users.size(); i != e; ++i)
943 if (Instruction *U = cast<Instruction>(Users[i])) {
944 if (!L->contains(U->getParent()))
947 Worklist.push_back(U);
949 // If we know that LIC is not Val, use this info to simplify code.
950 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
951 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
952 if (SI->getCaseValue(i) == Val) {
953 // Found a dead case value. Don't remove PHI nodes in the
954 // successor if they become single-entry, those PHI nodes may
955 // be in the Users list.
956 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
963 // TODO: We could do other simplifications, for example, turning
964 // LIC == Val -> false.
968 SimplifyCode(Worklist);
971 /// SimplifyCode - Okay, now that we have simplified some instructions in the
972 /// loop, walk over it and constant prop, dce, and fold control flow where
973 /// possible. Note that this is effectively a very simple loop-structure-aware
974 /// optimizer. During processing of this loop, L could very well be deleted, so
975 /// it must not be used.
977 /// FIXME: When the loop optimizer is more mature, separate this out to a new
980 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
981 while (!Worklist.empty()) {
982 Instruction *I = Worklist.back();
985 // Simple constant folding.
986 if (Constant *C = ConstantFoldInstruction(I)) {
987 ReplaceUsesOfWith(I, C, Worklist);
992 if (isInstructionTriviallyDead(I)) {
993 DEBUG(std::cerr << "Remove dead instruction '" << *I);
995 // Add uses to the worklist, which may be dead now.
996 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
997 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
998 Worklist.push_back(Use);
999 I->eraseFromParent();
1000 RemoveFromWorklist(I, Worklist);
1005 // Special case hacks that appear commonly in unswitched code.
1006 switch (I->getOpcode()) {
1007 case Instruction::Select:
1008 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1009 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1013 case Instruction::And:
1014 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1015 cast<BinaryOperator>(I)->swapOperands();
1016 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1017 if (CB->getValue()) // X & 1 -> X
1018 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1020 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1024 case Instruction::Or:
1025 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1026 cast<BinaryOperator>(I)->swapOperands();
1027 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1028 if (CB->getValue()) // X | 1 -> 1
1029 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1031 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1035 case Instruction::Br: {
1036 BranchInst *BI = cast<BranchInst>(I);
1037 if (BI->isUnconditional()) {
1038 // If BI's parent is the only pred of the successor, fold the two blocks
1040 BasicBlock *Pred = BI->getParent();
1041 BasicBlock *Succ = BI->getSuccessor(0);
1042 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1043 if (!SinglePred) continue; // Nothing to do.
1044 assert(SinglePred == Pred && "CFG broken");
1046 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1047 << Succ->getName() << "\n");
1049 // Resolve any single entry PHI nodes in Succ.
1050 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1051 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1053 // Move all of the successor contents from Succ to Pred.
1054 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1056 BI->eraseFromParent();
1057 RemoveFromWorklist(BI, Worklist);
1059 // If Succ has any successors with PHI nodes, update them to have
1060 // entries coming from Pred instead of Succ.
1061 Succ->replaceAllUsesWith(Pred);
1063 // Remove Succ from the loop tree.
1064 LI->removeBlock(Succ);
1065 Succ->eraseFromParent();
1067 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
1068 // Conditional branch. Turn it into an unconditional branch, then
1069 // remove dead blocks.
1070 break; // FIXME: Enable.
1072 DEBUG(std::cerr << "Folded branch: " << *BI);
1073 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1074 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1075 DeadSucc->removePredecessor(BI->getParent(), true);
1076 Worklist.push_back(new BranchInst(LiveSucc, BI));
1077 BI->eraseFromParent();
1078 RemoveFromWorklist(BI, Worklist);
1081 RemoveBlockIfDead(DeadSucc, Worklist);