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) override;
160 bool processCurrentLoop();
162 /// This transformation requires natural loop information & requires that
163 /// loop preheaders be inserted into the CFG.
165 void getAnalysisUsage(AnalysisUsage &AU) const override {
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 void releaseMemory() override {
180 BranchesInfo.forgetLoop(currentLoop);
183 void initLoopData() {
184 loopHeader = currentLoop->getHeader();
185 loopPreheader = currentLoop->getLoopPreheader();
188 /// Split all of the edges from inside the loop to their exit blocks.
189 /// Update the appropriate Phi nodes as we do so.
190 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
192 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
193 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
194 BasicBlock *ExitBlock);
195 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
197 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
198 Constant *Val, bool isEqual);
200 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
201 BasicBlock *TrueDest,
202 BasicBlock *FalseDest,
203 Instruction *InsertPt);
205 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
206 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
207 BasicBlock **LoopExit = 0);
212 // Analyze loop. Check its size, calculate is it possible to unswitch
213 // it. Returns true if we can unswitch this loop.
214 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
216 LoopPropsMapIt PropsIt;
218 std::tie(PropsIt, Inserted) =
219 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
221 LoopProperties &Props = PropsIt->second;
226 // Limit the number of instructions to avoid causing significant code
227 // expansion, and the number of basic blocks, to avoid loops with
228 // large numbers of branches which cause loop unswitching to go crazy.
229 // This is a very ad-hoc heuristic.
231 // FIXME: This is overly conservative because it does not take into
232 // consideration code simplification opportunities and code that can
233 // be shared by the resultant unswitched loops.
235 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
237 Metrics.analyzeBasicBlock(*I, TTI);
239 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
240 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
241 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
243 if (Metrics.notDuplicatable) {
244 DEBUG(dbgs() << "NOT unswitching loop %"
245 << L->getHeader()->getName() << ", contents cannot be "
251 if (!Props.CanBeUnswitchedCount) {
252 DEBUG(dbgs() << "NOT unswitching loop %"
253 << L->getHeader()->getName() << ", cost too high: "
254 << L->getBlocks().size() << "\n");
258 // Be careful. This links are good only before new loop addition.
259 CurrentLoopProperties = &Props;
260 CurLoopInstructions = &Props.UnswitchedVals;
265 // Clean all data related to given loop.
266 void LUAnalysisCache::forgetLoop(const Loop *L) {
268 LoopPropsMapIt LIt = LoopsProperties.find(L);
270 if (LIt != LoopsProperties.end()) {
271 LoopProperties &Props = LIt->second;
272 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
273 LoopsProperties.erase(LIt);
276 CurrentLoopProperties = 0;
277 CurLoopInstructions = 0;
280 // Mark case value as unswitched.
281 // Since SI instruction can be partly unswitched, in order to avoid
282 // extra unswitching in cloned loops keep track all unswitched values.
283 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
284 (*CurLoopInstructions)[SI].insert(V);
287 // Check was this case value unswitched before or not.
288 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
289 return (*CurLoopInstructions)[SI].count(V);
292 // Clone all loop-unswitch related loop properties.
293 // Redistribute unswitching quotas.
294 // Note, that new loop data is stored inside the VMap.
295 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
296 const ValueToValueMapTy &VMap) {
298 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
299 LoopProperties &OldLoopProps = *CurrentLoopProperties;
300 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
302 // Reallocate "can-be-unswitched quota"
304 --OldLoopProps.CanBeUnswitchedCount;
305 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
306 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
307 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
309 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
311 // Clone unswitched values info:
312 // for new loop switches we clone info about values that was
313 // already unswitched and has redundant successors.
314 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
315 const SwitchInst *OldInst = I->first;
316 Value *NewI = VMap.lookup(OldInst);
317 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
318 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
320 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
324 char LoopUnswitch::ID = 0;
325 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
327 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
328 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
329 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
330 INITIALIZE_PASS_DEPENDENCY(LCSSA)
331 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
334 Pass *llvm::createLoopUnswitchPass(bool Os) {
335 return new LoopUnswitch(Os);
338 /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
339 /// invariant in the loop, or has an invariant piece, return the invariant.
340 /// Otherwise, return null.
341 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
343 // We started analyze new instruction, increment scanned instructions counter.
346 // We can never unswitch on vector conditions.
347 if (Cond->getType()->isVectorTy())
350 // Constants should be folded, not unswitched on!
351 if (isa<Constant>(Cond)) return 0;
353 // TODO: Handle: br (VARIANT|INVARIANT).
355 // Hoist simple values out.
356 if (L->makeLoopInvariant(Cond, Changed))
359 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
360 if (BO->getOpcode() == Instruction::And ||
361 BO->getOpcode() == Instruction::Or) {
362 // If either the left or right side is invariant, we can unswitch on this,
363 // which will cause the branch to go away in one loop and the condition to
364 // simplify in the other one.
365 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
367 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
374 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
375 if (skipOptnoneFunction(L))
378 LI = &getAnalysis<LoopInfo>();
380 DominatorTreeWrapperPass *DTWP =
381 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
382 DT = DTWP ? &DTWP->getDomTree() : 0;
384 Function *F = currentLoop->getHeader()->getParent();
385 bool Changed = false;
387 assert(currentLoop->isLCSSAForm(*DT));
389 Changed |= processCurrentLoop();
393 // FIXME: Reconstruct dom info, because it is not preserved properly.
400 /// processCurrentLoop - Do actual work and unswitch loop if possible
402 bool LoopUnswitch::processCurrentLoop() {
403 bool Changed = false;
407 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
411 // Loops with indirectbr cannot be cloned.
412 if (!currentLoop->isSafeToClone())
415 // Without dedicated exits, splitting the exit edge may fail.
416 if (!currentLoop->hasDedicatedExits())
419 LLVMContext &Context = loopHeader->getContext();
421 // Probably we reach the quota of branches for this loop. If so
423 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
426 // Loop over all of the basic blocks in the loop. If we find an interior
427 // block that is branching on a loop-invariant condition, we can unswitch this
429 for (Loop::block_iterator I = currentLoop->block_begin(),
430 E = currentLoop->block_end(); I != E; ++I) {
431 TerminatorInst *TI = (*I)->getTerminator();
432 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
433 // If this isn't branching on an invariant condition, we can't unswitch
435 if (BI->isConditional()) {
436 // See if this, or some part of it, is loop invariant. If so, we can
437 // unswitch on it if we desire.
438 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
439 currentLoop, Changed);
440 if (LoopCond && UnswitchIfProfitable(LoopCond,
441 ConstantInt::getTrue(Context))) {
446 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
447 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
448 currentLoop, Changed);
449 unsigned NumCases = SI->getNumCases();
450 if (LoopCond && NumCases) {
451 // Find a value to unswitch on:
452 // FIXME: this should chose the most expensive case!
453 // FIXME: scan for a case with a non-critical edge?
454 Constant *UnswitchVal = 0;
456 // Do not process same value again and again.
457 // At this point we have some cases already unswitched and
458 // some not yet unswitched. Let's find the first not yet unswitched one.
459 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
461 Constant *UnswitchValCandidate = i.getCaseValue();
462 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
463 UnswitchVal = UnswitchValCandidate;
471 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
478 // Scan the instructions to check for unswitchable values.
479 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
481 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
482 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
483 currentLoop, Changed);
484 if (LoopCond && UnswitchIfProfitable(LoopCond,
485 ConstantInt::getTrue(Context))) {
494 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
495 /// loop with no side effects (including infinite loops).
497 /// If true, we return true and set ExitBB to the block we
500 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
502 std::set<BasicBlock*> &Visited) {
503 if (!Visited.insert(BB).second) {
504 // Already visited. Without more analysis, this could indicate an infinite
508 if (!L->contains(BB)) {
509 // Otherwise, this is a loop exit, this is fine so long as this is the
511 if (ExitBB != 0) return false;
516 // Otherwise, this is an unvisited intra-loop node. Check all successors.
517 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
518 // Check to see if the successor is a trivial loop exit.
519 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
523 // Okay, everything after this looks good, check to make sure that this block
524 // doesn't include any side effects.
525 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
526 if (I->mayHaveSideEffects())
532 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
533 /// leads to an exit from the specified loop, and has no side-effects in the
534 /// process. If so, return the block that is exited to, otherwise return null.
535 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
536 std::set<BasicBlock*> Visited;
537 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
538 BasicBlock *ExitBB = 0;
539 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
544 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
545 /// trivial: that is, that the condition controls whether or not the loop does
546 /// anything at all. If this is a trivial condition, unswitching produces no
547 /// code duplications (equivalently, it produces a simpler loop and a new empty
548 /// loop, which gets deleted).
550 /// If this is a trivial condition, return true, otherwise return false. When
551 /// returning true, this sets Cond and Val to the condition that controls the
552 /// trivial condition: when Cond dynamically equals Val, the loop is known to
553 /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
556 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
557 BasicBlock **LoopExit) {
558 BasicBlock *Header = currentLoop->getHeader();
559 TerminatorInst *HeaderTerm = Header->getTerminator();
560 LLVMContext &Context = Header->getContext();
562 BasicBlock *LoopExitBB = 0;
563 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
564 // If the header block doesn't end with a conditional branch on Cond, we
566 if (!BI->isConditional() || BI->getCondition() != Cond)
569 // Check to see if a successor of the branch is guaranteed to
570 // exit through a unique exit block without having any
571 // side-effects. If so, determine the value of Cond that causes it to do
573 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
574 BI->getSuccessor(0)))) {
575 if (Val) *Val = ConstantInt::getTrue(Context);
576 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
577 BI->getSuccessor(1)))) {
578 if (Val) *Val = ConstantInt::getFalse(Context);
580 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
581 // If this isn't a switch on Cond, we can't handle it.
582 if (SI->getCondition() != Cond) return false;
584 // Check to see if a successor of the switch is guaranteed to go to the
585 // latch block or exit through a one exit block without having any
586 // side-effects. If so, determine the value of Cond that causes it to do
588 // Note that we can't trivially unswitch on the default case or
589 // on already unswitched cases.
590 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
592 BasicBlock *LoopExitCandidate;
593 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
594 i.getCaseSuccessor()))) {
595 // Okay, we found a trivial case, remember the value that is trivial.
596 ConstantInt *CaseVal = i.getCaseValue();
598 // Check that it was not unswitched before, since already unswitched
599 // trivial vals are looks trivial too.
600 if (BranchesInfo.isUnswitched(SI, CaseVal))
602 LoopExitBB = LoopExitCandidate;
603 if (Val) *Val = CaseVal;
609 // If we didn't find a single unique LoopExit block, or if the loop exit block
610 // contains phi nodes, this isn't trivial.
611 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
612 return false; // Can't handle this.
614 if (LoopExit) *LoopExit = LoopExitBB;
616 // We already know that nothing uses any scalar values defined inside of this
617 // loop. As such, we just have to check to see if this loop will execute any
618 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
619 // part of the loop that the code *would* execute. We already checked the
620 // tail, check the header now.
621 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
622 if (I->mayHaveSideEffects())
627 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
628 /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
629 /// unswitch the loop, reprocess the pieces, then return true.
630 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
631 Function *F = loopHeader->getParent();
632 Constant *CondVal = 0;
633 BasicBlock *ExitBlock = 0;
635 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
636 // If the condition is trivial, always unswitch. There is no code growth
638 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
642 // Check to see if it would be profitable to unswitch current loop.
644 // Do not do non-trivial unswitch while optimizing for size.
645 if (OptimizeForSize ||
646 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
647 Attribute::OptimizeForSize))
650 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
654 /// CloneLoop - Recursively clone the specified loop and all of its children,
655 /// mapping the blocks with the specified map.
656 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
657 LoopInfo *LI, LPPassManager *LPM) {
658 Loop *New = new Loop();
659 LPM->insertLoop(New, PL);
661 // Add all of the blocks in L to the new loop.
662 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
664 if (LI->getLoopFor(*I) == L)
665 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
667 // Add all of the subloops to the new loop.
668 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
669 CloneLoop(*I, New, VM, LI, LPM);
674 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
675 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
676 /// code immediately before InsertPt.
677 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
678 BasicBlock *TrueDest,
679 BasicBlock *FalseDest,
680 Instruction *InsertPt) {
681 // Insert a conditional branch on LIC to the two preheaders. The original
682 // code is the true version and the new code is the false version.
683 Value *BranchVal = LIC;
684 if (!isa<ConstantInt>(Val) ||
685 Val->getType() != Type::getInt1Ty(LIC->getContext()))
686 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
687 else if (Val != ConstantInt::getTrue(Val->getContext()))
688 // We want to enter the new loop when the condition is true.
689 std::swap(TrueDest, FalseDest);
691 // Insert the new branch.
692 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
694 // If either edge is critical, split it. This helps preserve LoopSimplify
695 // form for enclosing loops.
696 SplitCriticalEdge(BI, 0, this, false, false, true);
697 SplitCriticalEdge(BI, 1, this, false, false, true);
700 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
701 /// condition in it (a cond branch from its header block to its latch block,
702 /// where the path through the loop that doesn't execute its body has no
703 /// side-effects), unswitch it. This doesn't involve any code duplication, just
704 /// moving the conditional branch outside of the loop and updating loop info.
705 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
707 BasicBlock *ExitBlock) {
708 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
709 << loopHeader->getName() << " [" << L->getBlocks().size()
710 << " blocks] in Function " << L->getHeader()->getParent()->getName()
711 << " on cond: " << *Val << " == " << *Cond << "\n");
713 // First step, split the preheader, so that we know that there is a safe place
714 // to insert the conditional branch. We will change loopPreheader to have a
715 // conditional branch on Cond.
716 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
718 // Now that we have a place to insert the conditional branch, create a place
719 // to branch to: this is the exit block out of the loop that we should
722 // Split this block now, so that the loop maintains its exit block, and so
723 // that the jump from the preheader can execute the contents of the exit block
724 // without actually branching to it (the exit block should be dominated by the
725 // loop header, not the preheader).
726 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
727 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
729 // Okay, now we have a position to branch from and a position to branch to,
730 // insert the new conditional branch.
731 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
732 loopPreheader->getTerminator());
733 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
734 loopPreheader->getTerminator()->eraseFromParent();
736 // We need to reprocess this loop, it could be unswitched again.
739 // Now that we know that the loop is never entered when this condition is a
740 // particular value, rewrite the loop with this info. We know that this will
741 // at least eliminate the old branch.
742 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
746 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
747 /// blocks. Update the appropriate Phi nodes as we do so.
748 void LoopUnswitch::SplitExitEdges(Loop *L,
749 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
751 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
752 BasicBlock *ExitBlock = ExitBlocks[i];
753 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
754 pred_end(ExitBlock));
756 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
757 // general, if we call it on all predecessors of all exits then it does.
758 if (!ExitBlock->isLandingPad()) {
759 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
761 SmallVector<BasicBlock*, 2> NewBBs;
762 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
768 /// UnswitchNontrivialCondition - We determined that the loop is profitable
769 /// to unswitch when LIC equal Val. Split it into loop versions and test the
770 /// condition outside of either loop. Return the loops created as Out1/Out2.
771 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
773 Function *F = loopHeader->getParent();
774 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
775 << loopHeader->getName() << " [" << L->getBlocks().size()
776 << " blocks] in Function " << F->getName()
777 << " when '" << *Val << "' == " << *LIC << "\n");
779 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
785 // First step, split the preheader and exit blocks, and add these blocks to
786 // the LoopBlocks list.
787 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
788 LoopBlocks.push_back(NewPreheader);
790 // We want the loop to come after the preheader, but before the exit blocks.
791 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
793 SmallVector<BasicBlock*, 8> ExitBlocks;
794 L->getUniqueExitBlocks(ExitBlocks);
796 // Split all of the edges from inside the loop to their exit blocks. Update
797 // the appropriate Phi nodes as we do so.
798 SplitExitEdges(L, ExitBlocks);
800 // The exit blocks may have been changed due to edge splitting, recompute.
802 L->getUniqueExitBlocks(ExitBlocks);
804 // Add exit blocks to the loop blocks.
805 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
807 // Next step, clone all of the basic blocks that make up the loop (including
808 // the loop preheader and exit blocks), keeping track of the mapping between
809 // the instructions and blocks.
810 NewBlocks.reserve(LoopBlocks.size());
811 ValueToValueMapTy VMap;
812 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
813 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
815 NewBlocks.push_back(NewBB);
816 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
817 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
820 // Splice the newly inserted blocks into the function right before the
821 // original preheader.
822 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
823 NewBlocks[0], F->end());
825 // Now we create the new Loop object for the versioned loop.
826 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
828 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
829 // Probably clone more loop-unswitch related loop properties.
830 BranchesInfo.cloneData(NewLoop, L, VMap);
832 Loop *ParentLoop = L->getParentLoop();
834 // Make sure to add the cloned preheader and exit blocks to the parent loop
836 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
839 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
840 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
841 // The new exit block should be in the same loop as the old one.
842 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
843 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
845 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
846 "Exit block should have been split to have one successor!");
847 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
849 // If the successor of the exit block had PHI nodes, add an entry for
851 for (BasicBlock::iterator I = ExitSucc->begin();
852 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
853 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
854 ValueToValueMapTy::iterator It = VMap.find(V);
855 if (It != VMap.end()) V = It->second;
856 PN->addIncoming(V, NewExit);
859 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
860 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
861 ExitSucc->getFirstInsertionPt());
863 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
866 LandingPadInst *LPI = BB->getLandingPadInst();
867 LPI->replaceAllUsesWith(PN);
868 PN->addIncoming(LPI, BB);
873 // Rewrite the code to refer to itself.
874 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
875 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
876 E = NewBlocks[i]->end(); I != E; ++I)
877 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
879 // Rewrite the original preheader to select between versions of the loop.
880 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
881 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
882 "Preheader splitting did not work correctly!");
884 // Emit the new branch that selects between the two versions of this loop.
885 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
886 LPM->deleteSimpleAnalysisValue(OldBR, L);
887 OldBR->eraseFromParent();
889 LoopProcessWorklist.push_back(NewLoop);
892 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
893 // deletes the instruction (for example by simplifying a PHI that feeds into
894 // the condition that we're unswitching on), we don't rewrite the second
896 WeakVH LICHandle(LIC);
898 // Now we rewrite the original code to know that the condition is true and the
899 // new code to know that the condition is false.
900 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
902 // It's possible that simplifying one loop could cause the other to be
903 // changed to another value or a constant. If its a constant, don't simplify
905 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
906 LICHandle && !isa<Constant>(LICHandle))
907 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
910 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
912 static void RemoveFromWorklist(Instruction *I,
913 std::vector<Instruction*> &Worklist) {
915 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
919 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
920 /// program, replacing all uses with V and update the worklist.
921 static void ReplaceUsesOfWith(Instruction *I, Value *V,
922 std::vector<Instruction*> &Worklist,
923 Loop *L, LPPassManager *LPM) {
924 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
926 // Add uses to the worklist, which may be dead now.
927 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
928 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
929 Worklist.push_back(Use);
931 // Add users to the worklist which may be simplified now.
932 for (User *U : I->users())
933 Worklist.push_back(cast<Instruction>(U));
934 LPM->deleteSimpleAnalysisValue(I, L);
935 RemoveFromWorklist(I, Worklist);
936 I->replaceAllUsesWith(V);
937 I->eraseFromParent();
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();
961 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
962 // in the loop with the appropriate one directly.
963 if (IsEqual || (isa<ConstantInt>(Val) &&
964 Val->getType()->isIntegerTy(1))) {
969 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
970 !cast<ConstantInt>(Val)->getZExtValue());
972 for (User *U : LIC->users()) {
973 Instruction *UI = dyn_cast<Instruction>(U);
974 if (!UI || !L->contains(UI))
976 Worklist.push_back(UI);
979 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
980 UE = Worklist.end(); UI != UE; ++UI)
981 (*UI)->replaceUsesOfWith(LIC, Replacement);
983 SimplifyCode(Worklist, L);
987 // Otherwise, we don't know the precise value of LIC, but we do know that it
988 // is certainly NOT "Val". As such, simplify any uses in the loop that we
989 // can. This case occurs when we unswitch switch statements.
990 for (User *U : LIC->users()) {
991 Instruction *UI = dyn_cast<Instruction>(U);
992 if (!UI || !L->contains(UI))
995 Worklist.push_back(UI);
997 // TODO: We could do other simplifications, for example, turning
998 // 'icmp eq LIC, Val' -> false.
1000 // If we know that LIC is not Val, use this info to simplify code.
1001 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1002 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
1004 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1005 // Default case is live for multiple values.
1006 if (DeadCase == SI->case_default()) continue;
1008 // Found a dead case value. Don't remove PHI nodes in the
1009 // successor if they become single-entry, those PHI nodes may
1010 // be in the Users list.
1012 BasicBlock *Switch = SI->getParent();
1013 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1014 BasicBlock *Latch = L->getLoopLatch();
1016 BranchesInfo.setUnswitched(SI, Val);
1018 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1019 // If the DeadCase successor dominates the loop latch, then the
1020 // transformation isn't safe since it will delete the sole predecessor edge
1022 if (Latch && DT->dominates(SISucc, Latch))
1025 // FIXME: This is a hack. We need to keep the successor around
1026 // and hooked up so as to preserve the loop structure, because
1027 // trying to update it is complicated. So instead we preserve the
1028 // loop structure and put the block on a dead code path.
1029 SplitEdge(Switch, SISucc, this);
1030 // Compute the successors instead of relying on the return value
1031 // of SplitEdge, since it may have split the switch successor
1033 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1034 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1035 // Create an "unreachable" destination.
1036 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1037 Switch->getParent(),
1039 new UnreachableInst(Context, Abort);
1040 // Force the new case destination to branch to the "unreachable"
1041 // block while maintaining a (dead) CFG edge to the old block.
1042 NewSISucc->getTerminator()->eraseFromParent();
1043 BranchInst::Create(Abort, OldSISucc,
1044 ConstantInt::getTrue(Context), NewSISucc);
1045 // Release the PHI operands for this edge.
1046 for (BasicBlock::iterator II = NewSISucc->begin();
1047 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1048 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1049 UndefValue::get(PN->getType()));
1050 // Tell the domtree about the new block. We don't fully update the
1051 // domtree here -- instead we force it to do a full recomputation
1052 // after the pass is complete -- but we do need to inform it of
1055 DT->addNewBlock(Abort, NewSISucc);
1058 SimplifyCode(Worklist, L);
1061 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1062 /// loop, walk over it and constant prop, dce, and fold control flow where
1063 /// possible. Note that this is effectively a very simple loop-structure-aware
1064 /// optimizer. During processing of this loop, L could very well be deleted, so
1065 /// it must not be used.
1067 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1070 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1071 while (!Worklist.empty()) {
1072 Instruction *I = Worklist.back();
1073 Worklist.pop_back();
1076 if (isInstructionTriviallyDead(I)) {
1077 DEBUG(dbgs() << "Remove dead instruction '" << *I);
1079 // Add uses to the worklist, which may be dead now.
1080 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1081 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1082 Worklist.push_back(Use);
1083 LPM->deleteSimpleAnalysisValue(I, L);
1084 RemoveFromWorklist(I, Worklist);
1085 I->eraseFromParent();
1090 // See if instruction simplification can hack this up. This is common for
1091 // things like "select false, X, Y" after unswitching made the condition be
1092 // 'false'. TODO: update the domtree properly so we can pass it here.
1093 if (Value *V = SimplifyInstruction(I))
1094 if (LI->replacementPreservesLCSSAForm(I, V)) {
1095 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1099 // Special case hacks that appear commonly in unswitched code.
1100 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1101 if (BI->isUnconditional()) {
1102 // If BI's parent is the only pred of the successor, fold the two blocks
1104 BasicBlock *Pred = BI->getParent();
1105 BasicBlock *Succ = BI->getSuccessor(0);
1106 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1107 if (!SinglePred) continue; // Nothing to do.
1108 assert(SinglePred == Pred && "CFG broken");
1110 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1111 << Succ->getName() << "\n");
1113 // Resolve any single entry PHI nodes in Succ.
1114 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1115 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1117 // If Succ has any successors with PHI nodes, update them to have
1118 // entries coming from Pred instead of Succ.
1119 Succ->replaceAllUsesWith(Pred);
1121 // Move all of the successor contents from Succ to Pred.
1122 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1124 LPM->deleteSimpleAnalysisValue(BI, L);
1125 BI->eraseFromParent();
1126 RemoveFromWorklist(BI, Worklist);
1128 // Remove Succ from the loop tree.
1129 LI->removeBlock(Succ);
1130 LPM->deleteSimpleAnalysisValue(Succ, L);
1131 Succ->eraseFromParent();