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
431 // If Orig block's immediate dominator is mapped in VM then use corresponding
432 // immediate dominator from the map. Otherwise Orig block's dominator is also
433 // NewBB's dominator.
435 // OrigPreheader is loop pre-header before this pass started
436 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
437 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
438 void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
439 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
440 BasicBlock *OrigHeader,
441 DominatorTree *DT, DominanceFrontier *DF,
442 DenseMap<const Value*, Value*> &VM) {
444 // If NewBB alreay has found its place in domiantor tree then no need to do
446 if (DT->getNode(NewBB))
449 // If Orig does not have any immediate domiantor then its clone, NewBB, does
450 // not need any immediate dominator.
451 DomTreeNode *OrigNode = DT->getNode(Orig);
454 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
458 BasicBlock *OrigIDom = NULL;
460 // If Orig is original loop header then its immediate dominator is
462 if (Orig == OrigHeader)
463 OrigIDom = NewPreheader;
465 // If Orig is new pre-header then its immediate dominator is
466 // original pre-header.
467 else if (Orig == NewPreheader)
468 OrigIDom = OrigPreheader;
470 // Other as DT to find Orig's immediate dominator.
472 OrigIDom = OrigIDomNode->getBlock();
474 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
475 BasicBlock *NewIDom = OrigIDom;
476 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
478 NewIDom = cast<BasicBlock>(I->second);
480 // If NewIDom does not have corresponding dominatore tree node then
482 if (!DT->getNode(NewIDom))
483 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
484 OrigHeader, DT, DF, VM);
487 DT->addNewBlock(NewBB, NewIDom);
489 // Copy cloned dominance frontiner set
490 DominanceFrontier::DomSetType NewDFSet;
492 DominanceFrontier::iterator DFI = DF->find(Orig);
493 if ( DFI != DF->end()) {
494 DominanceFrontier::DomSetType S = DFI->second;
495 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
498 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
500 NewDFSet.insert(cast<BasicBlock>(IDM->second));
505 DF->addBasicBlock(NewBB, NewDFSet);
509 /// CloneLoop - Recursively clone the specified loop and all of its children,
510 /// mapping the blocks with the specified map.
511 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
512 LoopInfo *LI, LPPassManager *LPM) {
513 Loop *New = new Loop();
515 LPM->insertLoop(New, PL);
517 // Add all of the blocks in L to the new loop.
518 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
520 if (LI->getLoopFor(*I) == L)
521 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
523 // Add all of the subloops to the new loop.
524 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
525 CloneLoop(*I, New, VM, LI, LPM);
530 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
531 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
532 /// code immediately before InsertPt.
533 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
534 BasicBlock *TrueDest,
535 BasicBlock *FalseDest,
536 Instruction *InsertPt) {
537 // Insert a conditional branch on LIC to the two preheaders. The original
538 // code is the true version and the new code is the false version.
539 Value *BranchVal = LIC;
540 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
541 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
542 else if (Val != ConstantInt::getTrue())
543 // We want to enter the new loop when the condition is true.
544 std::swap(TrueDest, FalseDest);
546 // Insert the new branch.
547 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
552 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
553 /// condition in it (a cond branch from its header block to its latch block,
554 /// where the path through the loop that doesn't execute its body has no
555 /// side-effects), unswitch it. This doesn't involve any code duplication, just
556 /// moving the conditional branch outside of the loop and updating loop info.
557 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
559 BasicBlock *ExitBlock) {
560 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
561 << L->getHeader()->getName() << " [" << L->getBlocks().size()
562 << " blocks] in Function " << L->getHeader()->getParent()->getName()
563 << " on cond: " << *Val << " == " << *Cond << "\n";
565 // First step, split the preheader, so that we know that there is a safe place
566 // to insert the conditional branch. We will change 'OrigPH' to have a
567 // conditional branch on Cond.
568 BasicBlock *OrigPH = L->getLoopPreheader();
569 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
571 // Now that we have a place to insert the conditional branch, create a place
572 // to branch to: this is the exit block out of the loop that we should
575 // Split this block now, so that the loop maintains its exit block, and so
576 // that the jump from the preheader can execute the contents of the exit block
577 // without actually branching to it (the exit block should be dominated by the
578 // loop header, not the preheader).
579 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
580 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
582 // Okay, now we have a position to branch from and a position to branch to,
583 // insert the new conditional branch.
584 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
585 OrigPH->getTerminator());
586 OrigPH->getTerminator()->eraseFromParent();
587 LPM->deleteSimpleAnalysisValue(OrigPH->getTerminator(), L);
589 // We need to reprocess this loop, it could be unswitched again.
592 // Now that we know that the loop is never entered when this condition is a
593 // particular value, rewrite the loop with this info. We know that this will
594 // at least eliminate the old branch.
595 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
599 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
600 /// equal Val. Split it into loop versions and test the condition outside of
601 /// either loop. Return the loops created as Out1/Out2.
602 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
604 Function *F = L->getHeader()->getParent();
605 DOUT << "loop-unswitch: Unswitching loop %"
606 << L->getHeader()->getName() << " [" << L->getBlocks().size()
607 << " blocks] in Function " << F->getName()
608 << " when '" << *Val << "' == " << *LIC << "\n";
610 // LoopBlocks contains all of the basic blocks of the loop, including the
611 // preheader of the loop, the body of the loop, and the exit blocks of the
612 // loop, in that order.
613 std::vector<BasicBlock*> LoopBlocks;
615 // First step, split the preheader and exit blocks, and add these blocks to
616 // the LoopBlocks list.
617 BasicBlock *OrigHeader = L->getHeader();
618 BasicBlock *OrigPreheader = L->getLoopPreheader();
619 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
620 LoopBlocks.push_back(NewPreheader);
622 // We want the loop to come after the preheader, but before the exit blocks.
623 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
625 std::vector<BasicBlock*> ExitBlocks;
626 L->getUniqueExitBlocks(ExitBlocks);
628 // Split all of the edges from inside the loop to their exit blocks. Update
629 // the appropriate Phi nodes as we do so.
630 SmallVector<BasicBlock *,8> MiddleBlocks;
631 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
632 BasicBlock *ExitBlock = ExitBlocks[i];
633 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
635 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
636 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
637 MiddleBlocks.push_back(MiddleBlock);
638 BasicBlock* StartBlock = Preds[j];
639 BasicBlock* EndBlock;
640 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
641 EndBlock = MiddleBlock;
642 MiddleBlock = EndBlock->getSinglePredecessor();;
644 EndBlock = ExitBlock;
647 std::set<PHINode*> InsertedPHIs;
648 PHINode* OldLCSSA = 0;
649 for (BasicBlock::iterator I = EndBlock->begin();
650 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
651 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
652 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
653 OldLCSSA->getName() + ".us-lcssa",
654 MiddleBlock->getTerminator());
655 NewLCSSA->addIncoming(OldValue, StartBlock);
656 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
658 InsertedPHIs.insert(NewLCSSA);
661 BasicBlock::iterator InsertPt = EndBlock->begin();
662 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
663 for (BasicBlock::iterator I = MiddleBlock->begin();
664 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
666 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
667 OldLCSSA->getName() + ".us-lcssa",
669 OldLCSSA->replaceAllUsesWith(NewLCSSA);
670 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
675 // The exit blocks may have been changed due to edge splitting, recompute.
677 L->getUniqueExitBlocks(ExitBlocks);
679 // Add exit blocks to the loop blocks.
680 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
682 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
683 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
685 // Next step, clone all of the basic blocks that make up the loop (including
686 // the loop preheader and exit blocks), keeping track of the mapping between
687 // the instructions and blocks.
688 std::vector<BasicBlock*> NewBlocks;
689 NewBlocks.reserve(LoopBlocks.size());
690 DenseMap<const Value*, Value*> ValueMap;
691 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
692 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
693 NewBlocks.push_back(New);
694 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
695 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
698 // OutSiders are basic block that are dominated by original header and
699 // at the same time they are not part of loop.
700 SmallPtrSet<BasicBlock *, 8> OutSiders;
702 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
703 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
704 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
705 BasicBlock *B = (*DI)->getBlock();
707 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
708 if (VI == ValueMap.end())
713 // Splice the newly inserted blocks into the function right before the
714 // original preheader.
715 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
716 NewBlocks[0], F->end());
718 // Now we create the new Loop object for the versioned loop.
719 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
720 Loop *ParentLoop = L->getParentLoop();
722 // Make sure to add the cloned preheader and exit blocks to the parent loop
724 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
727 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
728 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
729 // The new exit block should be in the same loop as the old one.
730 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
731 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
733 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
734 "Exit block should have been split to have one successor!");
735 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
737 // If the successor of the exit block had PHI nodes, add an entry for
740 for (BasicBlock::iterator I = ExitSucc->begin();
741 (PN = dyn_cast<PHINode>(I)); ++I) {
742 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
743 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
744 if (It != ValueMap.end()) V = It->second;
745 PN->addIncoming(V, NewExit);
749 // Rewrite the code to refer to itself.
750 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
751 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
752 E = NewBlocks[i]->end(); I != E; ++I)
753 RemapInstruction(I, ValueMap);
755 // Rewrite the original preheader to select between versions of the loop.
756 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
757 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
758 "Preheader splitting did not work correctly!");
760 // Emit the new branch that selects between the two versions of this loop.
761 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
762 OldBR->eraseFromParent();
763 LPM->deleteSimpleAnalysisValue(OldBR, L);
765 // Update dominator info
768 // Clone dominator info for all cloned basic block.
769 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
770 BasicBlock *LBB = LoopBlocks[i];
771 BasicBlock *NBB = NewBlocks[i];
772 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
773 OrigHeader, DT, DF, ValueMap);
775 // Remove any OutSiders from LBB and NBB's dominance frontier.
776 DominanceFrontier::iterator LBBI = DF->find(LBB);
777 if (LBBI != DF->end()) {
778 DominanceFrontier::DomSetType &LBSet = LBBI->second;
779 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
780 LE = LBSet.end(); LI != LE; /* NULL */) {
781 BasicBlock *B = *LI++;
782 if (OutSiders.count(B))
783 DF->removeFromFrontier(LBBI, B);
787 // Remove any OutSiders from LBB and NBB's dominance frontier.
788 DominanceFrontier::iterator NBBI = DF->find(NBB);
789 if (NBBI != DF->end()) {
790 DominanceFrontier::DomSetType NBSet = NBBI->second;
791 for (DominanceFrontier::DomSetType::iterator NI = NBSet.begin(),
792 NE = NBSet.end(); NI != NE; /* NULL */) {
793 BasicBlock *B = *NI++;
794 if (OutSiders.count(B))
795 DF->removeFromFrontier(NBBI, B);
800 // MiddleBlocks are dominated by original pre header. SplitEdge updated
801 // MiddleBlocks' dominance frontier appropriately.
802 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
803 BasicBlock *MBB = MiddleBlocks[i];
804 if (!MBB->getSinglePredecessor())
805 DT->changeImmediateDominator(MBB, OrigPreheader);
808 // All Outsiders are now dominated by original pre header.
809 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
810 OE = OutSiders.end(); OI != OE; ++OI) {
811 BasicBlock *OB = *OI;
812 DT->changeImmediateDominator(OB, OrigPreheader);
815 // New loop headers are dominated by original preheader
816 DT->changeImmediateDominator(NewBlocks[0], OrigPreheader);
817 DT->changeImmediateDominator(LoopBlocks[0], OrigPreheader);
820 LoopProcessWorklist.push_back(NewLoop);
823 // Now we rewrite the original code to know that the condition is true and the
824 // new code to know that the condition is false.
825 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
827 // It's possible that simplifying one loop could cause the other to be
828 // deleted. If so, don't simplify it.
829 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
830 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
833 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
835 static void RemoveFromWorklist(Instruction *I,
836 std::vector<Instruction*> &Worklist) {
837 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
839 while (WI != Worklist.end()) {
840 unsigned Offset = WI-Worklist.begin();
842 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
846 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
847 /// program, replacing all uses with V and update the worklist.
848 static void ReplaceUsesOfWith(Instruction *I, Value *V,
849 std::vector<Instruction*> &Worklist,
850 Loop *L, LPPassManager *LPM) {
851 DOUT << "Replace with '" << *V << "': " << *I;
853 // Add uses to the worklist, which may be dead now.
854 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
855 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
856 Worklist.push_back(Use);
858 // Add users to the worklist which may be simplified now.
859 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
861 Worklist.push_back(cast<Instruction>(*UI));
862 I->replaceAllUsesWith(V);
863 I->eraseFromParent();
864 LPM->deleteSimpleAnalysisValue(I, L);
865 RemoveFromWorklist(I, Worklist);
869 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
870 /// information, and remove any dead successors it has.
872 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
873 std::vector<Instruction*> &Worklist,
875 if (pred_begin(BB) != pred_end(BB)) {
876 // This block isn't dead, since an edge to BB was just removed, see if there
877 // are any easy simplifications we can do now.
878 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
879 // If it has one pred, fold phi nodes in BB.
880 while (isa<PHINode>(BB->begin()))
881 ReplaceUsesOfWith(BB->begin(),
882 cast<PHINode>(BB->begin())->getIncomingValue(0),
885 // If this is the header of a loop and the only pred is the latch, we now
886 // have an unreachable loop.
887 if (Loop *L = LI->getLoopFor(BB))
888 if (L->getHeader() == BB && L->contains(Pred)) {
889 // Remove the branch from the latch to the header block, this makes
890 // the header dead, which will make the latch dead (because the header
891 // dominates the latch).
892 Pred->getTerminator()->eraseFromParent();
893 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
894 new UnreachableInst(Pred);
896 // The loop is now broken, remove it from LI.
897 RemoveLoopFromHierarchy(L);
899 // Reprocess the header, which now IS dead.
900 RemoveBlockIfDead(BB, Worklist, L);
904 // If pred ends in a uncond branch, add uncond branch to worklist so that
905 // the two blocks will get merged.
906 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
907 if (BI->isUnconditional())
908 Worklist.push_back(BI);
913 DOUT << "Nuking dead block: " << *BB;
915 // Remove the instructions in the basic block from the worklist.
916 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
917 RemoveFromWorklist(I, Worklist);
919 // Anything that uses the instructions in this basic block should have their
920 // uses replaced with undefs.
922 I->replaceAllUsesWith(UndefValue::get(I->getType()));
925 // If this is the edge to the header block for a loop, remove the loop and
926 // promote all subloops.
927 if (Loop *BBLoop = LI->getLoopFor(BB)) {
928 if (BBLoop->getLoopLatch() == BB)
929 RemoveLoopFromHierarchy(BBLoop);
932 // Remove the block from the loop info, which removes it from any loops it
937 // Remove phi node entries in successors for this block.
938 TerminatorInst *TI = BB->getTerminator();
939 std::vector<BasicBlock*> Succs;
940 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
941 Succs.push_back(TI->getSuccessor(i));
942 TI->getSuccessor(i)->removePredecessor(BB);
945 // Unique the successors, remove anything with multiple uses.
946 std::sort(Succs.begin(), Succs.end());
947 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
949 // Remove the basic block, including all of the instructions contained in it.
950 BB->eraseFromParent();
951 LPM->deleteSimpleAnalysisValue(BB, L);
952 // Remove successor blocks here that are not dead, so that we know we only
953 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
954 // then getting removed before we revisit them, which is badness.
956 for (unsigned i = 0; i != Succs.size(); ++i)
957 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
958 // One exception is loop headers. If this block was the preheader for a
959 // loop, then we DO want to visit the loop so the loop gets deleted.
960 // We know that if the successor is a loop header, that this loop had to
961 // be the preheader: the case where this was the latch block was handled
962 // above and headers can only have two predecessors.
963 if (!LI->isLoopHeader(Succs[i])) {
964 Succs.erase(Succs.begin()+i);
969 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
970 RemoveBlockIfDead(Succs[i], Worklist, L);
973 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
974 /// become unwrapped, either because the backedge was deleted, or because the
975 /// edge into the header was removed. If the edge into the header from the
976 /// latch block was removed, the loop is unwrapped but subloops are still alive,
977 /// so they just reparent loops. If the loops are actually dead, they will be
979 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
980 LPM->deleteLoopFromQueue(L);
981 RemoveLoopFromWorklist(L);
986 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
987 // the value specified by Val in the specified loop, or we know it does NOT have
988 // that value. Rewrite any uses of LIC or of properties correlated to it.
989 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
992 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
994 // FIXME: Support correlated properties, like:
1001 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1002 // selects, switches.
1003 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1004 std::vector<Instruction*> Worklist;
1006 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1007 // in the loop with the appropriate one directly.
1008 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1013 Replacement = ConstantInt::get(Type::Int1Ty,
1014 !cast<ConstantInt>(Val)->getZExtValue());
1016 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1017 if (Instruction *U = cast<Instruction>(Users[i])) {
1018 if (!L->contains(U->getParent()))
1020 U->replaceUsesOfWith(LIC, Replacement);
1021 Worklist.push_back(U);
1024 // Otherwise, we don't know the precise value of LIC, but we do know that it
1025 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1026 // can. This case occurs when we unswitch switch statements.
1027 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1028 if (Instruction *U = cast<Instruction>(Users[i])) {
1029 if (!L->contains(U->getParent()))
1032 Worklist.push_back(U);
1034 // If we know that LIC is not Val, use this info to simplify code.
1035 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1036 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1037 if (SI->getCaseValue(i) == Val) {
1038 // Found a dead case value. Don't remove PHI nodes in the
1039 // successor if they become single-entry, those PHI nodes may
1040 // be in the Users list.
1042 // FIXME: This is a hack. We need to keep the successor around
1043 // and hooked up so as to preserve the loop structure, because
1044 // trying to update it is complicated. So instead we preserve the
1045 // loop structure and put the block on an dead code path.
1047 BasicBlock* Old = SI->getParent();
1048 BasicBlock* Split = SplitBlock(Old, SI, this);
1050 Instruction* OldTerm = Old->getTerminator();
1051 new BranchInst(Split, SI->getSuccessor(i),
1052 ConstantInt::getTrue(), OldTerm);
1054 Old->getTerminator()->eraseFromParent();
1058 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1059 (PN = dyn_cast<PHINode>(II)); ++II) {
1060 Value *InVal = PN->removeIncomingValue(Split, false);
1061 PN->addIncoming(InVal, Old);
1070 // TODO: We could do other simplifications, for example, turning
1071 // LIC == Val -> false.
1075 SimplifyCode(Worklist, L);
1078 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1079 /// loop, walk over it and constant prop, dce, and fold control flow where
1080 /// possible. Note that this is effectively a very simple loop-structure-aware
1081 /// optimizer. During processing of this loop, L could very well be deleted, so
1082 /// it must not be used.
1084 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1087 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1088 while (!Worklist.empty()) {
1089 Instruction *I = Worklist.back();
1090 Worklist.pop_back();
1092 // Simple constant folding.
1093 if (Constant *C = ConstantFoldInstruction(I)) {
1094 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1099 if (isInstructionTriviallyDead(I)) {
1100 DOUT << "Remove dead instruction '" << *I;
1102 // Add uses to the worklist, which may be dead now.
1103 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1104 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1105 Worklist.push_back(Use);
1106 I->eraseFromParent();
1107 LPM->deleteSimpleAnalysisValue(I, L);
1108 RemoveFromWorklist(I, Worklist);
1113 // Special case hacks that appear commonly in unswitched code.
1114 switch (I->getOpcode()) {
1115 case Instruction::Select:
1116 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1117 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1122 case Instruction::And:
1123 if (isa<ConstantInt>(I->getOperand(0)) &&
1124 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1125 cast<BinaryOperator>(I)->swapOperands();
1126 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1127 if (CB->getType() == Type::Int1Ty) {
1128 if (CB->isOne()) // X & 1 -> X
1129 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1131 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1135 case Instruction::Or:
1136 if (isa<ConstantInt>(I->getOperand(0)) &&
1137 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1138 cast<BinaryOperator>(I)->swapOperands();
1139 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1140 if (CB->getType() == Type::Int1Ty) {
1141 if (CB->isOne()) // X | 1 -> 1
1142 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1144 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1148 case Instruction::Br: {
1149 BranchInst *BI = cast<BranchInst>(I);
1150 if (BI->isUnconditional()) {
1151 // If BI's parent is the only pred of the successor, fold the two blocks
1153 BasicBlock *Pred = BI->getParent();
1154 BasicBlock *Succ = BI->getSuccessor(0);
1155 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1156 if (!SinglePred) continue; // Nothing to do.
1157 assert(SinglePred == Pred && "CFG broken");
1159 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1160 << Succ->getName() << "\n";
1162 // Resolve any single entry PHI nodes in Succ.
1163 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1164 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1166 // Move all of the successor contents from Succ to Pred.
1167 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1169 BI->eraseFromParent();
1170 LPM->deleteSimpleAnalysisValue(BI, L);
1171 RemoveFromWorklist(BI, Worklist);
1173 // If Succ has any successors with PHI nodes, update them to have
1174 // entries coming from Pred instead of Succ.
1175 Succ->replaceAllUsesWith(Pred);
1177 // Remove Succ from the loop tree.
1178 LI->removeBlock(Succ);
1179 Succ->eraseFromParent();
1180 LPM->deleteSimpleAnalysisValue(Succ, L);
1182 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1183 // Conditional branch. Turn it into an unconditional branch, then
1184 // remove dead blocks.
1185 break; // FIXME: Enable.
1187 DOUT << "Folded branch: " << *BI;
1188 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1189 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1190 DeadSucc->removePredecessor(BI->getParent(), true);
1191 Worklist.push_back(new BranchInst(LiveSucc, BI));
1192 BI->eraseFromParent();
1193 LPM->deleteSimpleAnalysisValue(BI, L);
1194 RemoveFromWorklist(BI, Worklist);
1197 RemoveBlockIfDead(DeadSucc, Worklist, L);