1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57 static cl::opt<unsigned>
58 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
62 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63 LoopInfo *LI; // Loop information
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector<Loop*> LoopProcessWorklist;
69 SmallPtrSet<Value *,8> UnswitchedVals;
75 DominanceFrontier *DF;
77 BasicBlock *loopHeader;
78 BasicBlock *loopPreheader;
80 /// LoopDF - Loop's dominance frontier. This set is a collection of
81 /// loop exiting blocks' DF member blocks. However this does set does not
82 /// includes basic blocks that are inside loop.
83 SmallPtrSet<BasicBlock *, 8> LoopDF;
85 /// OrigLoopExitMap - This is used to map loop exiting block with
86 /// corresponding loop exit block, before updating CFG.
87 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
89 // LoopBlocks contains all of the basic blocks of the loop, including the
90 // preheader of the loop, the body of the loop, and the exit blocks of the
91 // loop, in that order.
92 std::vector<BasicBlock*> LoopBlocks;
93 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94 std::vector<BasicBlock*> NewBlocks;
96 static char ID; // Pass ID, replacement for typeid
97 explicit LoopUnswitch(bool Os = false) :
98 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
99 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100 loopPreheader(NULL) {}
102 bool runOnLoop(Loop *L, LPPassManager &LPM);
103 bool processCurrentLoop();
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addPreservedID(LoopSimplifyID);
111 AU.addRequired<LoopInfo>();
112 AU.addPreserved<LoopInfo>();
113 AU.addRequiredID(LCSSAID);
114 AU.addPreservedID(LCSSAID);
115 // FIXME: Loop Unswitch does not preserve dominator info in all cases.
116 // AU.addPreserved<DominatorTree>();
117 // AU.addPreserved<DominanceFrontier>();
122 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
124 void RemoveLoopFromWorklist(Loop *L) {
125 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
126 LoopProcessWorklist.end(), L);
127 if (I != LoopProcessWorklist.end())
128 LoopProcessWorklist.erase(I);
131 void initLoopData() {
132 loopHeader = currentLoop->getHeader();
133 loopPreheader = currentLoop->getLoopPreheader();
136 /// Split all of the edges from inside the loop to their exit blocks.
137 /// Update the appropriate Phi nodes as we do so.
138 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
139 SmallVector<BasicBlock *, 8> &MiddleBlocks);
141 /// If BB's dominance frontier has a member that is not part of loop L then
142 /// remove it. Add NewDFMember in BB's dominance frontier.
143 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
144 BasicBlock *NewDFMember);
146 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
147 unsigned getLoopUnswitchCost(Value *LIC);
148 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
149 BasicBlock *ExitBlock);
150 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
152 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
153 Constant *Val, bool isEqual);
155 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
156 BasicBlock *TrueDest,
157 BasicBlock *FalseDest,
158 Instruction *InsertPt);
160 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
161 void RemoveBlockIfDead(BasicBlock *BB,
162 std::vector<Instruction*> &Worklist, Loop *l);
163 void RemoveLoopFromHierarchy(Loop *L);
164 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
165 BasicBlock **LoopExit = 0);
169 char LoopUnswitch::ID = 0;
170 static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
172 LoopPass *llvm::createLoopUnswitchPass(bool Os) {
173 return new LoopUnswitch(Os);
176 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
177 /// invariant in the loop, or has an invariant piece, return the invariant.
178 /// Otherwise, return null.
179 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
180 // Constants should be folded, not unswitched on!
181 if (isa<Constant>(Cond)) return false;
183 // TODO: Handle: br (VARIANT|INVARIANT).
184 // TODO: Hoist simple expressions out of loops.
185 if (L->isLoopInvariant(Cond)) return Cond;
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
188 if (BO->getOpcode() == Instruction::And ||
189 BO->getOpcode() == Instruction::Or) {
190 // If either the left or right side is invariant, we can unswitch on this,
191 // which will cause the branch to go away in one loop and the condition to
192 // simplify in the other one.
193 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
195 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
202 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
203 LI = &getAnalysis<LoopInfo>();
205 DF = getAnalysisToUpdate<DominanceFrontier>();
206 DT = getAnalysisToUpdate<DominatorTree>();
208 bool Changed = false;
211 assert(currentLoop->isLCSSAForm());
213 Changed |= processCurrentLoop();
219 /// processCurrentLoop - Do actual work and unswitch loop if possible
221 bool LoopUnswitch::processCurrentLoop() {
222 bool Changed = false;
224 // Loop over all of the basic blocks in the loop. If we find an interior
225 // block that is branching on a loop-invariant condition, we can unswitch this
227 for (Loop::block_iterator I = currentLoop->block_begin(),
228 E = currentLoop->block_end();
230 TerminatorInst *TI = (*I)->getTerminator();
231 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
232 // If this isn't branching on an invariant condition, we can't unswitch
234 if (BI->isConditional()) {
235 // See if this, or some part of it, is loop invariant. If so, we can
236 // unswitch on it if we desire.
237 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
238 currentLoop, Changed);
239 if (LoopCond && UnswitchIfProfitable(LoopCond,
240 ConstantInt::getTrue())) {
245 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
246 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
247 currentLoop, Changed);
248 if (LoopCond && SI->getNumCases() > 1) {
249 // Find a value to unswitch on:
250 // FIXME: this should chose the most expensive case!
251 Constant *UnswitchVal = SI->getCaseValue(1);
252 // Do not process same value again and again.
253 if (!UnswitchedVals.insert(UnswitchVal))
256 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
263 // Scan the instructions to check for unswitchable values.
264 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
266 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
267 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
268 currentLoop, Changed);
269 if (LoopCond && UnswitchIfProfitable(LoopCond,
270 ConstantInt::getTrue())) {
279 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
280 /// 1. Exit the loop with no side effects.
281 /// 2. Branch to the latch block with no side-effects.
283 /// If these conditions are true, we return true and set ExitBB to the block we
286 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
288 std::set<BasicBlock*> &Visited) {
289 if (!Visited.insert(BB).second) {
290 // Already visited and Ok, end of recursion.
292 } else if (!L->contains(BB)) {
293 // Otherwise, this is a loop exit, this is fine so long as this is the
295 if (ExitBB != 0) return false;
300 // Otherwise, this is an unvisited intra-loop node. Check all successors.
301 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
302 // Check to see if the successor is a trivial loop exit.
303 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
307 // Okay, everything after this looks good, check to make sure that this block
308 // doesn't include any side effects.
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310 if (I->mayWriteToMemory())
316 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
317 /// leads to an exit from the specified loop, and has no side-effects in the
318 /// process. If so, return the block that is exited to, otherwise return null.
319 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
320 std::set<BasicBlock*> Visited;
321 Visited.insert(L->getHeader()); // Branches to header are ok.
322 BasicBlock *ExitBB = 0;
323 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
328 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
329 /// trivial: that is, that the condition controls whether or not the loop does
330 /// anything at all. If this is a trivial condition, unswitching produces no
331 /// code duplications (equivalently, it produces a simpler loop and a new empty
332 /// loop, which gets deleted).
334 /// If this is a trivial condition, return true, otherwise return false. When
335 /// returning true, this sets Cond and Val to the condition that controls the
336 /// trivial condition: when Cond dynamically equals Val, the loop is known to
337 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
340 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
341 BasicBlock **LoopExit) {
342 BasicBlock *Header = currentLoop->getHeader();
343 TerminatorInst *HeaderTerm = Header->getTerminator();
345 BasicBlock *LoopExitBB = 0;
346 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
347 // If the header block doesn't end with a conditional branch on Cond, we
349 if (!BI->isConditional() || BI->getCondition() != Cond)
352 // Check to see if a successor of the branch is guaranteed to go to the
353 // latch block or exit through a one exit block without having any
354 // side-effects. If so, determine the value of Cond that causes it to do
356 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
357 BI->getSuccessor(0)))) {
358 if (Val) *Val = ConstantInt::getTrue();
359 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
360 BI->getSuccessor(1)))) {
361 if (Val) *Val = ConstantInt::getFalse();
363 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
364 // If this isn't a switch on Cond, we can't handle it.
365 if (SI->getCondition() != Cond) return false;
367 // Check to see if a successor of the switch is guaranteed to go to the
368 // latch block or exit through a one exit block without having any
369 // side-effects. If so, determine the value of Cond that causes it to do
370 // this. Note that we can't trivially unswitch on the default case.
371 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
372 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
373 SI->getSuccessor(i)))) {
374 // Okay, we found a trivial case, remember the value that is trivial.
375 if (Val) *Val = SI->getCaseValue(i);
380 // If we didn't find a single unique LoopExit block, or if the loop exit block
381 // contains phi nodes, this isn't trivial.
382 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
383 return false; // Can't handle this.
385 if (LoopExit) *LoopExit = LoopExitBB;
387 // We already know that nothing uses any scalar values defined inside of this
388 // loop. As such, we just have to check to see if this loop will execute any
389 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
390 // part of the loop that the code *would* execute. We already checked the
391 // tail, check the header now.
392 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
393 if (I->mayWriteToMemory())
398 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
399 /// we choose to unswitch current loop on the specified value.
401 unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
402 // If the condition is trivial, always unswitch. There is no code growth for
404 if (IsTrivialUnswitchCondition(LIC))
407 // FIXME: This is really overly conservative. However, more liberal
408 // estimations have thus far resulted in excessive unswitching, which is bad
409 // both in compile time and in code size. This should be replaced once
410 // someone figures out how a good estimation.
411 return currentLoop->getBlocks().size();
414 // FIXME: this is brain dead. It should take into consideration code
416 for (Loop::block_iterator I = currentLoop->block_begin(),
417 E = currentLoop->block_end();
420 // Do not include empty blocks in the cost calculation. This happen due to
421 // loop canonicalization and will be removed.
422 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
425 // Count basic blocks.
432 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
433 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
434 /// unswitch the loop, reprocess the pieces, then return true.
435 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
436 // Check to see if it would be profitable to unswitch current loop.
437 unsigned Cost = getLoopUnswitchCost(LoopCond);
439 // Do not do non-trivial unswitch while optimizing for size.
440 if (Cost && OptimizeForSize)
443 if (Cost > Threshold) {
444 // FIXME: this should estimate growth by the amount of code shared by the
445 // resultant unswitched loops.
447 DOUT << "NOT unswitching loop %"
448 << currentLoop->getHeader()->getName() << ", cost too high: "
449 << currentLoop->getBlocks().size() << "\n";
456 BasicBlock *ExitBlock;
457 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
458 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
460 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
466 // RemapInstruction - Convert the instruction operands from referencing the
467 // current values into those specified by ValueMap.
469 static inline void RemapInstruction(Instruction *I,
470 DenseMap<const Value *, Value*> &ValueMap) {
471 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
472 Value *Op = I->getOperand(op);
473 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
474 if (It != ValueMap.end()) Op = It->second;
475 I->setOperand(op, Op);
479 // CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
482 // If Orig block's immediate dominator is mapped in VM then use corresponding
483 // immediate dominator from the map. Otherwise Orig block's dominator is also
484 // NewBB's dominator.
486 // OrigPreheader is loop pre-header before this pass started
487 // updating CFG. NewPrehader is loops new pre-header. However, after CFG
488 // manipulation, loop L may not exist. So rely on input parameter NewPreheader.
489 static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
490 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
491 BasicBlock *OrigHeader,
492 DominatorTree *DT, DominanceFrontier *DF,
493 DenseMap<const Value*, Value*> &VM) {
495 // If NewBB alreay has found its place in domiantor tree then no need to do
497 if (DT->getNode(NewBB))
500 // If Orig does not have any immediate domiantor then its clone, NewBB, does
501 // not need any immediate dominator.
502 DomTreeNode *OrigNode = DT->getNode(Orig);
505 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
509 BasicBlock *OrigIDom = NULL;
511 // If Orig is original loop header then its immediate dominator is
513 if (Orig == OrigHeader)
514 OrigIDom = NewPreheader;
516 // If Orig is new pre-header then its immediate dominator is
517 // original pre-header.
518 else if (Orig == NewPreheader)
519 OrigIDom = OrigPreheader;
521 // Otherwise ask DT to find Orig's immediate dominator.
523 OrigIDom = OrigIDomNode->getBlock();
525 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
526 BasicBlock *NewIDom = OrigIDom;
527 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
529 NewIDom = cast<BasicBlock>(I->second);
531 // If NewIDom does not have corresponding dominatore tree node then
533 if (!DT->getNode(NewIDom))
534 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
535 OrigHeader, DT, DF, VM);
538 DT->addNewBlock(NewBB, NewIDom);
540 // Copy cloned dominance frontiner set
541 DominanceFrontier::DomSetType NewDFSet;
543 DominanceFrontier::iterator DFI = DF->find(Orig);
544 if ( DFI != DF->end()) {
545 DominanceFrontier::DomSetType S = DFI->second;
546 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
549 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
551 NewDFSet.insert(cast<BasicBlock>(IDM->second));
556 DF->addBasicBlock(NewBB, NewDFSet);
560 /// CloneLoop - Recursively clone the specified loop and all of its children,
561 /// mapping the blocks with the specified map.
562 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
563 LoopInfo *LI, LPPassManager *LPM) {
564 Loop *New = new Loop();
566 LPM->insertLoop(New, PL);
568 // Add all of the blocks in L to the new loop.
569 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
571 if (LI->getLoopFor(*I) == L)
572 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
574 // Add all of the subloops to the new loop.
575 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
576 CloneLoop(*I, New, VM, LI, LPM);
581 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
582 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
583 /// code immediately before InsertPt.
584 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
585 BasicBlock *TrueDest,
586 BasicBlock *FalseDest,
587 Instruction *InsertPt) {
588 // Insert a conditional branch on LIC to the two preheaders. The original
589 // code is the true version and the new code is the false version.
590 Value *BranchVal = LIC;
591 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
592 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
593 else if (Val != ConstantInt::getTrue())
594 // We want to enter the new loop when the condition is true.
595 std::swap(TrueDest, FalseDest);
597 // Insert the new branch.
598 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
602 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
603 /// condition in it (a cond branch from its header block to its latch block,
604 /// where the path through the loop that doesn't execute its body has no
605 /// side-effects), unswitch it. This doesn't involve any code duplication, just
606 /// moving the conditional branch outside of the loop and updating loop info.
607 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
609 BasicBlock *ExitBlock) {
610 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
611 << loopHeader->getName() << " [" << L->getBlocks().size()
612 << " blocks] in Function " << L->getHeader()->getParent()->getName()
613 << " on cond: " << *Val << " == " << *Cond << "\n";
615 // First step, split the preheader, so that we know that there is a safe place
616 // to insert the conditional branch. We will change loopPreheader to have a
617 // conditional branch on Cond.
618 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
620 // Now that we have a place to insert the conditional branch, create a place
621 // to branch to: this is the exit block out of the loop that we should
624 // Split this block now, so that the loop maintains its exit block, and so
625 // that the jump from the preheader can execute the contents of the exit block
626 // without actually branching to it (the exit block should be dominated by the
627 // loop header, not the preheader).
628 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
629 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
631 // Okay, now we have a position to branch from and a position to branch to,
632 // insert the new conditional branch.
633 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
634 loopPreheader->getTerminator());
636 DT->changeImmediateDominator(NewExit, loopPreheader);
637 DT->changeImmediateDominator(NewPH, loopPreheader);
641 // NewExit is now part of NewPH and Loop Header's dominance
643 DominanceFrontier::iterator DFI = DF->find(NewPH);
644 if (DFI != DF->end())
645 DF->addToFrontier(DFI, NewExit);
646 DFI = DF->find(loopHeader);
647 DF->addToFrontier(DFI, NewExit);
649 // ExitBlock does not have successors then NewExit is part of
650 // its dominance frontier.
651 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
652 DFI = DF->find(ExitBlock);
653 DF->addToFrontier(DFI, NewExit);
656 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
657 loopPreheader->getTerminator()->eraseFromParent();
659 // We need to reprocess this loop, it could be unswitched again.
662 // Now that we know that the loop is never entered when this condition is a
663 // particular value, rewrite the loop with this info. We know that this will
664 // at least eliminate the old branch.
665 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
669 /// ReplaceLoopExternalDFMember -
670 /// If BB's dominance frontier has a member that is not part of loop L then
671 /// remove it. Add NewDFMember in BB's dominance frontier.
672 void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
673 BasicBlock *NewDFMember) {
675 DominanceFrontier::iterator DFI = DF->find(BB);
676 if (DFI == DF->end())
679 DominanceFrontier::DomSetType &DFSet = DFI->second;
680 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
681 DE = DFSet.end(); DI != DE;) {
682 BasicBlock *B = *DI++;
686 DF->removeFromFrontier(DFI, B);
690 DF->addToFrontier(DFI, NewDFMember);
693 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
694 /// blocks. Update the appropriate Phi nodes as we do so.
695 void LoopUnswitch::SplitExitEdges(Loop *L,
696 const SmallVector<BasicBlock *, 8> &ExitBlocks,
697 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
699 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
700 BasicBlock *ExitBlock = ExitBlocks[i];
701 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
703 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
704 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
705 MiddleBlocks.push_back(MiddleBlock);
706 BasicBlock* StartBlock = Preds[j];
707 BasicBlock* EndBlock;
708 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
709 EndBlock = MiddleBlock;
710 MiddleBlock = EndBlock->getSinglePredecessor();;
712 EndBlock = ExitBlock;
715 OrigLoopExitMap[StartBlock] = EndBlock;
717 std::set<PHINode*> InsertedPHIs;
718 PHINode* OldLCSSA = 0;
719 for (BasicBlock::iterator I = EndBlock->begin();
720 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
721 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
722 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
723 OldLCSSA->getName() + ".us-lcssa",
724 MiddleBlock->getTerminator());
725 NewLCSSA->addIncoming(OldValue, StartBlock);
726 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
728 InsertedPHIs.insert(NewLCSSA);
731 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
732 for (BasicBlock::iterator I = MiddleBlock->begin();
733 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
735 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
736 OldLCSSA->getName() + ".us-lcssa",
738 OldLCSSA->replaceAllUsesWith(NewLCSSA);
739 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
743 // StartBlock -- > MiddleBlock -- > EndBlock
744 // StartBlock is loop exiting block. EndBlock will become merge point
745 // of two loop exits after loop unswitch.
747 // If StartBlock's DF member includes a block that is not loop member
748 // then replace that DF member with EndBlock.
750 // If MiddleBlock's DF member includes a block that is not loop member
751 // tnen replace that DF member with EndBlock.
753 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
754 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
761 /// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
762 /// dominance frontier using iterator DFI.
763 static void addBBToDomFrontier(DominanceFrontier &DF,
764 DominanceFrontier::iterator &DFI,
765 BasicBlock *BB, BasicBlock *DFBB) {
766 if (DFI != DF.end()) {
767 DF.addToFrontier(DFI, DFBB);
771 DominanceFrontier::DomSetType NSet;
773 DF.addBasicBlock(BB, NSet);
777 /// UnswitchNontrivialCondition - We determined that the loop is profitable
778 /// to unswitch when LIC equal Val. Split it into loop versions and test the
779 /// condition outside of either loop. Return the loops created as Out1/Out2.
780 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
782 Function *F = loopHeader->getParent();
783 DOUT << "loop-unswitch: Unswitching loop %"
784 << loopHeader->getName() << " [" << L->getBlocks().size()
785 << " blocks] in Function " << F->getName()
786 << " when '" << *Val << "' == " << *LIC << "\n";
791 // First step, split the preheader and exit blocks, and add these blocks to
792 // the LoopBlocks list.
793 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
794 LoopBlocks.push_back(NewPreheader);
796 // We want the loop to come after the preheader, but before the exit blocks.
797 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
799 SmallVector<BasicBlock*, 8> ExitBlocks;
800 L->getUniqueExitBlocks(ExitBlocks);
802 // Split all of the edges from inside the loop to their exit blocks. Update
803 // the appropriate Phi nodes as we do so.
804 SmallVector<BasicBlock *,8> MiddleBlocks;
805 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
807 // The exit blocks may have been changed due to edge splitting, recompute.
809 L->getUniqueExitBlocks(ExitBlocks);
811 // Add exit blocks to the loop blocks.
812 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
814 // Next step, clone all of the basic blocks that make up the loop (including
815 // the loop preheader and exit blocks), keeping track of the mapping between
816 // the instructions and blocks.
817 NewBlocks.reserve(LoopBlocks.size());
818 DenseMap<const Value*, Value*> ValueMap;
819 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
820 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
821 NewBlocks.push_back(New);
822 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
823 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
826 // OutSiders are basic block that are dominated by original header and
827 // at the same time they are not part of loop.
828 SmallPtrSet<BasicBlock *, 8> OutSiders;
830 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
831 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
832 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
833 BasicBlock *B = (*DI)->getBlock();
835 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
836 if (VI == ValueMap.end())
841 // Splice the newly inserted blocks into the function right before the
842 // original preheader.
843 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
844 NewBlocks[0], F->end());
846 // Now we create the new Loop object for the versioned loop.
847 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
848 Loop *ParentLoop = L->getParentLoop();
850 // Make sure to add the cloned preheader and exit blocks to the parent loop
852 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
855 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
856 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
857 // The new exit block should be in the same loop as the old one.
858 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
859 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
861 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
862 "Exit block should have been split to have one successor!");
863 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
865 // If the successor of the exit block had PHI nodes, add an entry for
868 for (BasicBlock::iterator I = ExitSucc->begin();
869 (PN = dyn_cast<PHINode>(I)); ++I) {
870 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
871 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
872 if (It != ValueMap.end()) V = It->second;
873 PN->addIncoming(V, NewExit);
877 // Rewrite the code to refer to itself.
878 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
879 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
880 E = NewBlocks[i]->end(); I != E; ++I)
881 RemapInstruction(I, ValueMap);
883 // Rewrite the original preheader to select between versions of the loop.
884 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
885 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
886 "Preheader splitting did not work correctly!");
888 // Emit the new branch that selects between the two versions of this loop.
889 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
890 LPM->deleteSimpleAnalysisValue(OldBR, L);
891 OldBR->eraseFromParent();
893 // Update dominator info
896 SmallVector<BasicBlock *,4> ExitingBlocks;
897 L->getExitingBlocks(ExitingBlocks);
899 // Clone dominator info for all cloned basic block.
900 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
901 BasicBlock *LBB = LoopBlocks[i];
902 BasicBlock *NBB = NewBlocks[i];
903 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
904 loopHeader, DT, DF, ValueMap);
906 // If LBB's dominance frontier includes DFMember
907 // such that DFMember is also a member of LoopDF then
908 // - Remove DFMember from LBB's dominance frontier
909 // - Copy loop exiting blocks', that are dominated by BB,
910 // dominance frontier member in BB's dominance frontier
912 DominanceFrontier::iterator LBBI = DF->find(LBB);
913 DominanceFrontier::iterator NBBI = DF->find(NBB);
914 if (LBBI == DF->end())
917 DominanceFrontier::DomSetType &LBSet = LBBI->second;
918 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
919 LE = LBSet.end(); LI != LE; /* NULL */) {
920 BasicBlock *B = *LI++;
921 if (B == LBB && B == loopHeader)
923 bool removeB = false;
924 if (!LoopDF.count(B))
927 // If LBB dominates loop exits then insert loop exit block's DF
929 for(SmallVector<BasicBlock *, 4>::iterator
930 LExitI = ExitingBlocks.begin(),
931 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
932 BasicBlock *E = *LExitI;
934 if (!DT->dominates(LBB,E))
937 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
938 OrigLoopExitMap.find(E);
939 if (DFBI == OrigLoopExitMap.end())
942 BasicBlock *DFB = DFBI->second;
943 DF->addToFrontier(LBBI, DFB);
944 DF->addToFrontier(NBBI, DFB);
948 // If B's replacement is inserted in DF then now is the time to remove
951 DF->removeFromFrontier(LBBI, B);
953 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
955 DF->removeFromFrontier(NBBI, B);
961 // MiddleBlocks are dominated by original pre header. SplitEdge updated
962 // MiddleBlocks' dominance frontier appropriately.
963 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
964 BasicBlock *MBB = MiddleBlocks[i];
965 if (!MBB->getSinglePredecessor())
966 DT->changeImmediateDominator(MBB, loopPreheader);
969 // All Outsiders are now dominated by original pre header.
970 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
971 OE = OutSiders.end(); OI != OE; ++OI) {
972 BasicBlock *OB = *OI;
973 DT->changeImmediateDominator(OB, loopPreheader);
976 // New loop headers are dominated by original preheader
977 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
978 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
981 LoopProcessWorklist.push_back(NewLoop);
984 // Now we rewrite the original code to know that the condition is true and the
985 // new code to know that the condition is false.
986 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
988 // It's possible that simplifying one loop could cause the other to be
989 // deleted. If so, don't simplify it.
990 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
991 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
994 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
996 static void RemoveFromWorklist(Instruction *I,
997 std::vector<Instruction*> &Worklist) {
998 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
1000 while (WI != Worklist.end()) {
1001 unsigned Offset = WI-Worklist.begin();
1003 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1007 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1008 /// program, replacing all uses with V and update the worklist.
1009 static void ReplaceUsesOfWith(Instruction *I, Value *V,
1010 std::vector<Instruction*> &Worklist,
1011 Loop *L, LPPassManager *LPM) {
1012 DOUT << "Replace with '" << *V << "': " << *I;
1014 // Add uses to the worklist, which may be dead now.
1015 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1016 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1017 Worklist.push_back(Use);
1019 // Add users to the worklist which may be simplified now.
1020 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1022 Worklist.push_back(cast<Instruction>(*UI));
1023 LPM->deleteSimpleAnalysisValue(I, L);
1024 RemoveFromWorklist(I, Worklist);
1025 I->replaceAllUsesWith(V);
1026 I->eraseFromParent();
1030 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1031 /// information, and remove any dead successors it has.
1033 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
1034 std::vector<Instruction*> &Worklist,
1036 if (pred_begin(BB) != pred_end(BB)) {
1037 // This block isn't dead, since an edge to BB was just removed, see if there
1038 // are any easy simplifications we can do now.
1039 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1040 // If it has one pred, fold phi nodes in BB.
1041 while (isa<PHINode>(BB->begin()))
1042 ReplaceUsesOfWith(BB->begin(),
1043 cast<PHINode>(BB->begin())->getIncomingValue(0),
1046 // If this is the header of a loop and the only pred is the latch, we now
1047 // have an unreachable loop.
1048 if (Loop *L = LI->getLoopFor(BB))
1049 if (loopHeader == BB && L->contains(Pred)) {
1050 // Remove the branch from the latch to the header block, this makes
1051 // the header dead, which will make the latch dead (because the header
1052 // dominates the latch).
1053 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
1054 Pred->getTerminator()->eraseFromParent();
1055 new UnreachableInst(Pred);
1057 // The loop is now broken, remove it from LI.
1058 RemoveLoopFromHierarchy(L);
1060 // Reprocess the header, which now IS dead.
1061 RemoveBlockIfDead(BB, Worklist, L);
1065 // If pred ends in a uncond branch, add uncond branch to worklist so that
1066 // the two blocks will get merged.
1067 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1068 if (BI->isUnconditional())
1069 Worklist.push_back(BI);
1074 DOUT << "Nuking dead block: " << *BB;
1076 // Remove the instructions in the basic block from the worklist.
1077 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1078 RemoveFromWorklist(I, Worklist);
1080 // Anything that uses the instructions in this basic block should have their
1081 // uses replaced with undefs.
1082 if (!I->use_empty())
1083 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1086 // If this is the edge to the header block for a loop, remove the loop and
1087 // promote all subloops.
1088 if (Loop *BBLoop = LI->getLoopFor(BB)) {
1089 if (BBLoop->getLoopLatch() == BB)
1090 RemoveLoopFromHierarchy(BBLoop);
1093 // Remove the block from the loop info, which removes it from any loops it
1095 LI->removeBlock(BB);
1098 // Remove phi node entries in successors for this block.
1099 TerminatorInst *TI = BB->getTerminator();
1100 std::vector<BasicBlock*> Succs;
1101 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1102 Succs.push_back(TI->getSuccessor(i));
1103 TI->getSuccessor(i)->removePredecessor(BB);
1106 // Unique the successors, remove anything with multiple uses.
1107 std::sort(Succs.begin(), Succs.end());
1108 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1110 // Remove the basic block, including all of the instructions contained in it.
1111 LPM->deleteSimpleAnalysisValue(BB, L);
1112 BB->eraseFromParent();
1113 // Remove successor blocks here that are not dead, so that we know we only
1114 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1115 // then getting removed before we revisit them, which is badness.
1117 for (unsigned i = 0; i != Succs.size(); ++i)
1118 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1119 // One exception is loop headers. If this block was the preheader for a
1120 // loop, then we DO want to visit the loop so the loop gets deleted.
1121 // We know that if the successor is a loop header, that this loop had to
1122 // be the preheader: the case where this was the latch block was handled
1123 // above and headers can only have two predecessors.
1124 if (!LI->isLoopHeader(Succs[i])) {
1125 Succs.erase(Succs.begin()+i);
1130 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
1131 RemoveBlockIfDead(Succs[i], Worklist, L);
1134 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1135 /// become unwrapped, either because the backedge was deleted, or because the
1136 /// edge into the header was removed. If the edge into the header from the
1137 /// latch block was removed, the loop is unwrapped but subloops are still alive,
1138 /// so they just reparent loops. If the loops are actually dead, they will be
1140 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
1141 LPM->deleteLoopFromQueue(L);
1142 RemoveLoopFromWorklist(L);
1147 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1148 // the value specified by Val in the specified loop, or we know it does NOT have
1149 // that value. Rewrite any uses of LIC or of properties correlated to it.
1150 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1153 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1155 // FIXME: Support correlated properties, like:
1162 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1163 // selects, switches.
1164 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1165 std::vector<Instruction*> Worklist;
1167 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1168 // in the loop with the appropriate one directly.
1169 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1174 Replacement = ConstantInt::get(Type::Int1Ty,
1175 !cast<ConstantInt>(Val)->getZExtValue());
1177 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1178 if (Instruction *U = cast<Instruction>(Users[i])) {
1179 if (!L->contains(U->getParent()))
1181 U->replaceUsesOfWith(LIC, Replacement);
1182 Worklist.push_back(U);
1185 // Otherwise, we don't know the precise value of LIC, but we do know that it
1186 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1187 // can. This case occurs when we unswitch switch statements.
1188 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1189 if (Instruction *U = cast<Instruction>(Users[i])) {
1190 if (!L->contains(U->getParent()))
1193 Worklist.push_back(U);
1195 // If we know that LIC is not Val, use this info to simplify code.
1196 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1197 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1198 if (SI->getCaseValue(i) == Val) {
1199 // Found a dead case value. Don't remove PHI nodes in the
1200 // successor if they become single-entry, those PHI nodes may
1201 // be in the Users list.
1203 // FIXME: This is a hack. We need to keep the successor around
1204 // and hooked up so as to preserve the loop structure, because
1205 // trying to update it is complicated. So instead we preserve the
1206 // loop structure and put the block on an dead code path.
1208 BasicBlock* Old = SI->getParent();
1209 BasicBlock* Split = SplitBlock(Old, SI, this);
1211 Instruction* OldTerm = Old->getTerminator();
1212 BranchInst::Create(Split, SI->getSuccessor(i),
1213 ConstantInt::getTrue(), OldTerm);
1215 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
1216 Old->getTerminator()->eraseFromParent();
1219 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1220 (PN = dyn_cast<PHINode>(II)); ++II) {
1221 Value *InVal = PN->removeIncomingValue(Split, false);
1222 PN->addIncoming(InVal, Old);
1231 // TODO: We could do other simplifications, for example, turning
1232 // LIC == Val -> false.
1236 SimplifyCode(Worklist, L);
1239 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1240 /// loop, walk over it and constant prop, dce, and fold control flow where
1241 /// possible. Note that this is effectively a very simple loop-structure-aware
1242 /// optimizer. During processing of this loop, L could very well be deleted, so
1243 /// it must not be used.
1245 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1248 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1249 while (!Worklist.empty()) {
1250 Instruction *I = Worklist.back();
1251 Worklist.pop_back();
1253 // Simple constant folding.
1254 if (Constant *C = ConstantFoldInstruction(I)) {
1255 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
1260 if (isInstructionTriviallyDead(I)) {
1261 DOUT << "Remove dead instruction '" << *I;
1263 // Add uses to the worklist, which may be dead now.
1264 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1265 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1266 Worklist.push_back(Use);
1267 LPM->deleteSimpleAnalysisValue(I, L);
1268 RemoveFromWorklist(I, Worklist);
1269 I->eraseFromParent();
1274 // Special case hacks that appear commonly in unswitched code.
1275 switch (I->getOpcode()) {
1276 case Instruction::Select:
1277 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1278 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1283 case Instruction::And:
1284 if (isa<ConstantInt>(I->getOperand(0)) &&
1285 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1286 cast<BinaryOperator>(I)->swapOperands();
1287 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1288 if (CB->getType() == Type::Int1Ty) {
1289 if (CB->isOne()) // X & 1 -> X
1290 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1292 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1296 case Instruction::Or:
1297 if (isa<ConstantInt>(I->getOperand(0)) &&
1298 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1299 cast<BinaryOperator>(I)->swapOperands();
1300 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1301 if (CB->getType() == Type::Int1Ty) {
1302 if (CB->isOne()) // X | 1 -> 1
1303 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1305 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1309 case Instruction::Br: {
1310 BranchInst *BI = cast<BranchInst>(I);
1311 if (BI->isUnconditional()) {
1312 // If BI's parent is the only pred of the successor, fold the two blocks
1314 BasicBlock *Pred = BI->getParent();
1315 BasicBlock *Succ = BI->getSuccessor(0);
1316 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1317 if (!SinglePred) continue; // Nothing to do.
1318 assert(SinglePred == Pred && "CFG broken");
1320 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1321 << Succ->getName() << "\n";
1323 // Resolve any single entry PHI nodes in Succ.
1324 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1325 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1327 // Move all of the successor contents from Succ to Pred.
1328 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1330 LPM->deleteSimpleAnalysisValue(BI, L);
1331 BI->eraseFromParent();
1332 RemoveFromWorklist(BI, Worklist);
1334 // If Succ has any successors with PHI nodes, update them to have
1335 // entries coming from Pred instead of Succ.
1336 Succ->replaceAllUsesWith(Pred);
1338 // Remove Succ from the loop tree.
1339 LI->removeBlock(Succ);
1340 LPM->deleteSimpleAnalysisValue(Succ, L);
1341 Succ->eraseFromParent();
1343 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1344 // Conditional branch. Turn it into an unconditional branch, then
1345 // remove dead blocks.
1346 break; // FIXME: Enable.
1348 DOUT << "Folded branch: " << *BI;
1349 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1350 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1351 DeadSucc->removePredecessor(BI->getParent(), true);
1352 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1353 LPM->deleteSimpleAnalysisValue(BI, L);
1354 BI->eraseFromParent();
1355 RemoveFromWorklist(BI, Worklist);
1358 RemoveBlockIfDead(DeadSucc, Worklist, L);