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/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/CodeMetrics.h"
35 #include "llvm/Analysis/InstructionSimplify.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Analysis/TargetTransformInfo.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Transforms/Utils/Local.h"
56 STATISTIC(NumBranches, "Number of branches unswitched");
57 STATISTIC(NumSwitches, "Number of switches unswitched");
58 STATISTIC(NumSelects , "Number of selects unswitched");
59 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
60 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
61 STATISTIC(TotalInsts, "Total number of instructions analyzed");
63 // The specific value of 100 here was chosen based only on intuition and a
64 // few specific examples.
65 static cl::opt<unsigned>
66 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
67 cl::init(100), cl::Hidden);
71 class LUAnalysisCache {
73 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
76 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
78 struct LoopProperties {
79 unsigned CanBeUnswitchedCount;
80 unsigned SizeEstimation;
81 UnswitchedValsMap UnswitchedVals;
84 // Here we use std::map instead of DenseMap, since we need to keep valid
85 // LoopProperties pointer for current loop for better performance.
86 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
87 typedef LoopPropsMap::iterator LoopPropsMapIt;
89 LoopPropsMap LoopsProperties;
90 UnswitchedValsMap *CurLoopInstructions;
91 LoopProperties *CurrentLoopProperties;
93 // Max size of code we can produce on remained iterations.
99 CurLoopInstructions(0), CurrentLoopProperties(0),
103 // Analyze loop. Check its size, calculate is it possible to unswitch
104 // it. Returns true if we can unswitch this loop.
105 bool countLoop(const Loop *L, const TargetTransformInfo &TTI);
107 // Clean all data related to given loop.
108 void forgetLoop(const Loop *L);
110 // Mark case value as unswitched.
111 // Since SI instruction can be partly unswitched, in order to avoid
112 // extra unswitching in cloned loops keep track all unswitched values.
113 void setUnswitched(const SwitchInst *SI, const Value *V);
115 // Check was this case value unswitched before or not.
116 bool isUnswitched(const SwitchInst *SI, const Value *V);
118 // Clone all loop-unswitch related loop properties.
119 // Redistribute unswitching quotas.
120 // Note, that new loop data is stored inside the VMap.
121 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
122 const ValueToValueMapTy &VMap);
125 class LoopUnswitch : public LoopPass {
126 LoopInfo *LI; // Loop information
129 // LoopProcessWorklist - Used to check if second loop needs processing
130 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
131 std::vector<Loop*> LoopProcessWorklist;
133 LUAnalysisCache BranchesInfo;
135 bool OptimizeForSize;
140 BasicBlock *loopHeader;
141 BasicBlock *loopPreheader;
143 // LoopBlocks contains all of the basic blocks of the loop, including the
144 // preheader of the loop, the body of the loop, and the exit blocks of the
145 // loop, in that order.
146 std::vector<BasicBlock*> LoopBlocks;
147 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
148 std::vector<BasicBlock*> NewBlocks;
151 static char ID; // Pass ID, replacement for typeid
152 explicit LoopUnswitch(bool Os = false) :
153 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
154 currentLoop(0), DT(0), loopHeader(0),
156 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
159 bool runOnLoop(Loop *L, LPPassManager &LPM);
160 bool processCurrentLoop();
162 /// This transformation requires natural loop information & requires that
163 /// loop preheaders be inserted into the CFG.
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.addRequiredID(LoopSimplifyID);
167 AU.addPreservedID(LoopSimplifyID);
168 AU.addRequired<LoopInfo>();
169 AU.addPreserved<LoopInfo>();
170 AU.addRequiredID(LCSSAID);
171 AU.addPreservedID(LCSSAID);
172 AU.addPreserved<DominatorTreeWrapperPass>();
173 AU.addPreserved<ScalarEvolution>();
174 AU.addRequired<TargetTransformInfo>();
179 virtual void releaseMemory() {
180 BranchesInfo.forgetLoop(currentLoop);
183 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
185 void RemoveLoopFromWorklist(Loop *L) {
186 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
187 LoopProcessWorklist.end(), L);
188 if (I != LoopProcessWorklist.end())
189 LoopProcessWorklist.erase(I);
192 void initLoopData() {
193 loopHeader = currentLoop->getHeader();
194 loopPreheader = currentLoop->getLoopPreheader();
197 /// Split all of the edges from inside the loop to their exit blocks.
198 /// Update the appropriate Phi nodes as we do so.
199 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
201 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
202 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
203 BasicBlock *ExitBlock);
204 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
207 Constant *Val, bool isEqual);
209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
210 BasicBlock *TrueDest,
211 BasicBlock *FalseDest,
212 Instruction *InsertPt);
214 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
215 void RemoveLoopFromHierarchy(Loop *L);
216 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
217 BasicBlock **LoopExit = 0);
222 // Analyze loop. Check its size, calculate is it possible to unswitch
223 // it. Returns true if we can unswitch this loop.
224 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
226 LoopPropsMapIt PropsIt;
228 llvm::tie(PropsIt, Inserted) =
229 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
231 LoopProperties &Props = PropsIt->second;
236 // Limit the number of instructions to avoid causing significant code
237 // expansion, and the number of basic blocks, to avoid loops with
238 // large numbers of branches which cause loop unswitching to go crazy.
239 // This is a very ad-hoc heuristic.
241 // FIXME: This is overly conservative because it does not take into
242 // consideration code simplification opportunities and code that can
243 // be shared by the resultant unswitched loops.
245 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
247 Metrics.analyzeBasicBlock(*I, TTI);
249 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
250 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
251 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
253 if (Metrics.notDuplicatable) {
254 DEBUG(dbgs() << "NOT unswitching loop %"
255 << L->getHeader()->getName() << ", contents cannot be "
261 if (!Props.CanBeUnswitchedCount) {
262 DEBUG(dbgs() << "NOT unswitching loop %"
263 << L->getHeader()->getName() << ", cost too high: "
264 << L->getBlocks().size() << "\n");
268 // Be careful. This links are good only before new loop addition.
269 CurrentLoopProperties = &Props;
270 CurLoopInstructions = &Props.UnswitchedVals;
275 // Clean all data related to given loop.
276 void LUAnalysisCache::forgetLoop(const Loop *L) {
278 LoopPropsMapIt LIt = LoopsProperties.find(L);
280 if (LIt != LoopsProperties.end()) {
281 LoopProperties &Props = LIt->second;
282 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
283 LoopsProperties.erase(LIt);
286 CurrentLoopProperties = 0;
287 CurLoopInstructions = 0;
290 // Mark case value as unswitched.
291 // Since SI instruction can be partly unswitched, in order to avoid
292 // extra unswitching in cloned loops keep track all unswitched values.
293 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
294 (*CurLoopInstructions)[SI].insert(V);
297 // Check was this case value unswitched before or not.
298 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
299 return (*CurLoopInstructions)[SI].count(V);
302 // Clone all loop-unswitch related loop properties.
303 // Redistribute unswitching quotas.
304 // Note, that new loop data is stored inside the VMap.
305 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
306 const ValueToValueMapTy &VMap) {
308 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
309 LoopProperties &OldLoopProps = *CurrentLoopProperties;
310 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
312 // Reallocate "can-be-unswitched quota"
314 --OldLoopProps.CanBeUnswitchedCount;
315 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
316 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
317 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
319 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
321 // Clone unswitched values info:
322 // for new loop switches we clone info about values that was
323 // already unswitched and has redundant successors.
324 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
325 const SwitchInst *OldInst = I->first;
326 Value *NewI = VMap.lookup(OldInst);
327 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
328 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
330 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
334 char LoopUnswitch::ID = 0;
335 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
337 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
338 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
339 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
340 INITIALIZE_PASS_DEPENDENCY(LCSSA)
341 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
344 Pass *llvm::createLoopUnswitchPass(bool Os) {
345 return new LoopUnswitch(Os);
348 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
349 /// invariant in the loop, or has an invariant piece, return the invariant.
350 /// Otherwise, return null.
351 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
353 // We started analyze new instruction, increment scanned instructions counter.
356 // We can never unswitch on vector conditions.
357 if (Cond->getType()->isVectorTy())
360 // Constants should be folded, not unswitched on!
361 if (isa<Constant>(Cond)) return 0;
363 // TODO: Handle: br (VARIANT|INVARIANT).
365 // Hoist simple values out.
366 if (L->makeLoopInvariant(Cond, Changed))
369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
370 if (BO->getOpcode() == Instruction::And ||
371 BO->getOpcode() == Instruction::Or) {
372 // If either the left or right side is invariant, we can unswitch on this,
373 // which will cause the branch to go away in one loop and the condition to
374 // simplify in the other one.
375 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
377 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
384 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
385 LI = &getAnalysis<LoopInfo>();
387 DominatorTreeWrapperPass *DTWP =
388 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
389 DT = DTWP ? &DTWP->getDomTree() : 0;
391 Function *F = currentLoop->getHeader()->getParent();
392 bool Changed = false;
394 assert(currentLoop->isLCSSAForm(*DT));
396 Changed |= processCurrentLoop();
400 // FIXME: Reconstruct dom info, because it is not preserved properly.
407 /// processCurrentLoop - Do actual work and unswitch loop if possible
409 bool LoopUnswitch::processCurrentLoop() {
410 bool Changed = false;
414 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
418 // Loops with indirectbr cannot be cloned.
419 if (!currentLoop->isSafeToClone())
422 // Without dedicated exits, splitting the exit edge may fail.
423 if (!currentLoop->hasDedicatedExits())
426 LLVMContext &Context = loopHeader->getContext();
428 // Probably we reach the quota of branches for this loop. If so
430 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
433 // Loop over all of the basic blocks in the loop. If we find an interior
434 // block that is branching on a loop-invariant condition, we can unswitch this
436 for (Loop::block_iterator I = currentLoop->block_begin(),
437 E = currentLoop->block_end(); I != E; ++I) {
438 TerminatorInst *TI = (*I)->getTerminator();
439 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
440 // If this isn't branching on an invariant condition, we can't unswitch
442 if (BI->isConditional()) {
443 // See if this, or some part of it, is loop invariant. If so, we can
444 // unswitch on it if we desire.
445 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
446 currentLoop, Changed);
447 if (LoopCond && UnswitchIfProfitable(LoopCond,
448 ConstantInt::getTrue(Context))) {
453 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
454 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
455 currentLoop, Changed);
456 unsigned NumCases = SI->getNumCases();
457 if (LoopCond && NumCases) {
458 // Find a value to unswitch on:
459 // FIXME: this should chose the most expensive case!
460 // FIXME: scan for a case with a non-critical edge?
461 Constant *UnswitchVal = 0;
463 // Do not process same value again and again.
464 // At this point we have some cases already unswitched and
465 // some not yet unswitched. Let's find the first not yet unswitched one.
466 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
468 Constant *UnswitchValCandidate = i.getCaseValue();
469 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
470 UnswitchVal = UnswitchValCandidate;
478 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
485 // Scan the instructions to check for unswitchable values.
486 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
488 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
489 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
490 currentLoop, Changed);
491 if (LoopCond && UnswitchIfProfitable(LoopCond,
492 ConstantInt::getTrue(Context))) {
501 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
502 /// loop with no side effects (including infinite loops).
504 /// If true, we return true and set ExitBB to the block we
507 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
509 std::set<BasicBlock*> &Visited) {
510 if (!Visited.insert(BB).second) {
511 // Already visited. Without more analysis, this could indicate an infinite
515 if (!L->contains(BB)) {
516 // Otherwise, this is a loop exit, this is fine so long as this is the
518 if (ExitBB != 0) return false;
523 // Otherwise, this is an unvisited intra-loop node. Check all successors.
524 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
525 // Check to see if the successor is a trivial loop exit.
526 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
530 // Okay, everything after this looks good, check to make sure that this block
531 // doesn't include any side effects.
532 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
533 if (I->mayHaveSideEffects())
539 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
540 /// leads to an exit from the specified loop, and has no side-effects in the
541 /// process. If so, return the block that is exited to, otherwise return null.
542 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
543 std::set<BasicBlock*> Visited;
544 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
545 BasicBlock *ExitBB = 0;
546 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
551 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
552 /// trivial: that is, that the condition controls whether or not the loop does
553 /// anything at all. If this is a trivial condition, unswitching produces no
554 /// code duplications (equivalently, it produces a simpler loop and a new empty
555 /// loop, which gets deleted).
557 /// If this is a trivial condition, return true, otherwise return false. When
558 /// returning true, this sets Cond and Val to the condition that controls the
559 /// trivial condition: when Cond dynamically equals Val, the loop is known to
560 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
563 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
564 BasicBlock **LoopExit) {
565 BasicBlock *Header = currentLoop->getHeader();
566 TerminatorInst *HeaderTerm = Header->getTerminator();
567 LLVMContext &Context = Header->getContext();
569 BasicBlock *LoopExitBB = 0;
570 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
571 // If the header block doesn't end with a conditional branch on Cond, we
573 if (!BI->isConditional() || BI->getCondition() != Cond)
576 // Check to see if a successor of the branch is guaranteed to
577 // exit through a unique exit block without having any
578 // side-effects. If so, determine the value of Cond that causes it to do
580 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
581 BI->getSuccessor(0)))) {
582 if (Val) *Val = ConstantInt::getTrue(Context);
583 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
584 BI->getSuccessor(1)))) {
585 if (Val) *Val = ConstantInt::getFalse(Context);
587 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
588 // If this isn't a switch on Cond, we can't handle it.
589 if (SI->getCondition() != Cond) return false;
591 // Check to see if a successor of the switch is guaranteed to go to the
592 // latch block or exit through a one exit block without having any
593 // side-effects. If so, determine the value of Cond that causes it to do
595 // Note that we can't trivially unswitch on the default case or
596 // on already unswitched cases.
597 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
599 BasicBlock *LoopExitCandidate;
600 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
601 i.getCaseSuccessor()))) {
602 // Okay, we found a trivial case, remember the value that is trivial.
603 ConstantInt *CaseVal = i.getCaseValue();
605 // Check that it was not unswitched before, since already unswitched
606 // trivial vals are looks trivial too.
607 if (BranchesInfo.isUnswitched(SI, CaseVal))
609 LoopExitBB = LoopExitCandidate;
610 if (Val) *Val = CaseVal;
616 // If we didn't find a single unique LoopExit block, or if the loop exit block
617 // contains phi nodes, this isn't trivial.
618 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
619 return false; // Can't handle this.
621 if (LoopExit) *LoopExit = LoopExitBB;
623 // We already know that nothing uses any scalar values defined inside of this
624 // loop. As such, we just have to check to see if this loop will execute any
625 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
626 // part of the loop that the code *would* execute. We already checked the
627 // tail, check the header now.
628 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
629 if (I->mayHaveSideEffects())
634 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
635 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
636 /// unswitch the loop, reprocess the pieces, then return true.
637 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
638 Function *F = loopHeader->getParent();
639 Constant *CondVal = 0;
640 BasicBlock *ExitBlock = 0;
642 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
643 // If the condition is trivial, always unswitch. There is no code growth
645 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
649 // Check to see if it would be profitable to unswitch current loop.
651 // Do not do non-trivial unswitch while optimizing for size.
652 if (OptimizeForSize ||
653 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
654 Attribute::OptimizeForSize))
657 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
661 /// CloneLoop - Recursively clone the specified loop and all of its children,
662 /// mapping the blocks with the specified map.
663 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
664 LoopInfo *LI, LPPassManager *LPM) {
665 Loop *New = new Loop();
666 LPM->insertLoop(New, PL);
668 // Add all of the blocks in L to the new loop.
669 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
671 if (LI->getLoopFor(*I) == L)
672 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
674 // Add all of the subloops to the new loop.
675 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
676 CloneLoop(*I, New, VM, LI, LPM);
681 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
682 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
683 /// code immediately before InsertPt.
684 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
685 BasicBlock *TrueDest,
686 BasicBlock *FalseDest,
687 Instruction *InsertPt) {
688 // Insert a conditional branch on LIC to the two preheaders. The original
689 // code is the true version and the new code is the false version.
690 Value *BranchVal = LIC;
691 if (!isa<ConstantInt>(Val) ||
692 Val->getType() != Type::getInt1Ty(LIC->getContext()))
693 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
694 else if (Val != ConstantInt::getTrue(Val->getContext()))
695 // We want to enter the new loop when the condition is true.
696 std::swap(TrueDest, FalseDest);
698 // Insert the new branch.
699 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
701 // If either edge is critical, split it. This helps preserve LoopSimplify
702 // form for enclosing loops.
703 SplitCriticalEdge(BI, 0, this, false, false, true);
704 SplitCriticalEdge(BI, 1, this, false, false, true);
707 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
708 /// condition in it (a cond branch from its header block to its latch block,
709 /// where the path through the loop that doesn't execute its body has no
710 /// side-effects), unswitch it. This doesn't involve any code duplication, just
711 /// moving the conditional branch outside of the loop and updating loop info.
712 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
714 BasicBlock *ExitBlock) {
715 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
716 << loopHeader->getName() << " [" << L->getBlocks().size()
717 << " blocks] in Function " << L->getHeader()->getParent()->getName()
718 << " on cond: " << *Val << " == " << *Cond << "\n");
720 // First step, split the preheader, so that we know that there is a safe place
721 // to insert the conditional branch. We will change loopPreheader to have a
722 // conditional branch on Cond.
723 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
725 // Now that we have a place to insert the conditional branch, create a place
726 // to branch to: this is the exit block out of the loop that we should
729 // Split this block now, so that the loop maintains its exit block, and so
730 // that the jump from the preheader can execute the contents of the exit block
731 // without actually branching to it (the exit block should be dominated by the
732 // loop header, not the preheader).
733 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
734 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
736 // Okay, now we have a position to branch from and a position to branch to,
737 // insert the new conditional branch.
738 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
739 loopPreheader->getTerminator());
740 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
741 loopPreheader->getTerminator()->eraseFromParent();
743 // We need to reprocess this loop, it could be unswitched again.
746 // Now that we know that the loop is never entered when this condition is a
747 // particular value, rewrite the loop with this info. We know that this will
748 // at least eliminate the old branch.
749 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
753 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
754 /// blocks. Update the appropriate Phi nodes as we do so.
755 void LoopUnswitch::SplitExitEdges(Loop *L,
756 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
758 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
759 BasicBlock *ExitBlock = ExitBlocks[i];
760 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
761 pred_end(ExitBlock));
763 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
764 // general, if we call it on all predecessors of all exits then it does.
765 if (!ExitBlock->isLandingPad()) {
766 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
768 SmallVector<BasicBlock*, 2> NewBBs;
769 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
775 /// UnswitchNontrivialCondition - We determined that the loop is profitable
776 /// to unswitch when LIC equal Val. Split it into loop versions and test the
777 /// condition outside of either loop. Return the loops created as Out1/Out2.
778 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
780 Function *F = loopHeader->getParent();
781 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
782 << loopHeader->getName() << " [" << L->getBlocks().size()
783 << " blocks] in Function " << F->getName()
784 << " when '" << *Val << "' == " << *LIC << "\n");
786 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
792 // First step, split the preheader and exit blocks, and add these blocks to
793 // the LoopBlocks list.
794 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
795 LoopBlocks.push_back(NewPreheader);
797 // We want the loop to come after the preheader, but before the exit blocks.
798 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
800 SmallVector<BasicBlock*, 8> ExitBlocks;
801 L->getUniqueExitBlocks(ExitBlocks);
803 // Split all of the edges from inside the loop to their exit blocks. Update
804 // the appropriate Phi nodes as we do so.
805 SplitExitEdges(L, ExitBlocks);
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 ValueToValueMapTy VMap;
819 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
820 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
822 NewBlocks.push_back(NewBB);
823 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
824 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
827 // Splice the newly inserted blocks into the function right before the
828 // original preheader.
829 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
830 NewBlocks[0], F->end());
832 // Now we create the new Loop object for the versioned loop.
833 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
835 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
836 // Probably clone more loop-unswitch related loop properties.
837 BranchesInfo.cloneData(NewLoop, L, VMap);
839 Loop *ParentLoop = L->getParentLoop();
841 // Make sure to add the cloned preheader and exit blocks to the parent loop
843 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
846 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
847 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
848 // The new exit block should be in the same loop as the old one.
849 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
850 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
852 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
853 "Exit block should have been split to have one successor!");
854 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
856 // If the successor of the exit block had PHI nodes, add an entry for
858 for (BasicBlock::iterator I = ExitSucc->begin();
859 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
860 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
861 ValueToValueMapTy::iterator It = VMap.find(V);
862 if (It != VMap.end()) V = It->second;
863 PN->addIncoming(V, NewExit);
866 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
867 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
868 ExitSucc->getFirstInsertionPt());
870 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
873 LandingPadInst *LPI = BB->getLandingPadInst();
874 LPI->replaceAllUsesWith(PN);
875 PN->addIncoming(LPI, BB);
880 // Rewrite the code to refer to itself.
881 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
882 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
883 E = NewBlocks[i]->end(); I != E; ++I)
884 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
886 // Rewrite the original preheader to select between versions of the loop.
887 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
888 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
889 "Preheader splitting did not work correctly!");
891 // Emit the new branch that selects between the two versions of this loop.
892 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
893 LPM->deleteSimpleAnalysisValue(OldBR, L);
894 OldBR->eraseFromParent();
896 LoopProcessWorklist.push_back(NewLoop);
899 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
900 // deletes the instruction (for example by simplifying a PHI that feeds into
901 // the condition that we're unswitching on), we don't rewrite the second
903 WeakVH LICHandle(LIC);
905 // Now we rewrite the original code to know that the condition is true and the
906 // new code to know that the condition is false.
907 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
909 // It's possible that simplifying one loop could cause the other to be
910 // changed to another value or a constant. If its a constant, don't simplify
912 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
913 LICHandle && !isa<Constant>(LICHandle))
914 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
917 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
919 static void RemoveFromWorklist(Instruction *I,
920 std::vector<Instruction*> &Worklist) {
922 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
926 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
927 /// program, replacing all uses with V and update the worklist.
928 static void ReplaceUsesOfWith(Instruction *I, Value *V,
929 std::vector<Instruction*> &Worklist,
930 Loop *L, LPPassManager *LPM) {
931 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
933 // Add uses to the worklist, which may be dead now.
934 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
935 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
936 Worklist.push_back(Use);
938 // Add users to the worklist which may be simplified now.
939 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
941 Worklist.push_back(cast<Instruction>(*UI));
942 LPM->deleteSimpleAnalysisValue(I, L);
943 RemoveFromWorklist(I, Worklist);
944 I->replaceAllUsesWith(V);
945 I->eraseFromParent();
949 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
950 /// become unwrapped, either because the backedge was deleted, or because the
951 /// edge into the header was removed. If the edge into the header from the
952 /// latch block was removed, the loop is unwrapped but subloops are still alive,
953 /// so they just reparent loops. If the loops are actually dead, they will be
955 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
956 LPM->deleteLoopFromQueue(L);
957 RemoveLoopFromWorklist(L);
960 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
961 // the value specified by Val in the specified loop, or we know it does NOT have
962 // that value. Rewrite any uses of LIC or of properties correlated to it.
963 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
966 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
968 // FIXME: Support correlated properties, like:
975 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
976 // selects, switches.
977 std::vector<Instruction*> Worklist;
978 LLVMContext &Context = Val->getContext();
980 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
981 // in the loop with the appropriate one directly.
982 if (IsEqual || (isa<ConstantInt>(Val) &&
983 Val->getType()->isIntegerTy(1))) {
988 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
989 !cast<ConstantInt>(Val)->getZExtValue());
991 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
993 Instruction *U = dyn_cast<Instruction>(*UI);
994 if (!U || !L->contains(U))
996 Worklist.push_back(U);
999 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1000 UE = Worklist.end(); UI != UE; ++UI)
1001 (*UI)->replaceUsesOfWith(LIC, Replacement);
1003 SimplifyCode(Worklist, L);
1007 // Otherwise, we don't know the precise value of LIC, but we do know that it
1008 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1009 // can. This case occurs when we unswitch switch statements.
1010 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
1012 Instruction *U = dyn_cast<Instruction>(*UI);
1013 if (!U || !L->contains(U))
1016 Worklist.push_back(U);
1018 // TODO: We could do other simplifications, for example, turning
1019 // 'icmp eq LIC, Val' -> false.
1021 // If we know that LIC is not Val, use this info to simplify code.
1022 SwitchInst *SI = dyn_cast<SwitchInst>(U);
1023 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
1025 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1026 // Default case is live for multiple values.
1027 if (DeadCase == SI->case_default()) continue;
1029 // Found a dead case value. Don't remove PHI nodes in the
1030 // successor if they become single-entry, those PHI nodes may
1031 // be in the Users list.
1033 BasicBlock *Switch = SI->getParent();
1034 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1035 BasicBlock *Latch = L->getLoopLatch();
1037 BranchesInfo.setUnswitched(SI, Val);
1039 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1040 // If the DeadCase successor dominates the loop latch, then the
1041 // transformation isn't safe since it will delete the sole predecessor edge
1043 if (Latch && DT->dominates(SISucc, Latch))
1046 // FIXME: This is a hack. We need to keep the successor around
1047 // and hooked up so as to preserve the loop structure, because
1048 // trying to update it is complicated. So instead we preserve the
1049 // loop structure and put the block on a dead code path.
1050 SplitEdge(Switch, SISucc, this);
1051 // Compute the successors instead of relying on the return value
1052 // of SplitEdge, since it may have split the switch successor
1054 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1055 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1056 // Create an "unreachable" destination.
1057 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1058 Switch->getParent(),
1060 new UnreachableInst(Context, Abort);
1061 // Force the new case destination to branch to the "unreachable"
1062 // block while maintaining a (dead) CFG edge to the old block.
1063 NewSISucc->getTerminator()->eraseFromParent();
1064 BranchInst::Create(Abort, OldSISucc,
1065 ConstantInt::getTrue(Context), NewSISucc);
1066 // Release the PHI operands for this edge.
1067 for (BasicBlock::iterator II = NewSISucc->begin();
1068 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1069 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1070 UndefValue::get(PN->getType()));
1071 // Tell the domtree about the new block. We don't fully update the
1072 // domtree here -- instead we force it to do a full recomputation
1073 // after the pass is complete -- but we do need to inform it of
1076 DT->addNewBlock(Abort, NewSISucc);
1079 SimplifyCode(Worklist, L);
1082 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1083 /// loop, walk over it and constant prop, dce, and fold control flow where
1084 /// possible. Note that this is effectively a very simple loop-structure-aware
1085 /// optimizer. During processing of this loop, L could very well be deleted, so
1086 /// it must not be used.
1088 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1091 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1092 while (!Worklist.empty()) {
1093 Instruction *I = Worklist.back();
1094 Worklist.pop_back();
1097 if (isInstructionTriviallyDead(I)) {
1098 DEBUG(dbgs() << "Remove dead instruction '" << *I);
1100 // Add uses to the worklist, which may be dead now.
1101 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1102 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1103 Worklist.push_back(Use);
1104 LPM->deleteSimpleAnalysisValue(I, L);
1105 RemoveFromWorklist(I, Worklist);
1106 I->eraseFromParent();
1111 // See if instruction simplification can hack this up. This is common for
1112 // things like "select false, X, Y" after unswitching made the condition be
1113 // 'false'. TODO: update the domtree properly so we can pass it here.
1114 if (Value *V = SimplifyInstruction(I))
1115 if (LI->replacementPreservesLCSSAForm(I, V)) {
1116 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1120 // Special case hacks that appear commonly in unswitched code.
1121 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1122 if (BI->isUnconditional()) {
1123 // If BI's parent is the only pred of the successor, fold the two blocks
1125 BasicBlock *Pred = BI->getParent();
1126 BasicBlock *Succ = BI->getSuccessor(0);
1127 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1128 if (!SinglePred) continue; // Nothing to do.
1129 assert(SinglePred == Pred && "CFG broken");
1131 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1132 << Succ->getName() << "\n");
1134 // Resolve any single entry PHI nodes in Succ.
1135 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1136 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1138 // If Succ has any successors with PHI nodes, update them to have
1139 // entries coming from Pred instead of Succ.
1140 Succ->replaceAllUsesWith(Pred);
1142 // Move all of the successor contents from Succ to Pred.
1143 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1145 LPM->deleteSimpleAnalysisValue(BI, L);
1146 BI->eraseFromParent();
1147 RemoveFromWorklist(BI, Worklist);
1149 // Remove Succ from the loop tree.
1150 LI->removeBlock(Succ);
1151 LPM->deleteSimpleAnalysisValue(Succ, L);
1152 Succ->eraseFromParent();