1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops. For example, it turns the left into the right code:
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
27 //===----------------------------------------------------------------------===//
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/PostOrderIterator.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
52 STATISTIC(NumBranches, "Number of branches unswitched");
53 STATISTIC(NumSwitches, "Number of switches unswitched");
54 STATISTIC(NumSelects , "Number of selects unswitched");
55 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
63 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
64 LoopInfo *LI; // Loop information
67 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
69 std::vector<Loop*> LoopProcessWorklist;
70 SmallPtrSet<Value *,8> UnswitchedVals;
75 static char ID; // Pass ID, replacement for typeid
76 explicit LoopUnswitch(bool Os = false) :
77 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false) {}
79 bool runOnLoop(Loop *L, LPPassManager &LPM);
80 bool processLoop(Loop *L);
82 /// This transformation requires natural loop information & requires that
83 /// loop preheaders be inserted into the CFG...
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequiredID(LoopSimplifyID);
87 AU.addPreservedID(LoopSimplifyID);
88 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
92 AU.addPreserved<DominatorTree>();
93 AU.addPreserved<DominanceFrontier>();
98 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
100 void RemoveLoopFromWorklist(Loop *L) {
101 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
102 LoopProcessWorklist.end(), L);
103 if (I != LoopProcessWorklist.end())
104 LoopProcessWorklist.erase(I);
107 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
108 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
109 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
110 BasicBlock *ExitBlock);
111 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
113 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
114 Constant *Val, bool isEqual);
116 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
117 BasicBlock *TrueDest,
118 BasicBlock *FalseDest,
119 Instruction *InsertPt);
121 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
122 void RemoveBlockIfDead(BasicBlock *BB,
123 std::vector<Instruction*> &Worklist, Loop *l);
124 void RemoveLoopFromHierarchy(Loop *L);
126 char LoopUnswitch::ID = 0;
127 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
130 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
131 return new LoopUnswitch(Os);
134 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
135 /// invariant in the loop, or has an invariant piece, return the invariant.
136 /// Otherwise, return null.
137 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
138 // Constants should be folded, not unswitched on!
139 if (isa<Constant>(Cond)) return false;
141 // TODO: Handle: br (VARIANT|INVARIANT).
142 // TODO: Hoist simple expressions out of loops.
143 if (L->isLoopInvariant(Cond)) return Cond;
145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
146 if (BO->getOpcode() == Instruction::And ||
147 BO->getOpcode() == Instruction::Or) {
148 // If either the left or right side is invariant, we can unswitch on this,
149 // which will cause the branch to go away in one loop and the condition to
150 // simplify in the other one.
151 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
153 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
160 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
161 LI = &getAnalysis<LoopInfo>();
163 bool Changed = false;
167 Changed |= processLoop(L);
173 /// processLoop - Do actual work and unswitch loop if possible and profitable.
174 bool LoopUnswitch::processLoop(Loop *L) {
175 assert(L->isLCSSAForm());
176 bool Changed = false;
178 // Loop over all of the basic blocks in the loop. If we find an interior
179 // block that is branching on a loop-invariant condition, we can unswitch this
181 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
183 TerminatorInst *TI = (*I)->getTerminator();
184 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
185 // If this isn't branching on an invariant condition, we can't unswitch
187 if (BI->isConditional()) {
188 // See if this, or some part of it, is loop invariant. If so, we can
189 // unswitch on it if we desire.
190 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
191 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
197 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
199 if (LoopCond && SI->getNumCases() > 1) {
200 // Find a value to unswitch on:
201 // FIXME: this should chose the most expensive case!
202 Constant *UnswitchVal = SI->getCaseValue(1);
203 // Do not process same value again and again.
204 if (!UnswitchedVals.insert(UnswitchVal))
207 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
214 // Scan the instructions to check for unswitchable values.
215 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
217 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
218 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
219 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
227 assert(L->isLCSSAForm());
232 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
233 /// 1. Exit the loop with no side effects.
234 /// 2. Branch to the latch block with no side-effects.
236 /// If these conditions are true, we return true and set ExitBB to the block we
239 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
241 std::set<BasicBlock*> &Visited) {
242 if (!Visited.insert(BB).second) {
243 // Already visited and Ok, end of recursion.
245 } else if (!L->contains(BB)) {
246 // Otherwise, this is a loop exit, this is fine so long as this is the
248 if (ExitBB != 0) return false;
253 // Otherwise, this is an unvisited intra-loop node. Check all successors.
254 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
255 // Check to see if the successor is a trivial loop exit.
256 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
260 // Okay, everything after this looks good, check to make sure that this block
261 // doesn't include any side effects.
262 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
263 if (I->mayWriteToMemory())
269 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
270 /// leads to an exit from the specified loop, and has no side-effects in the
271 /// process. If so, return the block that is exited to, otherwise return null.
272 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
273 std::set<BasicBlock*> Visited;
274 Visited.insert(L->getHeader()); // Branches to header are ok.
275 BasicBlock *ExitBB = 0;
276 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
281 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
282 /// trivial: that is, that the condition controls whether or not the loop does
283 /// anything at all. If this is a trivial condition, unswitching produces no
284 /// code duplications (equivalently, it produces a simpler loop and a new empty
285 /// loop, which gets deleted).
287 /// If this is a trivial condition, return true, otherwise return false. When
288 /// returning true, this sets Cond and Val to the condition that controls the
289 /// trivial condition: when Cond dynamically equals Val, the loop is known to
290 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
293 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
294 BasicBlock **LoopExit = 0) {
295 BasicBlock *Header = L->getHeader();
296 TerminatorInst *HeaderTerm = Header->getTerminator();
298 BasicBlock *LoopExitBB = 0;
299 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
300 // If the header block doesn't end with a conditional branch on Cond, we
302 if (!BI->isConditional() || BI->getCondition() != Cond)
305 // Check to see if a successor of the branch is guaranteed to go to the
306 // latch block or exit through a one exit block without having any
307 // side-effects. If so, determine the value of Cond that causes it to do
309 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
310 if (Val) *Val = ConstantInt::getTrue();
311 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
312 if (Val) *Val = ConstantInt::getFalse();
314 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
315 // If this isn't a switch on Cond, we can't handle it.
316 if (SI->getCondition() != Cond) return false;
318 // Check to see if a successor of the switch is guaranteed to go to the
319 // latch block or exit through a one exit block without having any
320 // side-effects. If so, determine the value of Cond that causes it to do
321 // this. Note that we can't trivially unswitch on the default case.
322 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
323 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
324 // Okay, we found a trivial case, remember the value that is trivial.
325 if (Val) *Val = SI->getCaseValue(i);
330 // If we didn't find a single unique LoopExit block, or if the loop exit block
331 // contains phi nodes, this isn't trivial.
332 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
333 return false; // Can't handle this.
335 if (LoopExit) *LoopExit = LoopExitBB;
337 // We already know that nothing uses any scalar values defined inside of this
338 // loop. As such, we just have to check to see if this loop will execute any
339 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
340 // part of the loop that the code *would* execute. We already checked the
341 // tail, check the header now.
342 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
343 if (I->mayWriteToMemory())
348 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
349 /// we choose to unswitch the specified loop on the specified value.
351 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
352 // If the condition is trivial, always unswitch. There is no code growth for
354 if (IsTrivialUnswitchCondition(L, LIC))
357 // FIXME: This is really overly conservative. However, more liberal
358 // estimations have thus far resulted in excessive unswitching, which is bad
359 // both in compile time and in code size. This should be replaced once
360 // someone figures out how a good estimation.
361 return L->getBlocks().size();
364 // FIXME: this is brain dead. It should take into consideration code
366 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
369 // Do not include empty blocks in the cost calculation. This happen due to
370 // loop canonicalization and will be removed.
371 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
374 // Count basic blocks.
381 /// UnswitchIfProfitable - We have found that we can unswitch L when
382 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
383 /// unswitch the loop, reprocess the pieces, then return true.
384 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
385 // Check to see if it would be profitable to unswitch this loop.
386 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
388 // Do not do non-trivial unswitch while optimizing for size.
389 if (Cost && OptimizeForSize)
392 if (Cost > Threshold) {
393 // FIXME: this should estimate growth by the amount of code shared by the
394 // resultant unswitched loops.
396 DOUT << "NOT unswitching loop %"
397 << L->getHeader()->getName() << ", cost too high: "
398 << L->getBlocks().size() << "\n";
402 // If this is a trivial condition to unswitch (which results in no code
403 // duplication), do it now.
405 BasicBlock *ExitBlock;
406 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
407 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
409 UnswitchNontrivialCondition(LoopCond, Val, L);
415 // RemapInstruction - Convert the instruction operands from referencing the
416 // current values into those specified by ValueMap.
418 static inline void RemapInstruction(Instruction *I,
419 DenseMap<const Value *, Value*> &ValueMap) {
420 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
421 Value *Op = I->getOperand(op);
422 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
423 if (It != ValueMap.end()) Op = It->second;
424 I->setOperand(op, Op);
428 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
430 // If Orig block's immediate dominator is mapped in VM then use corresponding
431 // immediate dominator from the map. Otherwise Orig block's dominator is also
432 // NewBB's dominator.
434 // OrigPreheader is loop pre-header before this pass started
435 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
436 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
437 void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
438 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
439 BasicBlock *OrigHeader,
440 DominatorTree *DT, DominanceFrontier *DF,
441 DenseMap<const Value*, Value*> &VM) {
443 // If NewBB alreay has found its place in domiantor tree then no need to do
445 if (DT->getNode(NewBB))
448 // If Orig does not have any immediate domiantor then its clone, NewBB, does
449 // not need any immediate dominator.
450 DomTreeNode *OrigNode = DT->getNode(Orig);
453 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
457 BasicBlock *OrigIDom = NULL;
459 // If Orig is original loop header then its immediate dominator is
461 if (Orig == OrigHeader)
462 OrigIDom = NewPreheader;
464 // If Orig is new pre-header then its immediate dominator is
465 // original pre-header.
466 else if (Orig == NewPreheader)
467 OrigIDom = OrigPreheader;
469 // Other as DT to find Orig's immediate dominator.
471 OrigIDom = OrigIDomNode->getBlock();
473 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
474 BasicBlock *NewIDom = OrigIDom;
475 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
477 NewIDom = cast<BasicBlock>(I->second);
479 // If NewIDom does not have corresponding dominatore tree node then
481 if (!DT->getNode(NewIDom))
482 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
483 OrigHeader, DT, DF, VM);
486 DT->addNewBlock(NewBB, NewIDom);
488 // Copy cloned dominance frontiner set
489 DominanceFrontier::DomSetType NewDFSet;
491 DominanceFrontier::iterator DFI = DF->find(Orig);
492 if ( DFI != DF->end()) {
493 DominanceFrontier::DomSetType S = DFI->second;
494 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
497 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
499 NewDFSet.insert(cast<BasicBlock>(IDM->second));
504 DF->addBasicBlock(NewBB, NewDFSet);
508 /// CloneLoop - Recursively clone the specified loop and all of its children,
509 /// mapping the blocks with the specified map.
510 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
511 LoopInfo *LI, LPPassManager *LPM) {
512 Loop *New = new Loop();
514 LPM->insertLoop(New, PL);
516 // Add all of the blocks in L to the new loop.
517 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
519 if (LI->getLoopFor(*I) == L)
520 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
522 // Add all of the subloops to the new loop.
523 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
524 CloneLoop(*I, New, VM, LI, LPM);
529 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
530 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
531 /// code immediately before InsertPt.
532 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
533 BasicBlock *TrueDest,
534 BasicBlock *FalseDest,
535 Instruction *InsertPt) {
536 // Insert a conditional branch on LIC to the two preheaders. The original
537 // code is the true version and the new code is the false version.
538 Value *BranchVal = LIC;
539 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
540 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
541 else if (Val != ConstantInt::getTrue())
542 // We want to enter the new loop when the condition is true.
543 std::swap(TrueDest, FalseDest);
545 // Insert the new branch.
546 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
551 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
552 /// condition in it (a cond branch from its header block to its latch block,
553 /// where the path through the loop that doesn't execute its body has no
554 /// side-effects), unswitch it. This doesn't involve any code duplication, just
555 /// moving the conditional branch outside of the loop and updating loop info.
556 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
558 BasicBlock *ExitBlock) {
559 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
560 << L->getHeader()->getName() << " [" << L->getBlocks().size()
561 << " blocks] in Function " << L->getHeader()->getParent()->getName()
562 << " on cond: " << *Val << " == " << *Cond << "\n";
564 // First step, split the preheader, so that we know that there is a safe place
565 // to insert the conditional branch. We will change 'OrigPH' to have a
566 // conditional branch on Cond.
567 BasicBlock *OrigPH = L->getLoopPreheader();
568 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
570 // Now that we have a place to insert the conditional branch, create a place
571 // to branch to: this is the exit block out of the loop that we should
574 // Split this block now, so that the loop maintains its exit block, and so
575 // that the jump from the preheader can execute the contents of the exit block
576 // without actually branching to it (the exit block should be dominated by the
577 // loop header, not the preheader).
578 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
579 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
581 // Okay, now we have a position to branch from and a position to branch to,
582 // insert the new conditional branch.
583 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
584 OrigPH->getTerminator());
585 OrigPH->getTerminator()->eraseFromParent();
586 LPM->deleteSimpleAnalysisValue(OrigPH->getTerminator(), L);
588 // We need to reprocess this loop, it could be unswitched again.
591 // Now that we know that the loop is never entered when this condition is a
592 // particular value, rewrite the loop with this info. We know that this will
593 // at least eliminate the old branch.
594 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
598 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
599 /// equal Val. Split it into loop versions and test the condition outside of
600 /// either loop. Return the loops created as Out1/Out2.
601 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
603 Function *F = L->getHeader()->getParent();
604 DOUT << "loop-unswitch: Unswitching loop %"
605 << L->getHeader()->getName() << " [" << L->getBlocks().size()
606 << " blocks] in Function " << F->getName()
607 << " when '" << *Val << "' == " << *LIC << "\n";
609 // LoopBlocks contains all of the basic blocks of the loop, including the
610 // preheader of the loop, the body of the loop, and the exit blocks of the
611 // loop, in that order.
612 std::vector<BasicBlock*> LoopBlocks;
614 // First step, split the preheader and exit blocks, and add these blocks to
615 // the LoopBlocks list.
616 BasicBlock *OrigHeader = L->getHeader();
617 BasicBlock *OrigPreheader = L->getLoopPreheader();
618 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
619 LoopBlocks.push_back(NewPreheader);
621 // We want the loop to come after the preheader, but before the exit blocks.
622 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
624 std::vector<BasicBlock*> ExitBlocks;
625 L->getUniqueExitBlocks(ExitBlocks);
627 // Split all of the edges from inside the loop to their exit blocks. Update
628 // the appropriate Phi nodes as we do so.
629 SmallVector<BasicBlock *,8> MiddleBlocks;
630 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
631 BasicBlock *ExitBlock = ExitBlocks[i];
632 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
634 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
635 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
636 MiddleBlocks.push_back(MiddleBlock);
637 BasicBlock* StartBlock = Preds[j];
638 BasicBlock* EndBlock;
639 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
640 EndBlock = MiddleBlock;
641 MiddleBlock = EndBlock->getSinglePredecessor();;
643 EndBlock = ExitBlock;
646 std::set<PHINode*> InsertedPHIs;
647 PHINode* OldLCSSA = 0;
648 for (BasicBlock::iterator I = EndBlock->begin();
649 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
650 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
651 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
652 OldLCSSA->getName() + ".us-lcssa",
653 MiddleBlock->getTerminator());
654 NewLCSSA->addIncoming(OldValue, StartBlock);
655 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
657 InsertedPHIs.insert(NewLCSSA);
660 BasicBlock::iterator InsertPt = EndBlock->begin();
661 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
662 for (BasicBlock::iterator I = MiddleBlock->begin();
663 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
665 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
666 OldLCSSA->getName() + ".us-lcssa",
668 OldLCSSA->replaceAllUsesWith(NewLCSSA);
669 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
674 // The exit blocks may have been changed due to edge splitting, recompute.
676 L->getUniqueExitBlocks(ExitBlocks);
678 // Add exit blocks to the loop blocks.
679 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
681 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
682 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
684 // Next step, clone all of the basic blocks that make up the loop (including
685 // the loop preheader and exit blocks), keeping track of the mapping between
686 // the instructions and blocks.
687 std::vector<BasicBlock*> NewBlocks;
688 NewBlocks.reserve(LoopBlocks.size());
689 DenseMap<const Value*, Value*> ValueMap;
690 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
691 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
692 NewBlocks.push_back(New);
693 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
694 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
697 // OutSiders are basic block that are dominated by original header and
698 // at the same time they are not part of loop.
699 SmallPtrSet<BasicBlock *, 8> OutSiders;
701 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
702 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
703 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
704 BasicBlock *B = (*DI)->getBlock();
706 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
707 if (VI == ValueMap.end())
712 // Splice the newly inserted blocks into the function right before the
713 // original preheader.
714 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
715 NewBlocks[0], F->end());
717 // Now we create the new Loop object for the versioned loop.
718 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
719 Loop *ParentLoop = L->getParentLoop();
721 // Make sure to add the cloned preheader and exit blocks to the parent loop
723 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
726 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
727 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
728 // The new exit block should be in the same loop as the old one.
729 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
730 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
732 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
733 "Exit block should have been split to have one successor!");
734 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
736 // If the successor of the exit block had PHI nodes, add an entry for
739 for (BasicBlock::iterator I = ExitSucc->begin();
740 (PN = dyn_cast<PHINode>(I)); ++I) {
741 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
742 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
743 if (It != ValueMap.end()) V = It->second;
744 PN->addIncoming(V, NewExit);
748 // Rewrite the code to refer to itself.
749 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
750 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
751 E = NewBlocks[i]->end(); I != E; ++I)
752 RemapInstruction(I, ValueMap);
754 // Rewrite the original preheader to select between versions of the loop.
755 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
756 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
757 "Preheader splitting did not work correctly!");
759 // Emit the new branch that selects between the two versions of this loop.
760 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
761 OldBR->eraseFromParent();
762 LPM->deleteSimpleAnalysisValue(OldBR, L);
764 // Update dominator info
767 // Clone dominator info for all cloned basic block.
768 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
769 BasicBlock *LBB = LoopBlocks[i];
770 BasicBlock *NBB = NewBlocks[i];
771 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
772 OrigHeader, DT, DF, ValueMap);
774 // Remove any OutSiders from LBB and NBB's dominance frontier.
775 DominanceFrontier::iterator LBBI = DF->find(LBB);
776 if (LBBI != DF->end()) {
777 DominanceFrontier::DomSetType &LBSet = LBBI->second;
778 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
779 LE = LBSet.end(); LI != LE; ++LI) {
781 if (OutSiders.count(B))
782 DF->removeFromFrontier(LBBI, B);
786 // Remove any OutSiders from LBB and NBB's dominance frontier.
787 DominanceFrontier::iterator NBBI = DF->find(NBB);
788 if (NBBI != DF->end()) {
789 DominanceFrontier::DomSetType NBSet = NBBI->second;
790 for (DominanceFrontier::DomSetType::iterator NI = NBSet.begin(),
791 NE = NBSet.end(); NI != NE; ++NI) {
793 if (OutSiders.count(B))
794 DF->removeFromFrontier(NBBI, B);
799 // MiddleBlocks are dominated by original pre header. SplitEdge updated
800 // MiddleBlocks' dominance frontier appropriately.
801 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
802 BasicBlock *MBB = MiddleBlocks[i];
803 if (!MBB->getSinglePredecessor())
804 DT->changeImmediateDominator(MBB, OrigPreheader);
807 // All Outsiders are now dominated by original pre header.
808 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
809 OE = OutSiders.end(); OI != OE; ++OI) {
810 BasicBlock *OB = *OI;
811 DT->changeImmediateDominator(OB, OrigPreheader);
814 // New loop headers are dominated by original preheader
815 DT->changeImmediateDominator(NewBlocks[0], OrigPreheader);
816 DT->changeImmediateDominator(LoopBlocks[0], OrigPreheader);
819 LoopProcessWorklist.push_back(NewLoop);
822 // Now we rewrite the original code to know that the condition is true and the
823 // new code to know that the condition is false.
824 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
826 // It's possible that simplifying one loop could cause the other to be
827 // deleted. If so, don't simplify it.
828 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
829 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
832 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
834 static void RemoveFromWorklist(Instruction *I,
835 std::vector<Instruction*> &Worklist) {
836 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
838 while (WI != Worklist.end()) {
839 unsigned Offset = WI-Worklist.begin();
841 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
845 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
846 /// program, replacing all uses with V and update the worklist.
847 static void ReplaceUsesOfWith(Instruction *I, Value *V,
848 std::vector<Instruction*> &Worklist,
849 Loop *L, LPPassManager *LPM) {
850 DOUT << "Replace with '" << *V << "': " << *I;
852 // Add uses to the worklist, which may be dead now.
853 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
854 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
855 Worklist.push_back(Use);
857 // Add users to the worklist which may be simplified now.
858 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
860 Worklist.push_back(cast<Instruction>(*UI));
861 I->replaceAllUsesWith(V);
862 I->eraseFromParent();
863 LPM->deleteSimpleAnalysisValue(I, L);
864 RemoveFromWorklist(I, Worklist);
868 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
869 /// information, and remove any dead successors it has.
871 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
872 std::vector<Instruction*> &Worklist,
874 if (pred_begin(BB) != pred_end(BB)) {
875 // This block isn't dead, since an edge to BB was just removed, see if there
876 // are any easy simplifications we can do now.
877 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
878 // If it has one pred, fold phi nodes in BB.
879 while (isa<PHINode>(BB->begin()))
880 ReplaceUsesOfWith(BB->begin(),
881 cast<PHINode>(BB->begin())->getIncomingValue(0),
884 // If this is the header of a loop and the only pred is the latch, we now
885 // have an unreachable loop.
886 if (Loop *L = LI->getLoopFor(BB))
887 if (L->getHeader() == BB && L->contains(Pred)) {
888 // Remove the branch from the latch to the header block, this makes
889 // the header dead, which will make the latch dead (because the header
890 // dominates the latch).
891 Pred->getTerminator()->eraseFromParent();
892 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
893 new UnreachableInst(Pred);
895 // The loop is now broken, remove it from LI.
896 RemoveLoopFromHierarchy(L);
898 // Reprocess the header, which now IS dead.
899 RemoveBlockIfDead(BB, Worklist, L);
903 // If pred ends in a uncond branch, add uncond branch to worklist so that
904 // the two blocks will get merged.
905 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
906 if (BI->isUnconditional())
907 Worklist.push_back(BI);
912 DOUT << "Nuking dead block: " << *BB;
914 // Remove the instructions in the basic block from the worklist.
915 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
916 RemoveFromWorklist(I, Worklist);
918 // Anything that uses the instructions in this basic block should have their
919 // uses replaced with undefs.
921 I->replaceAllUsesWith(UndefValue::get(I->getType()));
924 // If this is the edge to the header block for a loop, remove the loop and
925 // promote all subloops.
926 if (Loop *BBLoop = LI->getLoopFor(BB)) {
927 if (BBLoop->getLoopLatch() == BB)
928 RemoveLoopFromHierarchy(BBLoop);
931 // Remove the block from the loop info, which removes it from any loops it
936 // Remove phi node entries in successors for this block.
937 TerminatorInst *TI = BB->getTerminator();
938 std::vector<BasicBlock*> Succs;
939 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
940 Succs.push_back(TI->getSuccessor(i));
941 TI->getSuccessor(i)->removePredecessor(BB);
944 // Unique the successors, remove anything with multiple uses.
945 std::sort(Succs.begin(), Succs.end());
946 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
948 // Remove the basic block, including all of the instructions contained in it.
949 BB->eraseFromParent();
950 LPM->deleteSimpleAnalysisValue(BB, L);
951 // Remove successor blocks here that are not dead, so that we know we only
952 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
953 // then getting removed before we revisit them, which is badness.
955 for (unsigned i = 0; i != Succs.size(); ++i)
956 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
957 // One exception is loop headers. If this block was the preheader for a
958 // loop, then we DO want to visit the loop so the loop gets deleted.
959 // We know that if the successor is a loop header, that this loop had to
960 // be the preheader: the case where this was the latch block was handled
961 // above and headers can only have two predecessors.
962 if (!LI->isLoopHeader(Succs[i])) {
963 Succs.erase(Succs.begin()+i);
968 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
969 RemoveBlockIfDead(Succs[i], Worklist, L);
972 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
973 /// become unwrapped, either because the backedge was deleted, or because the
974 /// edge into the header was removed. If the edge into the header from the
975 /// latch block was removed, the loop is unwrapped but subloops are still alive,
976 /// so they just reparent loops. If the loops are actually dead, they will be
978 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
979 LPM->deleteLoopFromQueue(L);
980 RemoveLoopFromWorklist(L);
985 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
986 // the value specified by Val in the specified loop, or we know it does NOT have
987 // that value. Rewrite any uses of LIC or of properties correlated to it.
988 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
991 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
993 // FIXME: Support correlated properties, like:
1000 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1001 // selects, switches.
1002 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1003 std::vector<Instruction*> Worklist;
1005 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1006 // in the loop with the appropriate one directly.
1007 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1012 Replacement = ConstantInt::get(Type::Int1Ty,
1013 !cast<ConstantInt>(Val)->getZExtValue());
1015 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1016 if (Instruction *U = cast<Instruction>(Users[i])) {
1017 if (!L->contains(U->getParent()))
1019 U->replaceUsesOfWith(LIC, Replacement);
1020 Worklist.push_back(U);
1023 // Otherwise, we don't know the precise value of LIC, but we do know that it
1024 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1025 // can. This case occurs when we unswitch switch statements.
1026 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1027 if (Instruction *U = cast<Instruction>(Users[i])) {
1028 if (!L->contains(U->getParent()))
1031 Worklist.push_back(U);
1033 // If we know that LIC is not Val, use this info to simplify code.
1034 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1035 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1036 if (SI->getCaseValue(i) == Val) {
1037 // Found a dead case value. Don't remove PHI nodes in the
1038 // successor if they become single-entry, those PHI nodes may
1039 // be in the Users list.
1041 // FIXME: This is a hack. We need to keep the successor around
1042 // and hooked up so as to preserve the loop structure, because
1043 // trying to update it is complicated. So instead we preserve the
1044 // loop structure and put the block on an dead code path.
1046 BasicBlock* Old = SI->getParent();
1047 BasicBlock* Split = SplitBlock(Old, SI, this);
1049 Instruction* OldTerm = Old->getTerminator();
1050 new BranchInst(Split, SI->getSuccessor(i),
1051 ConstantInt::getTrue(), OldTerm);
1053 Old->getTerminator()->eraseFromParent();
1057 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1058 (PN = dyn_cast<PHINode>(II)); ++II) {
1059 Value *InVal = PN->removeIncomingValue(Split, false);
1060 PN->addIncoming(InVal, Old);
1069 // TODO: We could do other simplifications, for example, turning
1070 // LIC == Val -> false.
1074 SimplifyCode(Worklist, L);
1077 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1078 /// loop, walk over it and constant prop, dce, and fold control flow where
1079 /// possible. Note that this is effectively a very simple loop-structure-aware
1080 /// optimizer. During processing of this loop, L could very well be deleted, so
1081 /// it must not be used.
1083 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1086 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1087 while (!Worklist.empty()) {
1088 Instruction *I = Worklist.back();
1089 Worklist.pop_back();
1091 // Simple constant folding.
1092 if (Constant *C = ConstantFoldInstruction(I)) {
1093 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1098 if (isInstructionTriviallyDead(I)) {
1099 DOUT << "Remove dead instruction '" << *I;
1101 // Add uses to the worklist, which may be dead now.
1102 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1103 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1104 Worklist.push_back(Use);
1105 I->eraseFromParent();
1106 LPM->deleteSimpleAnalysisValue(I, L);
1107 RemoveFromWorklist(I, Worklist);
1112 // Special case hacks that appear commonly in unswitched code.
1113 switch (I->getOpcode()) {
1114 case Instruction::Select:
1115 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1116 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L, LPM);
1120 case Instruction::And:
1121 if (isa<ConstantInt>(I->getOperand(0)) &&
1122 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1123 cast<BinaryOperator>(I)->swapOperands();
1124 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1125 if (CB->getType() == Type::Int1Ty) {
1126 if (CB->isOne()) // X & 1 -> X
1127 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1129 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1133 case Instruction::Or:
1134 if (isa<ConstantInt>(I->getOperand(0)) &&
1135 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1136 cast<BinaryOperator>(I)->swapOperands();
1137 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1138 if (CB->getType() == Type::Int1Ty) {
1139 if (CB->isOne()) // X | 1 -> 1
1140 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1142 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1146 case Instruction::Br: {
1147 BranchInst *BI = cast<BranchInst>(I);
1148 if (BI->isUnconditional()) {
1149 // If BI's parent is the only pred of the successor, fold the two blocks
1151 BasicBlock *Pred = BI->getParent();
1152 BasicBlock *Succ = BI->getSuccessor(0);
1153 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1154 if (!SinglePred) continue; // Nothing to do.
1155 assert(SinglePred == Pred && "CFG broken");
1157 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1158 << Succ->getName() << "\n";
1160 // Resolve any single entry PHI nodes in Succ.
1161 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1162 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1164 // Move all of the successor contents from Succ to Pred.
1165 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1167 BI->eraseFromParent();
1168 LPM->deleteSimpleAnalysisValue(BI, L);
1169 RemoveFromWorklist(BI, Worklist);
1171 // If Succ has any successors with PHI nodes, update them to have
1172 // entries coming from Pred instead of Succ.
1173 Succ->replaceAllUsesWith(Pred);
1175 // Remove Succ from the loop tree.
1176 LI->removeBlock(Succ);
1177 Succ->eraseFromParent();
1178 LPM->deleteSimpleAnalysisValue(Succ, L);
1180 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1181 // Conditional branch. Turn it into an unconditional branch, then
1182 // remove dead blocks.
1183 break; // FIXME: Enable.
1185 DOUT << "Folded branch: " << *BI;
1186 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1187 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1188 DeadSucc->removePredecessor(BI->getParent(), true);
1189 Worklist.push_back(new BranchInst(LiveSucc, BI));
1190 BI->eraseFromParent();
1191 LPM->deleteSimpleAnalysisValue(BI, L);
1192 RemoveFromWorklist(BI, Worklist);
1195 RemoveBlockIfDead(DeadSucc, Worklist, L);