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>();
79 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
81 void RemoveLoopFromWorklist(Loop *L) {
82 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
83 LoopProcessWorklist.end(), L);
84 if (I != LoopProcessWorklist.end())
85 LoopProcessWorklist.erase(I);
88 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
89 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
90 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
91 BasicBlock *ExitBlock);
92 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
93 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
94 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
96 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
97 Constant *Val, bool isEqual);
99 void SimplifyCode(std::vector<Instruction*> &Worklist);
100 void RemoveBlockIfDead(BasicBlock *BB,
101 std::vector<Instruction*> &Worklist);
102 void RemoveLoopFromHierarchy(Loop *L);
104 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
107 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
109 bool LoopUnswitch::runOnFunction(Function &F) {
110 bool Changed = false;
111 LI = &getAnalysis<LoopInfo>();
113 // Populate the worklist of loops to process in post-order.
114 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
115 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
116 LoopProcessWorklist.push_back(*LI);
118 // Process the loops in worklist order, this is a post-order visitation of
119 // the loops. We use a worklist of loops so that loops can be removed at any
120 // time if they are deleted (e.g. the backedge of a loop is removed).
121 while (!LoopProcessWorklist.empty()) {
122 Loop *L = LoopProcessWorklist.back();
123 LoopProcessWorklist.pop_back();
124 Changed |= visitLoop(L);
130 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
131 /// invariant in the loop, or has an invariant piece, return the invariant.
132 /// Otherwise, return null.
133 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
134 // Constants should be folded, not unswitched on!
135 if (isa<Constant>(Cond)) return false;
137 // TODO: Handle: br (VARIANT|INVARIANT).
138 // TODO: Hoist simple expressions out of loops.
139 if (L->isLoopInvariant(Cond)) return Cond;
141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
142 if (BO->getOpcode() == Instruction::And ||
143 BO->getOpcode() == Instruction::Or) {
144 // If either the left or right side is invariant, we can unswitch on this,
145 // which will cause the branch to go away in one loop and the condition to
146 // simplify in the other one.
147 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
149 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
156 bool LoopUnswitch::visitLoop(Loop *L) {
157 bool Changed = false;
159 // Loop over all of the basic blocks in the loop. If we find an interior
160 // block that is branching on a loop-invariant condition, we can unswitch this
162 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
164 TerminatorInst *TI = (*I)->getTerminator();
165 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
166 // If this isn't branching on an invariant condition, we can't unswitch
168 if (BI->isConditional()) {
169 // See if this, or some part of it, is loop invariant. If so, we can
170 // unswitch on it if we desire.
171 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
172 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
177 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
178 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
179 if (LoopCond && SI->getNumCases() > 1) {
180 // Find a value to unswitch on:
181 // FIXME: this should chose the most expensive case!
182 Constant *UnswitchVal = SI->getCaseValue(1);
183 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
190 // Scan the instructions to check for unswitchable values.
191 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
193 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
194 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
195 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
206 /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
207 /// the loop that are used by instructions outside of it.
208 static bool LoopValuesUsedOutsideLoop(Loop *L) {
209 // We will be doing lots of "loop contains block" queries. Loop::contains is
210 // linear time, use a set to speed this up.
211 std::set<BasicBlock*> LoopBlocks;
213 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
215 LoopBlocks.insert(*BB);
217 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
219 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
220 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
222 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
223 if (!LoopBlocks.count(UserBB))
230 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
231 /// 1. Exit the loop with no side effects.
232 /// 2. Branch to the latch block with no side-effects.
234 /// If these conditions are true, we return true and set ExitBB to the block we
237 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
239 std::set<BasicBlock*> &Visited) {
240 if (!Visited.insert(BB).second) {
241 // Already visited and Ok, end of recursion.
243 } else if (!L->contains(BB)) {
244 // Otherwise, this is a loop exit, this is fine so long as this is the
246 if (ExitBB != 0) return false;
251 // Otherwise, this is an unvisited intra-loop node. Check all successors.
252 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
253 // Check to see if the successor is a trivial loop exit.
254 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
258 // Okay, everything after this looks good, check to make sure that this block
259 // doesn't include any side effects.
260 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
261 if (I->mayWriteToMemory())
267 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
268 /// leads to an exit from the specified loop, and has no side-effects in the
269 /// process. If so, return the block that is exited to, otherwise return null.
270 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
271 std::set<BasicBlock*> Visited;
272 Visited.insert(L->getHeader()); // Branches to header are ok.
273 BasicBlock *ExitBB = 0;
274 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
279 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
280 /// trivial: that is, that the condition controls whether or not the loop does
281 /// anything at all. If this is a trivial condition, unswitching produces no
282 /// code duplications (equivalently, it produces a simpler loop and a new empty
283 /// loop, which gets deleted).
285 /// If this is a trivial condition, return true, otherwise return false. When
286 /// returning true, this sets Cond and Val to the condition that controls the
287 /// trivial condition: when Cond dynamically equals Val, the loop is known to
288 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
291 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
292 BasicBlock **LoopExit = 0) {
293 BasicBlock *Header = L->getHeader();
294 TerminatorInst *HeaderTerm = Header->getTerminator();
296 BasicBlock *LoopExitBB = 0;
297 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
298 // If the header block doesn't end with a conditional branch on Cond, we
300 if (!BI->isConditional() || BI->getCondition() != Cond)
303 // Check to see if a successor of the branch is guaranteed to go to the
304 // latch block or exit through a one exit block without having any
305 // side-effects. If so, determine the value of Cond that causes it to do
307 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
308 if (Val) *Val = ConstantBool::True;
309 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
310 if (Val) *Val = ConstantBool::False;
312 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
313 // If this isn't a switch on Cond, we can't handle it.
314 if (SI->getCondition() != Cond) return false;
316 // Check to see if a successor of the switch is guaranteed to go to the
317 // latch block or exit through a one exit block without having any
318 // side-effects. If so, determine the value of Cond that causes it to do
319 // this. Note that we can't trivially unswitch on the default case.
320 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
321 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
322 // Okay, we found a trivial case, remember the value that is trivial.
323 if (Val) *Val = SI->getCaseValue(i);
328 // If we didn't find a single unique LoopExit block, or if the loop exit block
329 // contains phi nodes, this isn't trivial.
330 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
331 return false; // Can't handle this.
333 if (LoopExit) *LoopExit = LoopExitBB;
335 // We already know that nothing uses any scalar values defined inside of this
336 // loop. As such, we just have to check to see if this loop will execute any
337 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
338 // part of the loop that the code *would* execute. We already checked the
339 // tail, check the header now.
340 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
341 if (I->mayWriteToMemory())
346 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
347 /// we choose to unswitch the specified loop on the specified value.
349 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
350 // If the condition is trivial, always unswitch. There is no code growth for
352 if (IsTrivialUnswitchCondition(L, LIC))
356 // FIXME: this is brain dead. It should take into consideration code
358 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
361 // Do not include empty blocks in the cost calculation. This happen due to
362 // loop canonicalization and will be removed.
363 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
366 // Count basic blocks.
373 /// UnswitchIfProfitable - We have found that we can unswitch L when
374 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
375 /// unswitch the loop, reprocess the pieces, then return true.
376 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
377 // Check to see if it would be profitable to unswitch this loop.
378 if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
379 // FIXME: this should estimate growth by the amount of code shared by the
380 // resultant unswitched loops.
382 DEBUG(std::cerr << "NOT unswitching loop %"
383 << L->getHeader()->getName() << ", cost too high: "
384 << L->getBlocks().size() << "\n");
388 // If this loop has live-out values, we can't unswitch it. We need something
389 // like loop-closed SSA form in order to know how to insert PHI nodes for
391 if (LoopValuesUsedOutsideLoop(L)) {
392 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
393 << ", a loop value is used outside loop!\n");
397 // If this is a trivial condition to unswitch (which results in no code
398 // duplication), do it now.
400 BasicBlock *ExitBlock;
401 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
402 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
404 UnswitchNontrivialCondition(LoopCond, Val, L);
410 /// SplitBlock - Split the specified block at the specified instruction - every
411 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
412 /// to a new block. The two blocks are joined by an unconditional branch and
413 /// the loop info is updated.
415 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
416 BasicBlock::iterator SplitIt = SplitPt;
417 while (isa<PHINode>(SplitIt))
419 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
421 // The new block lives in whichever loop the old one did.
422 if (Loop *L = LI->getLoopFor(Old))
423 L->addBasicBlockToLoop(New, *LI);
429 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
430 TerminatorInst *LatchTerm = BB->getTerminator();
431 unsigned SuccNum = 0;
432 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
433 assert(i != e && "Didn't find edge?");
434 if (LatchTerm->getSuccessor(i) == Succ) {
440 // If this is a critical edge, let SplitCriticalEdge do it.
441 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
442 return LatchTerm->getSuccessor(SuccNum);
444 // If the edge isn't critical, then BB has a single successor or Succ has a
445 // single pred. Split the block.
446 BasicBlock::iterator SplitPoint;
447 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
448 // If the successor only has a single pred, split the top of the successor
450 assert(SP == BB && "CFG broken");
451 return SplitBlock(Succ, Succ->begin());
453 // Otherwise, if BB has a single successor, split it at the bottom of the
455 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
456 "Should have a single succ!");
457 return SplitBlock(BB, BB->getTerminator());
463 // RemapInstruction - Convert the instruction operands from referencing the
464 // current values into those specified by ValueMap.
466 static inline void RemapInstruction(Instruction *I,
467 std::map<const Value *, Value*> &ValueMap) {
468 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
469 Value *Op = I->getOperand(op);
470 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
471 if (It != ValueMap.end()) Op = It->second;
472 I->setOperand(op, Op);
476 /// CloneLoop - Recursively clone the specified loop and all of its children,
477 /// mapping the blocks with the specified map.
478 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
480 Loop *New = new Loop();
483 PL->addChildLoop(New);
485 LI->addTopLevelLoop(New);
487 // Add all of the blocks in L to the new loop.
488 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
490 if (LI->getLoopFor(*I) == L)
491 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
493 // Add all of the subloops to the new loop.
494 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
495 CloneLoop(*I, New, VM, LI);
500 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
501 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
502 /// code immediately before InsertPt.
503 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
504 BasicBlock *TrueDest,
505 BasicBlock *FalseDest,
506 Instruction *InsertPt) {
507 // Insert a conditional branch on LIC to the two preheaders. The original
508 // code is the true version and the new code is the false version.
509 Value *BranchVal = LIC;
510 if (!isa<ConstantBool>(Val)) {
511 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
512 } else if (Val != ConstantBool::True) {
513 // We want to enter the new loop when the condition is true.
514 std::swap(TrueDest, FalseDest);
517 // Insert the new branch.
518 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
522 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
523 /// condition in it (a cond branch from its header block to its latch block,
524 /// where the path through the loop that doesn't execute its body has no
525 /// side-effects), unswitch it. This doesn't involve any code duplication, just
526 /// moving the conditional branch outside of the loop and updating loop info.
527 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
529 BasicBlock *ExitBlock) {
530 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
531 << L->getHeader()->getName() << " [" << L->getBlocks().size()
532 << " blocks] in Function " << L->getHeader()->getParent()->getName()
533 << " on cond: " << *Val << " == " << *Cond << "\n");
535 // First step, split the preheader, so that we know that there is a safe place
536 // to insert the conditional branch. We will change 'OrigPH' to have a
537 // conditional branch on Cond.
538 BasicBlock *OrigPH = L->getLoopPreheader();
539 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
541 // Now that we have a place to insert the conditional branch, create a place
542 // to branch to: this is the exit block out of the loop that we should
545 // Split this block now, so that the loop maintains its exit block, and so
546 // that the jump from the preheader can execute the contents of the exit block
547 // without actually branching to it (the exit block should be dominated by the
548 // loop header, not the preheader).
549 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
550 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
552 // Okay, now we have a position to branch from and a position to branch to,
553 // insert the new conditional branch.
554 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
555 OrigPH->getTerminator());
556 OrigPH->getTerminator()->eraseFromParent();
558 // We need to reprocess this loop, it could be unswitched again.
559 LoopProcessWorklist.push_back(L);
561 // Now that we know that the loop is never entered when this condition is a
562 // particular value, rewrite the loop with this info. We know that this will
563 // at least eliminate the old branch.
564 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
569 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
570 /// equal Val. Split it into loop versions and test the condition outside of
571 /// either loop. Return the loops created as Out1/Out2.
572 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
574 Function *F = L->getHeader()->getParent();
575 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
576 << L->getHeader()->getName() << " [" << L->getBlocks().size()
577 << " blocks] in Function " << F->getName()
578 << " when '" << *Val << "' == " << *LIC << "\n");
580 // LoopBlocks contains all of the basic blocks of the loop, including the
581 // preheader of the loop, the body of the loop, and the exit blocks of the
582 // loop, in that order.
583 std::vector<BasicBlock*> LoopBlocks;
585 // First step, split the preheader and exit blocks, and add these blocks to
586 // the LoopBlocks list.
587 BasicBlock *OrigPreheader = L->getLoopPreheader();
588 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
590 // We want the loop to come after the preheader, but before the exit blocks.
591 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
593 std::vector<BasicBlock*> ExitBlocks;
594 L->getExitBlocks(ExitBlocks);
595 std::sort(ExitBlocks.begin(), ExitBlocks.end());
596 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
599 // Split all of the edges from inside the loop to their exit blocks. This
600 // unswitching trivial: no phi nodes to update.
601 unsigned NumBlocks = L->getBlocks().size();
603 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
604 BasicBlock *ExitBlock = ExitBlocks[i];
605 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
607 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
608 assert(L->contains(Preds[j]) &&
609 "All preds of loop exit blocks must be the same loop!");
610 SplitEdge(Preds[j], ExitBlock);
614 // The exit blocks may have been changed due to edge splitting, recompute.
616 L->getExitBlocks(ExitBlocks);
617 std::sort(ExitBlocks.begin(), ExitBlocks.end());
618 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
621 // Add exit blocks to the loop blocks.
622 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
624 // Next step, clone all of the basic blocks that make up the loop (including
625 // the loop preheader and exit blocks), keeping track of the mapping between
626 // the instructions and blocks.
627 std::vector<BasicBlock*> NewBlocks;
628 NewBlocks.reserve(LoopBlocks.size());
629 std::map<const Value*, Value*> ValueMap;
630 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
631 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
632 NewBlocks.push_back(New);
633 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
636 // Splice the newly inserted blocks into the function right before the
637 // original preheader.
638 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
639 NewBlocks[0], F->end());
641 // Now we create the new Loop object for the versioned loop.
642 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
643 Loop *ParentLoop = L->getParentLoop();
645 // Make sure to add the cloned preheader and exit blocks to the parent loop
647 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
650 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
651 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
652 // The new exit block should be in the same loop as the old one.
653 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
654 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
656 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
657 "Exit block should have been split to have one successor!");
658 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
660 // If the successor of the exit block had PHI nodes, add an entry for
663 for (BasicBlock::iterator I = ExitSucc->begin();
664 (PN = dyn_cast<PHINode>(I)); ++I) {
665 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
666 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
667 if (It != ValueMap.end()) V = It->second;
668 PN->addIncoming(V, NewExit);
672 // Rewrite the code to refer to itself.
673 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
674 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
675 E = NewBlocks[i]->end(); I != E; ++I)
676 RemapInstruction(I, ValueMap);
678 // Rewrite the original preheader to select between versions of the loop.
679 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
680 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
681 "Preheader splitting did not work correctly!");
683 // Emit the new branch that selects between the two versions of this loop.
684 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
685 OldBR->eraseFromParent();
687 LoopProcessWorklist.push_back(L);
688 LoopProcessWorklist.push_back(NewLoop);
690 // Now we rewrite the original code to know that the condition is true and the
691 // new code to know that the condition is false.
692 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
694 // It's possible that simplifying one loop could cause the other to be
695 // deleted. If so, don't simplify it.
696 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
697 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
700 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
702 static void RemoveFromWorklist(Instruction *I,
703 std::vector<Instruction*> &Worklist) {
704 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
706 while (WI != Worklist.end()) {
707 unsigned Offset = WI-Worklist.begin();
709 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
713 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
714 /// program, replacing all uses with V and update the worklist.
715 static void ReplaceUsesOfWith(Instruction *I, Value *V,
716 std::vector<Instruction*> &Worklist) {
717 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
719 // Add uses to the worklist, which may be dead now.
720 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
721 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
722 Worklist.push_back(Use);
724 // Add users to the worklist which may be simplified now.
725 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
727 Worklist.push_back(cast<Instruction>(*UI));
728 I->replaceAllUsesWith(V);
729 I->eraseFromParent();
730 RemoveFromWorklist(I, Worklist);
734 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
735 /// information, and remove any dead successors it has.
737 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
738 std::vector<Instruction*> &Worklist) {
739 if (pred_begin(BB) != pred_end(BB)) {
740 // This block isn't dead, since an edge to BB was just removed, see if there
741 // are any easy simplifications we can do now.
742 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
743 // If it has one pred, fold phi nodes in BB.
744 while (isa<PHINode>(BB->begin()))
745 ReplaceUsesOfWith(BB->begin(),
746 cast<PHINode>(BB->begin())->getIncomingValue(0),
749 // If this is the header of a loop and the only pred is the latch, we now
750 // have an unreachable loop.
751 if (Loop *L = LI->getLoopFor(BB))
752 if (L->getHeader() == BB && L->contains(Pred)) {
753 // Remove the branch from the latch to the header block, this makes
754 // the header dead, which will make the latch dead (because the header
755 // dominates the latch).
756 Pred->getTerminator()->eraseFromParent();
757 new UnreachableInst(Pred);
759 // The loop is now broken, remove it from LI.
760 RemoveLoopFromHierarchy(L);
762 // Reprocess the header, which now IS dead.
763 RemoveBlockIfDead(BB, Worklist);
767 // If pred ends in a uncond branch, add uncond branch to worklist so that
768 // the two blocks will get merged.
769 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
770 if (BI->isUnconditional())
771 Worklist.push_back(BI);
776 DEBUG(std::cerr << "Nuking dead block: " << *BB);
778 // Remove the instructions in the basic block from the worklist.
779 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
780 RemoveFromWorklist(I, Worklist);
782 // Anything that uses the instructions in this basic block should have their
783 // uses replaced with undefs.
785 I->replaceAllUsesWith(UndefValue::get(I->getType()));
788 // If this is the edge to the header block for a loop, remove the loop and
789 // promote all subloops.
790 if (Loop *BBLoop = LI->getLoopFor(BB)) {
791 if (BBLoop->getLoopLatch() == BB)
792 RemoveLoopFromHierarchy(BBLoop);
795 // Remove the block from the loop info, which removes it from any loops it
800 // Remove phi node entries in successors for this block.
801 TerminatorInst *TI = BB->getTerminator();
802 std::vector<BasicBlock*> Succs;
803 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
804 Succs.push_back(TI->getSuccessor(i));
805 TI->getSuccessor(i)->removePredecessor(BB);
808 // Unique the successors, remove anything with multiple uses.
809 std::sort(Succs.begin(), Succs.end());
810 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
812 // Remove the basic block, including all of the instructions contained in it.
813 BB->eraseFromParent();
815 // Remove successor blocks here that are not dead, so that we know we only
816 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
817 // then getting removed before we revisit them, which is badness.
819 for (unsigned i = 0; i != Succs.size(); ++i)
820 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
821 // One exception is loop headers. If this block was the preheader for a
822 // loop, then we DO want to visit the loop so the loop gets deleted.
823 // We know that if the successor is a loop header, that this loop had to
824 // be the preheader: the case where this was the latch block was handled
825 // above and headers can only have two predecessors.
826 if (!LI->isLoopHeader(Succs[i])) {
827 Succs.erase(Succs.begin()+i);
832 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
833 RemoveBlockIfDead(Succs[i], Worklist);
836 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
837 /// become unwrapped, either because the backedge was deleted, or because the
838 /// edge into the header was removed. If the edge into the header from the
839 /// latch block was removed, the loop is unwrapped but subloops are still alive,
840 /// so they just reparent loops. If the loops are actually dead, they will be
842 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
843 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
844 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
845 // they are now all in it.
846 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
848 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
849 LI->changeLoopFor(*I, ParentLoop);
851 // Remove the loop from its parent loop.
852 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
854 assert(I != E && "Couldn't find loop");
856 ParentLoop->removeChildLoop(I);
861 // Move all subloops into the parent loop.
862 while (L->begin() != L->end())
863 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
865 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
866 // they no longer in a loop at all.
868 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
869 // Don't change blocks in subloops.
870 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
871 LI->removeBlock(L->getBlocks()[i]);
876 // Remove the loop from the top-level LoopInfo object.
877 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
878 assert(I != E && "Couldn't find loop");
885 // Move all of the subloops to the top-level.
886 while (L->begin() != L->end())
887 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
891 RemoveLoopFromWorklist(L);
896 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
897 // the value specified by Val in the specified loop, or we know it does NOT have
898 // that value. Rewrite any uses of LIC or of properties correlated to it.
899 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
902 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
904 // FIXME: Support correlated properties, like:
911 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
912 // selects, switches.
913 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
914 std::vector<Instruction*> Worklist;
916 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
917 // in the loop with the appropriate one directly.
918 if (IsEqual || isa<ConstantBool>(Val)) {
923 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
925 for (unsigned i = 0, e = Users.size(); i != e; ++i)
926 if (Instruction *U = cast<Instruction>(Users[i])) {
927 if (!L->contains(U->getParent()))
929 U->replaceUsesOfWith(LIC, Replacement);
930 Worklist.push_back(U);
933 // Otherwise, we don't know the precise value of LIC, but we do know that it
934 // is certainly NOT "Val". As such, simplify any uses in the loop that we
935 // can. This case occurs when we unswitch switch statements.
936 for (unsigned i = 0, e = Users.size(); i != e; ++i)
937 if (Instruction *U = cast<Instruction>(Users[i])) {
938 if (!L->contains(U->getParent()))
941 Worklist.push_back(U);
943 // If we know that LIC is not Val, use this info to simplify code.
944 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
945 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
946 if (SI->getCaseValue(i) == Val) {
947 // Found a dead case value. Don't remove PHI nodes in the
948 // successor if they become single-entry, those PHI nodes may
949 // be in the Users list.
950 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
957 // TODO: We could do other simplifications, for example, turning
958 // LIC == Val -> false.
962 SimplifyCode(Worklist);
965 /// SimplifyCode - Okay, now that we have simplified some instructions in the
966 /// loop, walk over it and constant prop, dce, and fold control flow where
967 /// possible. Note that this is effectively a very simple loop-structure-aware
968 /// optimizer. During processing of this loop, L could very well be deleted, so
969 /// it must not be used.
971 /// FIXME: When the loop optimizer is more mature, separate this out to a new
974 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
975 while (!Worklist.empty()) {
976 Instruction *I = Worklist.back();
979 // Simple constant folding.
980 if (Constant *C = ConstantFoldInstruction(I)) {
981 ReplaceUsesOfWith(I, C, Worklist);
986 if (isInstructionTriviallyDead(I)) {
987 DEBUG(std::cerr << "Remove dead instruction '" << *I);
989 // Add uses to the worklist, which may be dead now.
990 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
991 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
992 Worklist.push_back(Use);
993 I->eraseFromParent();
994 RemoveFromWorklist(I, Worklist);
999 // Special case hacks that appear commonly in unswitched code.
1000 switch (I->getOpcode()) {
1001 case Instruction::Select:
1002 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1003 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1007 case Instruction::And:
1008 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1009 cast<BinaryOperator>(I)->swapOperands();
1010 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1011 if (CB->getValue()) // X & 1 -> X
1012 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1014 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1018 case Instruction::Or:
1019 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1020 cast<BinaryOperator>(I)->swapOperands();
1021 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1022 if (CB->getValue()) // X | 1 -> 1
1023 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1025 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1029 case Instruction::Br: {
1030 BranchInst *BI = cast<BranchInst>(I);
1031 if (BI->isUnconditional()) {
1032 // If BI's parent is the only pred of the successor, fold the two blocks
1034 BasicBlock *Pred = BI->getParent();
1035 BasicBlock *Succ = BI->getSuccessor(0);
1036 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1037 if (!SinglePred) continue; // Nothing to do.
1038 assert(SinglePred == Pred && "CFG broken");
1040 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1041 << Succ->getName() << "\n");
1043 // Resolve any single entry PHI nodes in Succ.
1044 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1045 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1047 // Move all of the successor contents from Succ to Pred.
1048 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1050 BI->eraseFromParent();
1051 RemoveFromWorklist(BI, Worklist);
1053 // If Succ has any successors with PHI nodes, update them to have
1054 // entries coming from Pred instead of Succ.
1055 Succ->replaceAllUsesWith(Pred);
1057 // Remove Succ from the loop tree.
1058 LI->removeBlock(Succ);
1059 Succ->eraseFromParent();
1061 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
1062 // Conditional branch. Turn it into an unconditional branch, then
1063 // remove dead blocks.
1064 break; // FIXME: Enable.
1066 DEBUG(std::cerr << "Folded branch: " << *BI);
1067 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1068 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1069 DeadSucc->removePredecessor(BI->getParent(), true);
1070 Worklist.push_back(new BranchInst(LiveSucc, BI));
1071 BI->eraseFromParent();
1072 RemoveFromWorklist(BI, Worklist);
1075 RemoveBlockIfDead(DeadSucc, Worklist);