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/InlineCost.h"
36 #include "llvm/Analysis/InstructionSimplify.h"
37 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/LoopPass.h"
39 #include "llvm/Analysis/Dominators.h"
40 #include "llvm/Analysis/ScalarEvolution.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
54 STATISTIC(NumBranches, "Number of branches unswitched");
55 STATISTIC(NumSwitches, "Number of switches unswitched");
56 STATISTIC(NumSelects , "Number of selects unswitched");
57 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
58 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
60 // The specific value of 50 here was chosen based only on intuition and a
61 // few specific examples.
62 static cl::opt<unsigned>
63 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
64 cl::init(50), cl::Hidden);
67 class LoopUnswitch : public LoopPass {
68 LoopInfo *LI; // Loop information
71 // LoopProcessWorklist - Used to check if second loop needs processing
72 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
73 std::vector<Loop*> LoopProcessWorklist;
75 // FIXME: Consider custom class for this.
76 std::map<const SwitchInst*, SmallPtrSet<const Value *,8> > UnswitchedVals;
83 BasicBlock *loopHeader;
84 BasicBlock *loopPreheader;
86 // LoopBlocks contains all of the basic blocks of the loop, including the
87 // preheader of the loop, the body of the loop, and the exit blocks of the
88 // loop, in that order.
89 std::vector<BasicBlock*> LoopBlocks;
90 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
91 std::vector<BasicBlock*> NewBlocks;
94 static char ID; // Pass ID, replacement for typeid
95 explicit LoopUnswitch(bool Os = false) :
96 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
97 currentLoop(NULL), DT(NULL), loopHeader(NULL),
99 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
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 AU.addPreserved<DominatorTree>();
116 AU.addPreserved<ScalarEvolution>();
121 virtual void releaseMemory() {
122 // We need to forget about all switches in the current loop.
123 // FIXME: Do it better than enumerating all blocks of code
124 // and see if it is a switch instruction.
125 for (Loop::block_iterator I = currentLoop->block_begin(),
126 E = currentLoop->block_end(); I != E; ++I) {
127 SwitchInst* SI = dyn_cast<SwitchInst>((*I)->getTerminator());
129 UnswitchedVals.erase(SI);
133 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
135 void RemoveLoopFromWorklist(Loop *L) {
136 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
137 LoopProcessWorklist.end(), L);
138 if (I != LoopProcessWorklist.end())
139 LoopProcessWorklist.erase(I);
142 /// For new loop switches we clone info about values that was
143 /// already unswitched and has redundant successors.
144 /// Note, that new loop data is stored inside the VMap.
145 void CloneUnswitchedVals(const ValueToValueMapTy& VMap,
146 const BasicBlock* SrcBB);
148 void initLoopData() {
149 loopHeader = currentLoop->getHeader();
150 loopPreheader = currentLoop->getLoopPreheader();
153 /// Split all of the edges from inside the loop to their exit blocks.
154 /// Update the appropriate Phi nodes as we do so.
155 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
157 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
158 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
159 BasicBlock *ExitBlock);
160 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
162 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
163 Constant *Val, bool isEqual);
165 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
166 BasicBlock *TrueDest,
167 BasicBlock *FalseDest,
168 Instruction *InsertPt);
170 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
171 void RemoveBlockIfDead(BasicBlock *BB,
172 std::vector<Instruction*> &Worklist, Loop *l);
173 void RemoveLoopFromHierarchy(Loop *L);
174 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
175 BasicBlock **LoopExit = 0);
179 char LoopUnswitch::ID = 0;
180 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
182 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
183 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
184 INITIALIZE_PASS_DEPENDENCY(LCSSA)
185 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
188 Pass *llvm::createLoopUnswitchPass(bool Os) {
189 return new LoopUnswitch(Os);
192 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
193 /// invariant in the loop, or has an invariant piece, return the invariant.
194 /// Otherwise, return null.
195 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
196 // We can never unswitch on vector conditions.
197 if (Cond->getType()->isVectorTy())
200 // Constants should be folded, not unswitched on!
201 if (isa<Constant>(Cond)) return 0;
203 // TODO: Handle: br (VARIANT|INVARIANT).
205 // Hoist simple values out.
206 if (L->makeLoopInvariant(Cond, Changed))
209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
210 if (BO->getOpcode() == Instruction::And ||
211 BO->getOpcode() == Instruction::Or) {
212 // If either the left or right side is invariant, we can unswitch on this,
213 // which will cause the branch to go away in one loop and the condition to
214 // simplify in the other one.
215 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
217 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
224 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
225 LI = &getAnalysis<LoopInfo>();
227 DT = getAnalysisIfAvailable<DominatorTree>();
229 Function *F = currentLoop->getHeader()->getParent();
230 bool Changed = false;
232 assert(currentLoop->isLCSSAForm(*DT));
234 Changed |= processCurrentLoop();
238 // FIXME: Reconstruct dom info, because it is not preserved properly.
240 DT->runOnFunction(*F);
245 /// processCurrentLoop - Do actual work and unswitch loop if possible
247 bool LoopUnswitch::processCurrentLoop() {
248 bool Changed = false;
249 LLVMContext &Context = currentLoop->getHeader()->getContext();
251 // Loop over all of the basic blocks in the loop. If we find an interior
252 // block that is branching on a loop-invariant condition, we can unswitch this
254 for (Loop::block_iterator I = currentLoop->block_begin(),
255 E = currentLoop->block_end(); I != E; ++I) {
256 TerminatorInst *TI = (*I)->getTerminator();
257 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
258 // If this isn't branching on an invariant condition, we can't unswitch
260 if (BI->isConditional()) {
261 // See if this, or some part of it, is loop invariant. If so, we can
262 // unswitch on it if we desire.
263 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
264 currentLoop, Changed);
265 if (LoopCond && UnswitchIfProfitable(LoopCond,
266 ConstantInt::getTrue(Context))) {
271 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
272 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
273 currentLoop, Changed);
274 unsigned NumCases = SI->getNumCases();
275 if (LoopCond && NumCases > 1) {
276 // Find a value to unswitch on:
277 // FIXME: this should chose the most expensive case!
278 // FIXME: scan for a case with a non-critical edge?
279 Constant *UnswitchVal = NULL;
281 // Do not process same value again and again.
282 // At this point we have some cases already unswitched and
283 // some not yet unswitched. Let's find the first not yet unswitched one.
284 for (unsigned i = 1; i < NumCases; ++i) {
285 Constant* UnswitchValCandidate = SI->getCaseValue(i);
286 if (!UnswitchedVals[SI].count(UnswitchValCandidate)) {
287 UnswitchVal = UnswitchValCandidate;
295 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
302 // Scan the instructions to check for unswitchable values.
303 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
305 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
306 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
307 currentLoop, Changed);
308 if (LoopCond && UnswitchIfProfitable(LoopCond,
309 ConstantInt::getTrue(Context))) {
318 /// For new loop switches we clone info about values that was
319 /// already unswitched and has redundant successors.
320 /// Not that new loop data is stored inside the VMap.
321 void LoopUnswitch::CloneUnswitchedVals(const ValueToValueMapTy& VMap,
322 const BasicBlock* SrcBB) {
324 const SwitchInst* SI = dyn_cast<SwitchInst>(SrcBB->getTerminator());
325 if (SI && UnswitchedVals.count(SI)) {
326 // Don't clone a totally simplified switch.
327 if (isa<Constant>(SI->getCondition()))
329 Value* I = VMap.lookup(SI);
330 assert(I && "All instructions that are in SrcBB must be in VMap.");
331 UnswitchedVals[cast<SwitchInst>(I)] = UnswitchedVals[SI];
335 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
336 /// loop with no side effects (including infinite loops).
338 /// If true, we return true and set ExitBB to the block we
341 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
343 std::set<BasicBlock*> &Visited) {
344 if (!Visited.insert(BB).second) {
345 // Already visited. Without more analysis, this could indicate an infinite
348 } else if (!L->contains(BB)) {
349 // Otherwise, this is a loop exit, this is fine so long as this is the
351 if (ExitBB != 0) return false;
356 // Otherwise, this is an unvisited intra-loop node. Check all successors.
357 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
358 // Check to see if the successor is a trivial loop exit.
359 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
363 // Okay, everything after this looks good, check to make sure that this block
364 // doesn't include any side effects.
365 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
366 if (I->mayHaveSideEffects())
372 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
373 /// leads to an exit from the specified loop, and has no side-effects in the
374 /// process. If so, return the block that is exited to, otherwise return null.
375 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
376 std::set<BasicBlock*> Visited;
377 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
378 BasicBlock *ExitBB = 0;
379 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
384 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
385 /// trivial: that is, that the condition controls whether or not the loop does
386 /// anything at all. If this is a trivial condition, unswitching produces no
387 /// code duplications (equivalently, it produces a simpler loop and a new empty
388 /// loop, which gets deleted).
390 /// If this is a trivial condition, return true, otherwise return false. When
391 /// returning true, this sets Cond and Val to the condition that controls the
392 /// trivial condition: when Cond dynamically equals Val, the loop is known to
393 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
396 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
397 BasicBlock **LoopExit) {
398 BasicBlock *Header = currentLoop->getHeader();
399 TerminatorInst *HeaderTerm = Header->getTerminator();
400 LLVMContext &Context = Header->getContext();
402 BasicBlock *LoopExitBB = 0;
403 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
404 // If the header block doesn't end with a conditional branch on Cond, we
406 if (!BI->isConditional() || BI->getCondition() != Cond)
409 // Check to see if a successor of the branch is guaranteed to
410 // exit through a unique exit block without having any
411 // side-effects. If so, determine the value of Cond that causes it to do
413 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
414 BI->getSuccessor(0)))) {
415 if (Val) *Val = ConstantInt::getTrue(Context);
416 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
417 BI->getSuccessor(1)))) {
418 if (Val) *Val = ConstantInt::getFalse(Context);
420 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
421 // If this isn't a switch on Cond, we can't handle it.
422 if (SI->getCondition() != Cond) return false;
424 // Check to see if a successor of the switch is guaranteed to go to the
425 // latch block or exit through a one exit block without having any
426 // side-effects. If so, determine the value of Cond that causes it to do
428 // Note that we can't trivially unswitch on the default case or
429 // on already unswitched cases.
430 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
431 BasicBlock* LoopExitCandidate;
432 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
433 SI->getSuccessor(i)))) {
434 // Okay, we found a trivial case, remember the value that is trivial.
435 ConstantInt* CaseVal = SI->getCaseValue(i);
437 // Check that it was not unswitched before, since already unswitched
438 // trivial vals are looks trivial too.
439 if (UnswitchedVals[SI].count(CaseVal))
441 LoopExitBB = LoopExitCandidate;
442 if (Val) *Val = CaseVal;
448 // If we didn't find a single unique LoopExit block, or if the loop exit block
449 // contains phi nodes, this isn't trivial.
450 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
451 return false; // Can't handle this.
453 if (LoopExit) *LoopExit = LoopExitBB;
455 // We already know that nothing uses any scalar values defined inside of this
456 // loop. As such, we just have to check to see if this loop will execute any
457 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
458 // part of the loop that the code *would* execute. We already checked the
459 // tail, check the header now.
460 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
461 if (I->mayHaveSideEffects())
466 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
467 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
468 /// unswitch the loop, reprocess the pieces, then return true.
469 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
473 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
477 Function *F = loopHeader->getParent();
479 Constant *CondVal = 0;
480 BasicBlock *ExitBlock = 0;
481 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
482 // If the condition is trivial, always unswitch. There is no code growth
484 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
488 // Check to see if it would be profitable to unswitch current loop.
490 // Do not do non-trivial unswitch while optimizing for size.
491 if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
494 // FIXME: This is overly conservative because it does not take into
495 // consideration code simplification opportunities and code that can
496 // be shared by the resultant unswitched loops.
498 for (Loop::block_iterator I = currentLoop->block_begin(),
499 E = currentLoop->block_end();
501 Metrics.analyzeBasicBlock(*I);
503 // Limit the number of instructions to avoid causing significant code
504 // expansion, and the number of basic blocks, to avoid loops with
505 // large numbers of branches which cause loop unswitching to go crazy.
506 // This is a very ad-hoc heuristic.
508 unsigned NumUnswitched =
509 (NumSwitches + NumBranches) + 1 /*take in account current iteration*/;
511 unsigned NumInsts = Metrics.NumInsts * NumUnswitched;
512 unsigned NumBlocks = Metrics.NumBlocks * NumUnswitched;
514 if (NumInsts > Threshold || NumBlocks * 5 > Threshold ||
515 Metrics.containsIndirectBr || Metrics.isRecursive) {
516 DEBUG(dbgs() << "NOT unswitching loop %"
517 << currentLoop->getHeader()->getName() << ", cost too high: "
518 << currentLoop->getBlocks().size() << "\n");
522 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
526 /// CloneLoop - Recursively clone the specified loop and all of its children,
527 /// mapping the blocks with the specified map.
528 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
529 LoopInfo *LI, LPPassManager *LPM) {
530 Loop *New = new Loop();
531 LPM->insertLoop(New, PL);
533 // Add all of the blocks in L to the new loop.
534 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
536 if (LI->getLoopFor(*I) == L)
537 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
539 // Add all of the subloops to the new loop.
540 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
541 CloneLoop(*I, New, VM, LI, LPM);
546 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
547 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
548 /// code immediately before InsertPt.
549 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
550 BasicBlock *TrueDest,
551 BasicBlock *FalseDest,
552 Instruction *InsertPt) {
553 // Insert a conditional branch on LIC to the two preheaders. The original
554 // code is the true version and the new code is the false version.
555 Value *BranchVal = LIC;
556 if (!isa<ConstantInt>(Val) ||
557 Val->getType() != Type::getInt1Ty(LIC->getContext()))
558 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
559 else if (Val != ConstantInt::getTrue(Val->getContext()))
560 // We want to enter the new loop when the condition is true.
561 std::swap(TrueDest, FalseDest);
563 // Insert the new branch.
564 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
566 // If either edge is critical, split it. This helps preserve LoopSimplify
567 // form for enclosing loops.
568 SplitCriticalEdge(BI, 0, this);
569 SplitCriticalEdge(BI, 1, this);
572 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
573 /// condition in it (a cond branch from its header block to its latch block,
574 /// where the path through the loop that doesn't execute its body has no
575 /// side-effects), unswitch it. This doesn't involve any code duplication, just
576 /// moving the conditional branch outside of the loop and updating loop info.
577 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
579 BasicBlock *ExitBlock) {
580 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
581 << loopHeader->getName() << " [" << L->getBlocks().size()
582 << " blocks] in Function " << L->getHeader()->getParent()->getName()
583 << " on cond: " << *Val << " == " << *Cond << "\n");
585 // First step, split the preheader, so that we know that there is a safe place
586 // to insert the conditional branch. We will change loopPreheader to have a
587 // conditional branch on Cond.
588 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
590 // Now that we have a place to insert the conditional branch, create a place
591 // to branch to: this is the exit block out of the loop that we should
594 // Split this block now, so that the loop maintains its exit block, and so
595 // that the jump from the preheader can execute the contents of the exit block
596 // without actually branching to it (the exit block should be dominated by the
597 // loop header, not the preheader).
598 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
599 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
601 // Okay, now we have a position to branch from and a position to branch to,
602 // insert the new conditional branch.
603 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
604 loopPreheader->getTerminator());
605 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
606 loopPreheader->getTerminator()->eraseFromParent();
608 // We need to reprocess this loop, it could be unswitched again.
611 // Now that we know that the loop is never entered when this condition is a
612 // particular value, rewrite the loop with this info. We know that this will
613 // at least eliminate the old branch.
614 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
618 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
619 /// blocks. Update the appropriate Phi nodes as we do so.
620 void LoopUnswitch::SplitExitEdges(Loop *L,
621 const SmallVector<BasicBlock *, 8> &ExitBlocks){
623 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
624 BasicBlock *ExitBlock = ExitBlocks[i];
625 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
626 pred_end(ExitBlock));
628 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
629 // general, if we call it on all predecessors of all exits then it does.
630 if (!ExitBlock->isLandingPad()) {
631 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
633 SmallVector<BasicBlock*, 2> NewBBs;
634 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
640 /// UnswitchNontrivialCondition - We determined that the loop is profitable
641 /// to unswitch when LIC equal Val. Split it into loop versions and test the
642 /// condition outside of either loop. Return the loops created as Out1/Out2.
643 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
645 Function *F = loopHeader->getParent();
646 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
647 << loopHeader->getName() << " [" << L->getBlocks().size()
648 << " blocks] in Function " << F->getName()
649 << " when '" << *Val << "' == " << *LIC << "\n");
651 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
657 // First step, split the preheader and exit blocks, and add these blocks to
658 // the LoopBlocks list.
659 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
660 LoopBlocks.push_back(NewPreheader);
662 // We want the loop to come after the preheader, but before the exit blocks.
663 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
665 SmallVector<BasicBlock*, 8> ExitBlocks;
666 L->getUniqueExitBlocks(ExitBlocks);
668 // Split all of the edges from inside the loop to their exit blocks. Update
669 // the appropriate Phi nodes as we do so.
670 SplitExitEdges(L, ExitBlocks);
672 // The exit blocks may have been changed due to edge splitting, recompute.
674 L->getUniqueExitBlocks(ExitBlocks);
676 // Add exit blocks to the loop blocks.
677 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
679 // Next step, clone all of the basic blocks that make up the loop (including
680 // the loop preheader and exit blocks), keeping track of the mapping between
681 // the instructions and blocks.
682 NewBlocks.reserve(LoopBlocks.size());
683 ValueToValueMapTy VMap;
684 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
685 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
687 // Inherit simplified switches info for NewBB
688 // We needn't pass NewBB since its instructions are already contained
690 CloneUnswitchedVals(VMap, LoopBlocks[i]);
692 NewBlocks.push_back(NewBB);
693 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
694 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
697 // Splice the newly inserted blocks into the function right before the
698 // original preheader.
699 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
700 NewBlocks[0], F->end());
702 // Now we create the new Loop object for the versioned loop.
703 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
704 Loop *ParentLoop = L->getParentLoop();
706 // Make sure to add the cloned preheader and exit blocks to the parent loop
708 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
711 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
712 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
713 // The new exit block should be in the same loop as the old one.
714 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
715 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
717 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
718 "Exit block should have been split to have one successor!");
719 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
721 // If the successor of the exit block had PHI nodes, add an entry for
724 for (BasicBlock::iterator I = ExitSucc->begin(); isa<PHINode>(I); ++I) {
725 PN = cast<PHINode>(I);
726 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
727 ValueToValueMapTy::iterator It = VMap.find(V);
728 if (It != VMap.end()) V = It->second;
729 PN->addIncoming(V, NewExit);
732 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
733 PN = PHINode::Create(LPad->getType(), 0, "",
734 ExitSucc->getFirstInsertionPt());
736 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
739 LandingPadInst *LPI = BB->getLandingPadInst();
740 LPI->replaceAllUsesWith(PN);
741 PN->addIncoming(LPI, BB);
746 // Rewrite the code to refer to itself.
747 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
748 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
749 E = NewBlocks[i]->end(); I != E; ++I)
750 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
752 // Rewrite the original preheader to select between versions of the loop.
753 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
754 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
755 "Preheader splitting did not work correctly!");
757 // Emit the new branch that selects between the two versions of this loop.
758 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
759 LPM->deleteSimpleAnalysisValue(OldBR, L);
760 OldBR->eraseFromParent();
762 LoopProcessWorklist.push_back(NewLoop);
765 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
766 // deletes the instruction (for example by simplifying a PHI that feeds into
767 // the condition that we're unswitching on), we don't rewrite the second
769 WeakVH LICHandle(LIC);
771 // Now we rewrite the original code to know that the condition is true and the
772 // new code to know that the condition is false.
773 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
775 // It's possible that simplifying one loop could cause the other to be
776 // changed to another value or a constant. If its a constant, don't simplify
778 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
779 LICHandle && !isa<Constant>(LICHandle))
780 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
783 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
785 static void RemoveFromWorklist(Instruction *I,
786 std::vector<Instruction*> &Worklist) {
787 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
789 while (WI != Worklist.end()) {
790 unsigned Offset = WI-Worklist.begin();
792 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
796 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
797 /// program, replacing all uses with V and update the worklist.
798 static void ReplaceUsesOfWith(Instruction *I, Value *V,
799 std::vector<Instruction*> &Worklist,
800 Loop *L, LPPassManager *LPM) {
801 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
803 // Add uses to the worklist, which may be dead now.
804 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
805 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
806 Worklist.push_back(Use);
808 // Add users to the worklist which may be simplified now.
809 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
811 Worklist.push_back(cast<Instruction>(*UI));
812 LPM->deleteSimpleAnalysisValue(I, L);
813 RemoveFromWorklist(I, Worklist);
814 I->replaceAllUsesWith(V);
815 I->eraseFromParent();
819 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
820 /// information, and remove any dead successors it has.
822 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
823 std::vector<Instruction*> &Worklist,
825 if (pred_begin(BB) != pred_end(BB)) {
826 // This block isn't dead, since an edge to BB was just removed, see if there
827 // are any easy simplifications we can do now.
828 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
829 // If it has one pred, fold phi nodes in BB.
830 while (isa<PHINode>(BB->begin()))
831 ReplaceUsesOfWith(BB->begin(),
832 cast<PHINode>(BB->begin())->getIncomingValue(0),
835 // If this is the header of a loop and the only pred is the latch, we now
836 // have an unreachable loop.
837 if (Loop *L = LI->getLoopFor(BB))
838 if (loopHeader == BB && L->contains(Pred)) {
839 // Remove the branch from the latch to the header block, this makes
840 // the header dead, which will make the latch dead (because the header
841 // dominates the latch).
842 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
843 Pred->getTerminator()->eraseFromParent();
844 new UnreachableInst(BB->getContext(), Pred);
846 // The loop is now broken, remove it from LI.
847 RemoveLoopFromHierarchy(L);
849 // Reprocess the header, which now IS dead.
850 RemoveBlockIfDead(BB, Worklist, L);
854 // If pred ends in a uncond branch, add uncond branch to worklist so that
855 // the two blocks will get merged.
856 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
857 if (BI->isUnconditional())
858 Worklist.push_back(BI);
863 DEBUG(dbgs() << "Nuking dead block: " << *BB);
865 // Remove the instructions in the basic block from the worklist.
866 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
867 RemoveFromWorklist(I, Worklist);
869 // Anything that uses the instructions in this basic block should have their
870 // uses replaced with undefs.
871 // If I is not void type then replaceAllUsesWith undef.
872 // This allows ValueHandlers and custom metadata to adjust itself.
873 if (!I->getType()->isVoidTy())
874 I->replaceAllUsesWith(UndefValue::get(I->getType()));
877 // If this is the edge to the header block for a loop, remove the loop and
878 // promote all subloops.
879 if (Loop *BBLoop = LI->getLoopFor(BB)) {
880 if (BBLoop->getLoopLatch() == BB) {
881 RemoveLoopFromHierarchy(BBLoop);
882 if (currentLoop == BBLoop) {
889 // Remove the block from the loop info, which removes it from any loops it
894 // Remove phi node entries in successors for this block.
895 TerminatorInst *TI = BB->getTerminator();
896 SmallVector<BasicBlock*, 4> Succs;
897 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
898 Succs.push_back(TI->getSuccessor(i));
899 TI->getSuccessor(i)->removePredecessor(BB);
902 // Unique the successors, remove anything with multiple uses.
903 array_pod_sort(Succs.begin(), Succs.end());
904 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
906 // Remove the basic block, including all of the instructions contained in it.
907 LPM->deleteSimpleAnalysisValue(BB, L);
908 BB->eraseFromParent();
909 // Remove successor blocks here that are not dead, so that we know we only
910 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
911 // then getting removed before we revisit them, which is badness.
913 for (unsigned i = 0; i != Succs.size(); ++i)
914 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
915 // One exception is loop headers. If this block was the preheader for a
916 // loop, then we DO want to visit the loop so the loop gets deleted.
917 // We know that if the successor is a loop header, that this loop had to
918 // be the preheader: the case where this was the latch block was handled
919 // above and headers can only have two predecessors.
920 if (!LI->isLoopHeader(Succs[i])) {
921 Succs.erase(Succs.begin()+i);
926 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
927 RemoveBlockIfDead(Succs[i], Worklist, L);
930 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
931 /// become unwrapped, either because the backedge was deleted, or because the
932 /// edge into the header was removed. If the edge into the header from the
933 /// latch block was removed, the loop is unwrapped but subloops are still alive,
934 /// so they just reparent loops. If the loops are actually dead, they will be
936 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
937 LPM->deleteLoopFromQueue(L);
938 RemoveLoopFromWorklist(L);
941 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
942 // the value specified by Val in the specified loop, or we know it does NOT have
943 // that value. Rewrite any uses of LIC or of properties correlated to it.
944 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
947 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
949 // FIXME: Support correlated properties, like:
956 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
957 // selects, switches.
958 std::vector<Instruction*> Worklist;
959 LLVMContext &Context = Val->getContext();
962 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
963 // in the loop with the appropriate one directly.
964 if (IsEqual || (isa<ConstantInt>(Val) &&
965 Val->getType()->isIntegerTy(1))) {
970 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
971 !cast<ConstantInt>(Val)->getZExtValue());
973 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
975 Instruction *U = dyn_cast<Instruction>(*UI);
976 if (!U || !L->contains(U))
978 Worklist.push_back(U);
981 for (std::vector<Instruction*>::iterator UI = Worklist.begin();
982 UI != Worklist.end(); ++UI)
983 (*UI)->replaceUsesOfWith(LIC, Replacement);
985 SimplifyCode(Worklist, L);
989 // Otherwise, we don't know the precise value of LIC, but we do know that it
990 // is certainly NOT "Val". As such, simplify any uses in the loop that we
991 // can. This case occurs when we unswitch switch statements.
992 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
994 Instruction *U = dyn_cast<Instruction>(*UI);
995 if (!U || !L->contains(U))
998 Worklist.push_back(U);
1000 // TODO: We could do other simplifications, for example, turning
1001 // 'icmp eq LIC, Val' -> false.
1003 // If we know that LIC is not Val, use this info to simplify code.
1004 SwitchInst *SI = dyn_cast<SwitchInst>(U);
1005 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
1007 unsigned DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1008 if (DeadCase == 0) continue; // Default case is live for multiple values.
1010 // Found a dead case value. Don't remove PHI nodes in the
1011 // successor if they become single-entry, those PHI nodes may
1012 // be in the Users list.
1014 BasicBlock *Switch = SI->getParent();
1015 BasicBlock *SISucc = SI->getSuccessor(DeadCase);
1016 BasicBlock *Latch = L->getLoopLatch();
1018 UnswitchedVals[SI].insert(Val);
1020 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1021 // If the DeadCase successor dominates the loop latch, then the
1022 // transformation isn't safe since it will delete the sole predecessor edge
1024 if (Latch && DT->dominates(SISucc, Latch))
1027 // FIXME: This is a hack. We need to keep the successor around
1028 // and hooked up so as to preserve the loop structure, because
1029 // trying to update it is complicated. So instead we preserve the
1030 // loop structure and put the block on a dead code path.
1031 SplitEdge(Switch, SISucc, this);
1032 // Compute the successors instead of relying on the return value
1033 // of SplitEdge, since it may have split the switch successor
1035 BasicBlock *NewSISucc = SI->getSuccessor(DeadCase);
1036 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1037 // Create an "unreachable" destination.
1038 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1039 Switch->getParent(),
1041 new UnreachableInst(Context, Abort);
1042 // Force the new case destination to branch to the "unreachable"
1043 // block while maintaining a (dead) CFG edge to the old block.
1044 NewSISucc->getTerminator()->eraseFromParent();
1045 BranchInst::Create(Abort, OldSISucc,
1046 ConstantInt::getTrue(Context), NewSISucc);
1047 // Release the PHI operands for this edge.
1048 for (BasicBlock::iterator II = NewSISucc->begin();
1049 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1050 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1051 UndefValue::get(PN->getType()));
1052 // Tell the domtree about the new block. We don't fully update the
1053 // domtree here -- instead we force it to do a full recomputation
1054 // after the pass is complete -- but we do need to inform it of
1057 DT->addNewBlock(Abort, NewSISucc);
1060 SimplifyCode(Worklist, L);
1063 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1064 /// loop, walk over it and constant prop, dce, and fold control flow where
1065 /// possible. Note that this is effectively a very simple loop-structure-aware
1066 /// optimizer. During processing of this loop, L could very well be deleted, so
1067 /// it must not be used.
1069 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1072 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1073 while (!Worklist.empty()) {
1074 Instruction *I = Worklist.back();
1075 Worklist.pop_back();
1078 if (isInstructionTriviallyDead(I)) {
1079 DEBUG(dbgs() << "Remove dead instruction '" << *I);
1081 // Add uses to the worklist, which may be dead now.
1082 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1083 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1084 Worklist.push_back(Use);
1085 LPM->deleteSimpleAnalysisValue(I, L);
1086 RemoveFromWorklist(I, Worklist);
1087 I->eraseFromParent();
1092 // See if instruction simplification can hack this up. This is common for
1093 // things like "select false, X, Y" after unswitching made the condition be
1095 if (Value *V = SimplifyInstruction(I, 0, 0, DT))
1096 if (LI->replacementPreservesLCSSAForm(I, V)) {
1097 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1101 // Special case hacks that appear commonly in unswitched code.
1102 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1103 if (BI->isUnconditional()) {
1104 // If BI's parent is the only pred of the successor, fold the two blocks
1106 BasicBlock *Pred = BI->getParent();
1107 BasicBlock *Succ = BI->getSuccessor(0);
1108 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1109 if (!SinglePred) continue; // Nothing to do.
1110 assert(SinglePred == Pred && "CFG broken");
1112 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1113 << Succ->getName() << "\n");
1115 // Resolve any single entry PHI nodes in Succ.
1116 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1117 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1119 // If Succ has any successors with PHI nodes, update them to have
1120 // entries coming from Pred instead of Succ.
1121 Succ->replaceAllUsesWith(Pred);
1123 // Move all of the successor contents from Succ to Pred.
1124 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1126 LPM->deleteSimpleAnalysisValue(BI, L);
1127 BI->eraseFromParent();
1128 RemoveFromWorklist(BI, Worklist);
1130 // Remove Succ from the loop tree.
1131 LI->removeBlock(Succ);
1132 LPM->deleteSimpleAnalysisValue(Succ, L);
1133 Succ->eraseFromParent();
1138 if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1139 // Conditional branch. Turn it into an unconditional branch, then
1140 // remove dead blocks.
1141 continue; // FIXME: Enable.
1143 DEBUG(dbgs() << "Folded branch: " << *BI);
1144 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1145 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1146 DeadSucc->removePredecessor(BI->getParent(), true);
1147 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1148 LPM->deleteSimpleAnalysisValue(BI, L);
1149 BI->eraseFromParent();
1150 RemoveFromWorklist(BI, Worklist);
1153 RemoveBlockIfDead(DeadSucc, Worklist, L);