1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
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 file implements Loop Index Splitting Pass. This pass handles three
13 // [1] Loop is eliminated when loop body is executed only once. For example,
14 // for (i = 0; i < N; ++i) {
20 // [2] Loop's iteration space is shrunk if loop body is executed for certain
21 // range only. For example,
23 // for (i = 0; i < N; ++i) {
24 // if ( i > A && i < B) {
28 // is trnasformed to iterators from A to B, if A > 0 and B < N.
30 // [3] Loop is split if the loop body is dominated by an branch. For example,
32 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
34 // is transformed into
36 // for (i = LB; i < min(UB, AEV); ++i)
38 // for (i = max(LB, BSV); i < UB; ++i);
40 //===----------------------------------------------------------------------===//
42 #define DEBUG_TYPE "loop-index-split"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Analysis/LoopPass.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/Dominators.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
56 STATISTIC(NumIndexSplit, "Number of loop index split");
57 STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
58 STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
62 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
65 static char ID; // Pass ID, replacement for typeid
66 LoopIndexSplit() : LoopPass(&ID) {}
68 // Index split Loop L. Return true if loop is split.
69 bool runOnLoop(Loop *L, LPPassManager &LPM);
71 void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<ScalarEvolution>();
73 AU.addPreserved<ScalarEvolution>();
74 AU.addRequiredID(LCSSAID);
75 AU.addPreservedID(LCSSAID);
76 AU.addRequired<LoopInfo>();
77 AU.addPreserved<LoopInfo>();
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addPreservedID(LoopSimplifyID);
80 AU.addRequired<DominatorTree>();
81 AU.addRequired<DominanceFrontier>();
82 AU.addPreserved<DominatorTree>();
83 AU.addPreserved<DominanceFrontier>();
87 /// processOneIterationLoop -- Eliminate loop if loop body is executed
88 /// only once. For example,
89 /// for (i = 0; i < N; ++i) {
95 bool processOneIterationLoop();
97 // -- Routines used by updateLoopIterationSpace();
99 /// updateLoopIterationSpace -- Update loop's iteration space if loop
100 /// body is executed for certain IV range only. For example,
102 /// for (i = 0; i < N; ++i) {
103 /// if ( i > A && i < B) {
107 /// is transformed to iterators from A to B, if A > 0 and B < N.
109 bool updateLoopIterationSpace();
111 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
112 /// with a loop invariant value. Update loop's lower and upper bound based on
113 /// the loop invariant value.
114 bool restrictLoopBound(ICmpInst &Op);
116 // --- Routines used by splitLoop(). --- /
120 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
121 /// DeadBB. This routine is used to remove split condition's dead branch,
122 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
123 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
125 /// moveExitCondition - Move exit condition EC into split condition block.
126 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
127 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
128 PHINode *IV, Instruction *IVAdd, Loop *LP,
131 /// updatePHINodes - CFG has been changed.
133 /// - ExitBB's single predecessor was Latch
134 /// - Latch's second successor was Header
136 /// - ExitBB's single predecessor was Header
137 /// - Latch's one and only successor was Header
139 /// Update ExitBB PHINodes' to reflect this change.
140 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
142 PHINode *IV, Instruction *IVIncrement, Loop *LP);
144 // --- Utility routines --- /
146 /// cleanBlock - A block is considered clean if all non terminal
147 /// instructions are either PHINodes or IV based values.
148 bool cleanBlock(BasicBlock *BB);
150 /// IVisLT - If Op is comparing IV based value with an loop invariant and
151 /// IV based value is less than the loop invariant then return the loop
152 /// invariant. Otherwise return NULL.
153 Value * IVisLT(ICmpInst &Op);
155 /// IVisLE - If Op is comparing IV based value with an loop invariant and
156 /// IV based value is less than or equal to the loop invariant then
157 /// return the loop invariant. Otherwise return NULL.
158 Value * IVisLE(ICmpInst &Op);
160 /// IVisGT - If Op is comparing IV based value with an loop invariant and
161 /// IV based value is greater than the loop invariant then return the loop
162 /// invariant. Otherwise return NULL.
163 Value * IVisGT(ICmpInst &Op);
165 /// IVisGE - If Op is comparing IV based value with an loop invariant and
166 /// IV based value is greater than or equal to the loop invariant then
167 /// return the loop invariant. Otherwise return NULL.
168 Value * IVisGE(ICmpInst &Op);
172 // Current Loop information.
178 DominanceFrontier *DF;
181 ICmpInst *ExitCondition;
182 ICmpInst *SplitCondition;
185 Instruction *IVIncrement;
186 SmallPtrSet<Value *, 4> IVBasedValues;
190 char LoopIndexSplit::ID = 0;
191 static RegisterPass<LoopIndexSplit>
192 X("loop-index-split", "Index Split Loops");
194 Pass *llvm::createLoopIndexSplitPass() {
195 return new LoopIndexSplit();
198 // Index split Loop L. Return true if loop is split.
199 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
203 // FIXME - Nested loops make dominator info updates tricky.
204 if (!L->getSubLoops().empty())
207 SE = &getAnalysis<ScalarEvolution>();
208 DT = &getAnalysis<DominatorTree>();
209 LI = &getAnalysis<LoopInfo>();
210 DF = &getAnalysis<DominanceFrontier>();
212 // Initialize loop data.
213 IndVar = L->getCanonicalInductionVariable();
214 if (!IndVar) return false;
216 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
217 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
218 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
219 if (!IVIncrement) return false;
221 IVBasedValues.clear();
222 IVBasedValues.insert(IndVar);
223 IVBasedValues.insert(IVIncrement);
224 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
226 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
229 if (BO != IVIncrement
230 && (BO->getOpcode() == Instruction::Add
231 || BO->getOpcode() == Instruction::Sub))
232 if (IVBasedValues.count(BO->getOperand(0))
233 && L->isLoopInvariant(BO->getOperand(1)))
234 IVBasedValues.insert(BO);
237 // Reject loop if loop exit condition is not suitable.
238 SmallVector<BasicBlock *, 2> EBs;
239 L->getExitingBlocks(EBs);
242 BranchInst *EBR = dyn_cast<BranchInst>(EBs[0]->getTerminator());
243 if (!EBR) return false;
244 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
245 if (!ExitCondition) return false;
246 if (EBs[0] != L->getLoopLatch()) return false;
247 IVExitValue = ExitCondition->getOperand(1);
248 if (!L->isLoopInvariant(IVExitValue))
249 IVExitValue = ExitCondition->getOperand(0);
250 if (!L->isLoopInvariant(IVExitValue))
253 // If start value is more then exit value where induction variable
254 // increments by 1 then we are potentially dealing with an infinite loop.
255 // Do not index split this loop.
256 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
257 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
258 if (SV->getSExtValue() > EV->getSExtValue())
261 if (processOneIterationLoop())
264 if (updateLoopIterationSpace())
273 // --- Helper routines ---
274 // isUsedOutsideLoop - Returns true iff V is used outside the loop L.
275 static bool isUsedOutsideLoop(Value *V, Loop *L) {
276 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
277 if (!L->contains(cast<Instruction>(*UI)->getParent()))
283 static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
284 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
285 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
289 static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
290 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
291 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
294 // Return min(V1, V1)
295 static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
297 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
298 V1, V2, "lsp", InsertPt);
299 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
302 // Return max(V1, V2)
303 static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
305 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
306 V1, V2, "lsp", InsertPt);
307 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
310 /// processOneIterationLoop -- Eliminate loop if loop body is executed
311 /// only once. For example,
312 /// for (i = 0; i < N; ++i) {
318 bool LoopIndexSplit::processOneIterationLoop() {
319 SplitCondition = NULL;
320 BasicBlock *Latch = L->getLoopLatch();
321 BasicBlock *Header = L->getHeader();
322 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
323 if (!BR) return false;
324 if (!isa<BranchInst>(Latch->getTerminator())) return false;
325 if (BR->isUnconditional()) return false;
326 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
327 if (!SplitCondition) return false;
328 if (SplitCondition == ExitCondition) return false;
329 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
330 if (BR->getOperand(1) != Latch) return false;
331 if (!IVBasedValues.count(SplitCondition->getOperand(0))
332 && !IVBasedValues.count(SplitCondition->getOperand(1)))
335 // If IV is used outside the loop then this loop traversal is required.
336 // FIXME: Calculate and use last IV value.
337 if (isUsedOutsideLoop(IVIncrement, L))
340 // If BR operands are not IV or not loop invariants then skip this loop.
341 Value *OPV = SplitCondition->getOperand(0);
342 Value *SplitValue = SplitCondition->getOperand(1);
343 if (!L->isLoopInvariant(SplitValue)) {
344 Value *T = SplitValue;
348 if (!L->isLoopInvariant(SplitValue))
350 Instruction *OPI = dyn_cast<Instruction>(OPV);
351 if (!OPI) return false;
352 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
355 if (!cleanBlock(Header))
358 if (!cleanBlock(Latch))
361 // If the merge point for BR is not loop latch then skip this loop.
362 if (BR->getSuccessor(0) != Latch) {
363 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
364 assert (DF0 != DF->end() && "Unable to find dominance frontier");
365 if (!DF0->second.count(Latch))
369 if (BR->getSuccessor(1) != Latch) {
370 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
371 assert (DF1 != DF->end() && "Unable to find dominance frontier");
372 if (!DF1->second.count(Latch))
376 // Now, Current loop L contains compare instruction
377 // that compares induction variable, IndVar, against loop invariant. And
378 // entire (i.e. meaningful) loop body is dominated by this compare
379 // instruction. In such case eliminate
380 // loop structure surrounding this loop body. For example,
381 // for (int i = start; i < end; ++i) {
382 // if ( i == somevalue) {
386 // can be transformed into
387 // if (somevalue >= start && somevalue < end) {
392 // Replace index variable with split value in loop body. Loop body is executed
393 // only when index variable is equal to split value.
394 IndVar->replaceAllUsesWith(SplitValue);
396 // Replace split condition in header.
398 // SplitCondition : icmp eq i32 IndVar, SplitValue
400 // c1 = icmp uge i32 SplitValue, StartValue
401 // c2 = icmp ult i32 SplitValue, ExitValue
403 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
404 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
405 SplitValue, IVStartValue, "lisplit", BR);
407 CmpInst::Predicate C2P = ExitCondition->getPredicate();
408 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
409 if (LatchBR->getOperand(0) != Header)
410 C2P = CmpInst::getInversePredicate(C2P);
411 Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
412 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
414 SplitCondition->replaceAllUsesWith(NSplitCond);
415 SplitCondition->eraseFromParent();
417 // Remove Latch to Header edge.
418 BasicBlock *LatchSucc = NULL;
419 Header->removePredecessor(Latch);
420 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
425 LatchBR->setUnconditionalDest(LatchSucc);
427 // Remove IVIncrement
428 IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
429 IVIncrement->eraseFromParent();
431 LPM->deleteLoopFromQueue(L);
433 // Update Dominator Info.
434 // Only CFG change done is to remove Latch to Header edge. This
435 // does not change dominator tree because Latch did not dominate
438 DominanceFrontier::iterator HeaderDF = DF->find(Header);
439 if (HeaderDF != DF->end())
440 DF->removeFromFrontier(HeaderDF, Header);
442 DominanceFrontier::iterator LatchDF = DF->find(Latch);
443 if (LatchDF != DF->end())
444 DF->removeFromFrontier(LatchDF, Header);
447 ++NumIndexSplitRemoved;
451 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
452 /// with a loop invariant value. Update loop's lower and upper bound based on
453 /// the loop invariant value.
454 bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
455 bool Sign = Op.isSignedPredicate();
456 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
458 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
460 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
461 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
462 BasicBlock *T = EBR->getSuccessor(0);
463 EBR->setSuccessor(0, EBR->getSuccessor(1));
464 EBR->setSuccessor(1, T);
467 // New upper and lower bounds.
470 if (Value *V = IVisLT(Op)) {
471 // Restrict upper bound.
472 if (IVisLE(*ExitCondition))
473 V = getMinusOne(V, Sign, PHTerm);
474 NUB = getMin(V, IVExitValue, Sign, PHTerm);
475 } else if (Value *V = IVisLE(Op)) {
476 // Restrict upper bound.
477 if (IVisLT(*ExitCondition))
478 V = getPlusOne(V, Sign, PHTerm);
479 NUB = getMin(V, IVExitValue, Sign, PHTerm);
480 } else if (Value *V = IVisGT(Op)) {
481 // Restrict lower bound.
482 V = getPlusOne(V, Sign, PHTerm);
483 NLB = getMax(V, IVStartValue, Sign, PHTerm);
484 } else if (Value *V = IVisGE(Op))
485 // Restrict lower bound.
486 NLB = getMax(V, IVStartValue, Sign, PHTerm);
492 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
493 IndVar->setIncomingValue(i, NLB);
497 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
498 ExitCondition->setOperand(i, NUB);
503 /// updateLoopIterationSpace -- Update loop's iteration space if loop
504 /// body is executed for certain IV range only. For example,
506 /// for (i = 0; i < N; ++i) {
507 /// if ( i > A && i < B) {
511 /// is transformed to iterators from A to B, if A > 0 and B < N.
513 bool LoopIndexSplit::updateLoopIterationSpace() {
514 SplitCondition = NULL;
515 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
516 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
518 BasicBlock *Latch = L->getLoopLatch();
519 BasicBlock *Header = L->getHeader();
520 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
521 if (!BR) return false;
522 if (!isa<BranchInst>(Latch->getTerminator())) return false;
523 if (BR->isUnconditional()) return false;
524 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
525 if (!AND) return false;
526 if (AND->getOpcode() != Instruction::And) return false;
527 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
528 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
531 IVBasedValues.insert(AND);
532 IVBasedValues.insert(Op0);
533 IVBasedValues.insert(Op1);
534 if (!cleanBlock(Header)) return false;
535 BasicBlock *ExitingBlock = ExitCondition->getParent();
536 if (!cleanBlock(ExitingBlock)) return false;
538 // Verify that loop exiting block has only two predecessor, where one pred
539 // is split condition block. The other predecessor will become exiting block's
540 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
541 // more then two predecessors. This requires extra work in updating dominator
543 BasicBlock *ExitingBBPred = NULL;
544 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
546 BasicBlock *BB = *PI;
555 if (!restrictLoopBound(*Op0))
558 if (!restrictLoopBound(*Op1))
562 if (BR->getSuccessor(0) == ExitingBlock)
563 BR->setUnconditionalDest(BR->getSuccessor(1));
565 BR->setUnconditionalDest(BR->getSuccessor(0));
567 AND->eraseFromParent();
568 if (Op0->use_empty())
569 Op0->eraseFromParent();
570 if (Op1->use_empty())
571 Op1->eraseFromParent();
573 // Update domiantor info. Now, ExitingBlock has only one predecessor,
574 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
575 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
577 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
578 if (L->contains(ExitBlock))
579 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
581 // If ExitingBlock is a member of the loop basic blocks' DF list then
582 // replace ExitingBlock with header and exit block in the DF list
583 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
584 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
587 if (BB == Header || BB == ExitingBlock)
589 DominanceFrontier::iterator BBDF = DF->find(BB);
590 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
591 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
592 while (DomSetI != DomSetE) {
593 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
595 BasicBlock *DFBB = *CurrentItr;
596 if (DFBB == ExitingBlock) {
597 BBDF->second.erase(DFBB);
598 for (DominanceFrontier::DomSetType::iterator
599 EBI = ExitingBlockDF->second.begin(),
600 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
601 BBDF->second.insert(*EBI);
609 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
610 /// This routine is used to remove split condition's dead branch, dominated by
611 /// DeadBB. LiveBB dominates split conidition's other branch.
612 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
613 BasicBlock *LiveBB) {
615 // First update DeadBB's dominance frontier.
616 SmallVector<BasicBlock *, 8> FrontierBBs;
617 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
618 if (DeadBBDF != DF->end()) {
619 SmallVector<BasicBlock *, 8> PredBlocks;
621 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
622 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
623 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
625 BasicBlock *FrontierBB = *DeadBBSetI;
626 FrontierBBs.push_back(FrontierBB);
628 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
630 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
633 if (P == DeadBB || DT->dominates(DeadBB, P))
634 PredBlocks.push_back(P);
637 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
639 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
640 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
641 PE = PredBlocks.end(); PI != PE; ++PI) {
643 PN->removeIncomingValue(P);
652 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
653 SmallVector<BasicBlock *, 32> WorkList;
654 DomTreeNode *DN = DT->getNode(DeadBB);
655 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
656 E = df_end(DN); DI != E; ++DI) {
657 BasicBlock *BB = DI->getBlock();
658 WorkList.push_back(BB);
659 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
662 while (!WorkList.empty()) {
663 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
664 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
666 Instruction *I = BBI;
668 I->replaceAllUsesWith(UndefValue::get(I->getType()));
669 I->eraseFromParent();
671 LPM->deleteSimpleAnalysisValue(BB, LP);
675 BB->eraseFromParent();
678 // Update Frontier BBs' dominator info.
679 while (!FrontierBBs.empty()) {
680 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
681 BasicBlock *NewDominator = FBB->getSinglePredecessor();
683 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
686 if (NewDominator != LiveBB) {
687 for(; PI != PE; ++PI) {
690 NewDominator = LiveBB;
693 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
697 assert (NewDominator && "Unable to fix dominator info.");
698 DT->changeImmediateDominator(FBB, NewDominator);
699 DF->changeImmediateDominator(FBB, NewDominator, DT);
704 // moveExitCondition - Move exit condition EC into split condition block CondBB.
705 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
706 BasicBlock *ExitBB, ICmpInst *EC,
707 ICmpInst *SC, PHINode *IV,
708 Instruction *IVAdd, Loop *LP,
709 unsigned ExitValueNum) {
711 BasicBlock *ExitingBB = EC->getParent();
712 Instruction *CurrentBR = CondBB->getTerminator();
714 // Move exit condition into split condition block.
715 EC->moveBefore(CurrentBR);
716 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
718 // Move exiting block's branch into split condition block. Update its branch
720 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
721 ExitingBR->moveBefore(CurrentBR);
722 BasicBlock *OrigDestBB = NULL;
723 if (ExitingBR->getSuccessor(0) == ExitBB) {
724 OrigDestBB = ExitingBR->getSuccessor(1);
725 ExitingBR->setSuccessor(1, ActiveBB);
728 OrigDestBB = ExitingBR->getSuccessor(0);
729 ExitingBR->setSuccessor(0, ActiveBB);
732 // Remove split condition and current split condition branch.
733 SC->eraseFromParent();
734 CurrentBR->eraseFromParent();
736 // Connect exiting block to original destination.
737 BranchInst::Create(OrigDestBB, ExitingBB);
740 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
742 // Fix dominator info.
743 // ExitBB is now dominated by CondBB
744 DT->changeImmediateDominator(ExitBB, CondBB);
745 DF->changeImmediateDominator(ExitBB, CondBB, DT);
747 // Basicblocks dominated by ActiveBB may have ExitingBB or
748 // a basic block outside the loop in their DF list. If so,
749 // replace it with CondBB.
750 DomTreeNode *Node = DT->getNode(ActiveBB);
751 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
753 BasicBlock *BB = DI->getBlock();
754 DominanceFrontier::iterator BBDF = DF->find(BB);
755 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
756 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
757 while (DomSetI != DomSetE) {
758 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
760 BasicBlock *DFBB = *CurrentItr;
761 if (DFBB == ExitingBB || !L->contains(DFBB)) {
762 BBDF->second.erase(DFBB);
763 BBDF->second.insert(CondBB);
769 /// updatePHINodes - CFG has been changed.
771 /// - ExitBB's single predecessor was Latch
772 /// - Latch's second successor was Header
774 /// - ExitBB's single predecessor is Header
775 /// - Latch's one and only successor is Header
777 /// Update ExitBB PHINodes' to reflect this change.
778 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
780 PHINode *IV, Instruction *IVIncrement,
783 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
785 PHINode *PN = dyn_cast<PHINode>(BI);
790 Value *V = PN->getIncomingValueForBlock(Latch);
791 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
792 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
793 // in Header which is new incoming value for PN.
795 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
797 if (PHINode *U = dyn_cast<PHINode>(*UI))
798 if (LP->contains(U->getParent())) {
803 // Add incoming value from header only if PN has any use inside the loop.
805 PN->addIncoming(NewV, Header);
807 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
808 // If this instruction is IVIncrement then IV is new incoming value
809 // from header otherwise this instruction must be incoming value from
810 // header because loop is in LCSSA form.
811 if (PHI == IVIncrement)
812 PN->addIncoming(IV, Header);
814 PN->addIncoming(V, Header);
816 // Otherwise this is an incoming value from header because loop is in
818 PN->addIncoming(V, Header);
820 // Remove incoming value from Latch.
821 PN->removeIncomingValue(Latch);
825 bool LoopIndexSplit::splitLoop() {
826 SplitCondition = NULL;
827 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
828 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
830 BasicBlock *Header = L->getHeader();
831 BasicBlock *Latch = L->getLoopLatch();
832 BranchInst *SBR = NULL; // Split Condition Branch
833 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
834 // If Exiting block includes loop variant instructions then this
835 // loop may not be split safely.
836 BasicBlock *ExitingBlock = ExitCondition->getParent();
837 if (!cleanBlock(ExitingBlock)) return false;
839 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
841 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
842 if (!BR || BR->isUnconditional()) continue;
843 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
844 if (!CI || CI == ExitCondition
845 || CI->getPredicate() == ICmpInst::ICMP_NE
846 || CI->getPredicate() == ICmpInst::ICMP_EQ)
849 // Unable to handle triangle loops at the moment.
850 // In triangle loop, split condition is in header and one of the
851 // the split destination is loop latch. If split condition is EQ
852 // then such loops are already handle in processOneIterationLoop().
854 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
857 // If the block does not dominate the latch then this is not a diamond.
858 // Such loop may not benefit from index split.
859 if (!DT->dominates((*I), Latch))
862 // If split condition branches heads do not have single predecessor,
863 // SplitCondBlock, then is not possible to remove inactive branch.
864 if (!BR->getSuccessor(0)->getSinglePredecessor()
865 || !BR->getSuccessor(1)->getSinglePredecessor())
868 // If the merge point for BR is not loop latch then skip this condition.
869 if (BR->getSuccessor(0) != Latch) {
870 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
871 assert (DF0 != DF->end() && "Unable to find dominance frontier");
872 if (!DF0->second.count(Latch))
876 if (BR->getSuccessor(1) != Latch) {
877 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
878 assert (DF1 != DF->end() && "Unable to find dominance frontier");
879 if (!DF1->second.count(Latch))
890 // If the predicate sign does not match then skip.
891 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
894 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
895 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
896 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
897 if (!L->isLoopInvariant(SplitValue))
899 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
902 // Normalize loop conditions so that it is easier to calculate new loop
904 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
905 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
906 BasicBlock *T = EBR->getSuccessor(0);
907 EBR->setSuccessor(0, EBR->getSuccessor(1));
908 EBR->setSuccessor(1, T);
911 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
912 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
913 BasicBlock *T = SBR->getSuccessor(0);
914 SBR->setSuccessor(0, SBR->getSuccessor(1));
915 SBR->setSuccessor(1, T);
918 //[*] Calculate new loop bounds.
919 Value *AEV = SplitValue;
920 Value *BSV = SplitValue;
921 bool Sign = SplitCondition->isSignedPredicate();
922 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
924 if (IVisLT(*ExitCondition)) {
925 if (IVisLT(*SplitCondition)) {
928 else if (IVisLE(*SplitCondition)) {
929 AEV = getPlusOne(SplitValue, Sign, PHTerm);
930 BSV = getPlusOne(SplitValue, Sign, PHTerm);
932 assert (0 && "Unexpected split condition!");
935 else if (IVisLE(*ExitCondition)) {
936 if (IVisLT(*SplitCondition)) {
937 AEV = getMinusOne(SplitValue, Sign, PHTerm);
939 else if (IVisLE(*SplitCondition)) {
940 BSV = getPlusOne(SplitValue, Sign, PHTerm);
942 assert (0 && "Unexpected split condition!");
945 assert (0 && "Unexpected exit condition!");
947 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
948 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
951 DenseMap<const Value *, Value *> ValueMap;
952 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
955 // [*] ALoop's exiting edge enters BLoop's header.
956 // ALoop's original exit block becomes BLoop's exit block.
957 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
958 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
959 BranchInst *A_ExitInsn =
960 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
961 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
962 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
963 BasicBlock *B_Header = BLoop->getHeader();
964 if (ALoop->contains(B_ExitBlock)) {
965 B_ExitBlock = A_ExitInsn->getSuccessor(0);
966 A_ExitInsn->setSuccessor(0, B_Header);
968 A_ExitInsn->setSuccessor(1, B_Header);
970 // [*] Update ALoop's exit value using new exit value.
971 ExitCondition->setOperand(EVOpNum, AEV);
973 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
974 // original loop's preheader. Add incoming PHINode values from
975 // ALoop's exiting block. Update BLoop header's domiantor info.
977 // Collect inverse map of Header PHINodes.
978 DenseMap<Value *, Value *> InverseMap;
979 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
980 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
981 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
982 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
983 InverseMap[PNClone] = PN;
988 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
989 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
991 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
992 // Remove incoming value from original preheader.
993 PN->removeIncomingValue(A_Preheader);
995 // Add incoming value from A_ExitingBlock.
997 PN->addIncoming(BSV, A_ExitingBlock);
999 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1001 // If loop header is also loop exiting block then
1002 // OrigPN is incoming value for B loop header.
1003 if (A_ExitingBlock == ALoop->getHeader())
1006 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1007 PN->addIncoming(V2, A_ExitingBlock);
1013 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1014 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1016 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1017 // block. Remove incoming PHINode values from ALoop's exiting block.
1018 // Add new incoming values from BLoop's incoming exiting value.
1019 // Update BLoop exit block's dominator info..
1020 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1021 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1023 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1024 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1026 PN->removeIncomingValue(A_ExitingBlock);
1031 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1032 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1034 //[*] Split ALoop's exit edge. This creates a new block which
1035 // serves two purposes. First one is to hold PHINode defnitions
1036 // to ensure that ALoop's LCSSA form. Second use it to act
1037 // as a preheader for BLoop.
1038 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1040 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1041 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1042 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1044 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1045 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1046 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1047 newPHI->addIncoming(V1, A_ExitingBlock);
1048 A_ExitBlock->getInstList().push_front(newPHI);
1049 PN->removeIncomingValue(A_ExitBlock);
1050 PN->addIncoming(newPHI, A_ExitBlock);
1055 //[*] Eliminate split condition's inactive branch from ALoop.
1056 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1057 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1058 BasicBlock *A_InactiveBranch = NULL;
1059 BasicBlock *A_ActiveBranch = NULL;
1060 A_ActiveBranch = A_BR->getSuccessor(0);
1061 A_InactiveBranch = A_BR->getSuccessor(1);
1062 A_BR->setUnconditionalDest(A_ActiveBranch);
1063 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1065 //[*] Eliminate split condition's inactive branch in from BLoop.
1066 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1067 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1068 BasicBlock *B_InactiveBranch = NULL;
1069 BasicBlock *B_ActiveBranch = NULL;
1070 B_ActiveBranch = B_BR->getSuccessor(1);
1071 B_InactiveBranch = B_BR->getSuccessor(0);
1072 B_BR->setUnconditionalDest(B_ActiveBranch);
1073 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1075 BasicBlock *A_Header = ALoop->getHeader();
1076 if (A_ExitingBlock == A_Header)
1079 //[*] Move exit condition into split condition block to avoid
1080 // executing dead loop iteration.
1081 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1082 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1083 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1085 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1086 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1089 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1090 B_ExitBlock, B_ExitCondition,
1091 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1098 /// cleanBlock - A block is considered clean if all non terminal instructions
1099 /// are either, PHINodes, IV based.
1100 bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1101 Instruction *Terminator = BB->getTerminator();
1102 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1104 Instruction *I = BI;
1106 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
1107 || I == SplitCondition || IVBasedValues.count(I))
1110 if (I->mayWriteToMemory())
1113 // I is used only inside this block then it is OK.
1114 bool usedOutsideBB = false;
1115 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1117 Instruction *U = cast<Instruction>(UI);
1118 if (U->getParent() != BB)
1119 usedOutsideBB = true;
1124 // Otherwise we have a instruction that may not allow loop spliting.
1130 /// IVisLT - If Op is comparing IV based value with an loop invariant and
1131 /// IV based value is less than the loop invariant then return the loop
1132 /// invariant. Otherwise return NULL.
1133 Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1134 ICmpInst::Predicate P = Op.getPredicate();
1135 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1136 && IVBasedValues.count(Op.getOperand(0))
1137 && L->isLoopInvariant(Op.getOperand(1)))
1138 return Op.getOperand(1);
1140 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1141 && IVBasedValues.count(Op.getOperand(1))
1142 && L->isLoopInvariant(Op.getOperand(0)))
1143 return Op.getOperand(0);
1148 /// IVisLE - If Op is comparing IV based value with an loop invariant and
1149 /// IV based value is less than or equal to the loop invariant then
1150 /// return the loop invariant. Otherwise return NULL.
1151 Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1152 ICmpInst::Predicate P = Op.getPredicate();
1153 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1154 && IVBasedValues.count(Op.getOperand(0))
1155 && L->isLoopInvariant(Op.getOperand(1)))
1156 return Op.getOperand(1);
1158 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1159 && IVBasedValues.count(Op.getOperand(1))
1160 && L->isLoopInvariant(Op.getOperand(0)))
1161 return Op.getOperand(0);
1166 /// IVisGT - If Op is comparing IV based value with an loop invariant and
1167 /// IV based value is greater than the loop invariant then return the loop
1168 /// invariant. Otherwise return NULL.
1169 Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1170 ICmpInst::Predicate P = Op.getPredicate();
1171 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1172 && IVBasedValues.count(Op.getOperand(0))
1173 && L->isLoopInvariant(Op.getOperand(1)))
1174 return Op.getOperand(1);
1176 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1177 && IVBasedValues.count(Op.getOperand(1))
1178 && L->isLoopInvariant(Op.getOperand(0)))
1179 return Op.getOperand(0);
1184 /// IVisGE - If Op is comparing IV based value with an loop invariant and
1185 /// IV based value is greater than or equal to the loop invariant then
1186 /// return the loop invariant. Otherwise return NULL.
1187 Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1188 ICmpInst::Predicate P = Op.getPredicate();
1189 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1190 && IVBasedValues.count(Op.getOperand(0))
1191 && L->isLoopInvariant(Op.getOperand(1)))
1192 return Op.getOperand(1);
1194 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1195 && IVBasedValues.count(Op.getOperand(1))
1196 && L->isLoopInvariant(Op.getOperand(0)))
1197 return Op.getOperand(0);