1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Index Splitting Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-index-split"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
28 STATISTIC(NumIndexSplit, "Number of loops index split");
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
46 AU.addRequired<LoopInfo>();
47 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
50 AU.addRequired<DominatorTree>();
51 AU.addRequired<DominanceFrontier>();
52 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
60 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
61 UseTrueBranchFirst(true), A_ExitValue(NULL),
64 // Induction variable's range is split at this value.
67 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
70 // True if after loop index split, first loop will execute split condition's
72 bool UseTrueBranchFirst;
74 // Exit value for first loop after loop split.
77 // Start value for second loop after loop split.
83 SplitCondition = NULL;
84 UseTrueBranchFirst = true;
93 // safeIcmpInst - CI is considered safe instruction if one of the operand
94 // is SCEVAddRecExpr based on induction variable and other operand is
95 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
99 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
102 /// Find loop's exit condition.
103 void findLoopConditionals();
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
108 /// processOneIterationLoop - Current loop L contains compare instruction
109 /// that compares induction variable, IndVar, agains loop invariant. If
110 /// entire (i.e. meaningful) loop body is dominated by this compare
111 /// instruction then loop body is executed only for one iteration. In
112 /// such case eliminate loop structure surrounding this loop body. For
113 bool processOneIterationLoop(SplitInfo &SD);
115 /// If loop header includes loop variant instruction operands then
116 /// this loop may not be eliminated.
117 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
119 /// If Exiting block includes loop variant instructions then this
120 /// loop may not be eliminated.
121 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
123 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
124 /// This routine is used to remove split condition's dead branch, dominated by
125 /// DeadBB. LiveBB dominates split conidition's other branch.
126 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
128 /// safeSplitCondition - Return true if it is possible to
129 /// split loop using given split condition.
130 bool safeSplitCondition(SplitInfo &SD);
132 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
133 /// based on split value.
134 void calculateLoopBounds(SplitInfo &SD);
136 /// updatePHINodes - CFG has been changed.
138 /// - ExitBB's single predecessor was Latch
139 /// - Latch's second successor was Header
141 /// - ExitBB's single predecessor was Header
142 /// - Latch's one and only successor was Header
144 /// Update ExitBB PHINodes' to reflect this change.
145 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
147 PHINode *IV, Instruction *IVIncrement);
149 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
150 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
151 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
152 PHINode *IV, Instruction *IVAdd, Loop *LP);
154 /// splitLoop - Split current loop L in two loops using split information
155 /// SD. Update dominator information. Maintain LCSSA form.
156 bool splitLoop(SplitInfo &SD);
160 IndVarIncrement = NULL;
161 ExitCondition = NULL;
175 DominanceFrontier *DF;
176 SmallVector<SplitInfo, 4> SplitData;
178 // Induction variable whose range is being split by this transformation.
180 Instruction *IndVarIncrement;
182 // Loop exit condition.
183 ICmpInst *ExitCondition;
185 // Induction variable's initial value.
188 // Induction variable's final loop exit value operand number in exit condition..
189 unsigned ExitValueNum;
192 char LoopIndexSplit::ID = 0;
193 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
196 LoopPass *llvm::createLoopIndexSplitPass() {
197 return new LoopIndexSplit();
200 // Index split Loop L. Return true if loop is split.
201 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
202 bool Changed = false;
206 // FIXME - Nested loops make dominator info updates tricky.
207 if (!L->getSubLoops().empty())
210 SE = &getAnalysis<ScalarEvolution>();
211 DT = &getAnalysis<DominatorTree>();
212 LI = &getAnalysis<LoopInfo>();
213 DF = &getAnalysis<DominanceFrontier>();
217 findLoopConditionals();
222 findSplitCondition();
224 if (SplitData.empty())
227 // First see if it is possible to eliminate loop itself or not.
228 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
229 E = SplitData.end(); SI != E;) {
231 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
232 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
233 Changed = processOneIterationLoop(SD);
236 // If is loop is eliminated then nothing else to do here.
239 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
241 SplitData.erase(Delete_SI);
247 if (SplitData.empty())
250 // Split most profitiable condition.
251 // FIXME : Implement cost analysis.
252 unsigned MostProfitableSDIndex = 0;
253 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
261 /// Return true if V is a induction variable or induction variable's
262 /// increment for loop L.
263 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
265 Instruction *I = dyn_cast<Instruction>(V);
269 // Check if I is a phi node from loop header or not.
270 if (PHINode *PN = dyn_cast<PHINode>(V)) {
271 if (PN->getParent() == L->getHeader()) {
277 // Check if I is a add instruction whose one operand is
278 // phi node from loop header and second operand is constant.
279 if (I->getOpcode() != Instruction::Add)
282 Value *Op0 = I->getOperand(0);
283 Value *Op1 = I->getOperand(1);
285 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
286 if (PN->getParent() == L->getHeader()
287 && isa<ConstantInt>(Op1)) {
294 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
295 if (PN->getParent() == L->getHeader()
296 && isa<ConstantInt>(Op0)) {
306 // Find loop's exit condition and associated induction variable.
307 void LoopIndexSplit::findLoopConditionals() {
309 BasicBlock *ExitingBlock = NULL;
311 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
314 if (!L->isLoopExit(BB))
324 // If exiting block is neither loop header nor loop latch then this loop is
326 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
329 // If exit block's terminator is conditional branch inst then we have found
331 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
332 if (!BR || BR->isUnconditional())
335 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
340 if (CI->getPredicate() == ICmpInst::ICMP_EQ
341 || CI->getPredicate() == ICmpInst::ICMP_NE)
344 if (CI->getPredicate() == ICmpInst::ICMP_SGT
345 || CI->getPredicate() == ICmpInst::ICMP_UGT
346 || CI->getPredicate() == ICmpInst::ICMP_SGE
347 || CI->getPredicate() == ICmpInst::ICMP_UGE) {
349 BasicBlock *FirstSuccessor = BR->getSuccessor(0);
350 // splitLoop() is expecting LT/LE as exit condition predicate.
351 // Swap operands here if possible to meet this requirement.
352 if (!L->contains(FirstSuccessor))
360 // Exit condition's one operand is loop invariant exit value and second
361 // operand is SCEVAddRecExpr based on induction variable.
362 Value *V0 = CI->getOperand(0);
363 Value *V1 = CI->getOperand(1);
365 SCEVHandle SH0 = SE->getSCEV(V0);
366 SCEVHandle SH1 = SE->getSCEV(V1);
368 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
372 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
378 ExitCondition = NULL;
380 BasicBlock *Preheader = L->getLoopPreheader();
381 StartValue = IndVar->getIncomingValueForBlock(Preheader);
385 /// Find condition inside a loop that is suitable candidate for index split.
386 void LoopIndexSplit::findSplitCondition() {
389 // Check all basic block's terminators.
390 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
395 // If this basic block does not terminate in a conditional branch
396 // then terminator is not a suitable split condition.
397 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
401 if (BR->isUnconditional())
404 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
405 if (!CI || CI == ExitCondition)
408 if (CI->getPredicate() == ICmpInst::ICMP_NE)
411 // If split condition predicate is GT or GE then first execute
412 // false branch of split condition.
413 if (CI->getPredicate() == ICmpInst::ICMP_UGT
414 || CI->getPredicate() == ICmpInst::ICMP_SGT
415 || CI->getPredicate() == ICmpInst::ICMP_UGE
416 || CI->getPredicate() == ICmpInst::ICMP_SGE)
417 SD.UseTrueBranchFirst = false;
419 // If one operand is loop invariant and second operand is SCEVAddRecExpr
420 // based on induction variable then CI is a candidate split condition.
421 if (safeICmpInst(CI, SD))
422 SplitData.push_back(SD);
426 // safeIcmpInst - CI is considered safe instruction if one of the operand
427 // is SCEVAddRecExpr based on induction variable and other operand is
428 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
430 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
432 Value *V0 = CI->getOperand(0);
433 Value *V1 = CI->getOperand(1);
435 SCEVHandle SH0 = SE->getSCEV(V0);
436 SCEVHandle SH1 = SE->getSCEV(V1);
438 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
440 SD.SplitCondition = CI;
441 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
445 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
446 if (IndVarIncrement && IndVarIncrement == Insn)
450 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
452 SD.SplitCondition = CI;
453 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
457 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
458 if (IndVarIncrement && IndVarIncrement == Insn)
466 /// processOneIterationLoop - Current loop L contains compare instruction
467 /// that compares induction variable, IndVar, against loop invariant. If
468 /// entire (i.e. meaningful) loop body is dominated by this compare
469 /// instruction then loop body is executed only once. In such case eliminate
470 /// loop structure surrounding this loop body. For example,
471 /// for (int i = start; i < end; ++i) {
472 /// if ( i == somevalue) {
476 /// can be transformed into
477 /// if (somevalue >= start && somevalue < end) {
481 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
483 BasicBlock *Header = L->getHeader();
485 // First of all, check if SplitCondition dominates entire loop body
488 // If SplitCondition is not in loop header then this loop is not suitable
489 // for this transformation.
490 if (SD.SplitCondition->getParent() != Header)
493 // If loop header includes loop variant instruction operands then
494 // this loop may not be eliminated.
495 if (!safeHeader(SD, Header))
498 // If Exiting block includes loop variant instructions then this
499 // loop may not be eliminated.
500 if (!safeExitingBlock(SD, ExitCondition->getParent()))
505 // Replace index variable with split value in loop body. Loop body is executed
506 // only when index variable is equal to split value.
507 IndVar->replaceAllUsesWith(SD.SplitValue);
509 // Remove Latch to Header edge.
510 BasicBlock *Latch = L->getLoopLatch();
511 BasicBlock *LatchSucc = NULL;
512 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
515 Header->removePredecessor(Latch);
516 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
521 BR->setUnconditionalDest(LatchSucc);
523 Instruction *Terminator = Header->getTerminator();
524 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
526 // Replace split condition in header.
528 // SplitCondition : icmp eq i32 IndVar, SplitValue
530 // c1 = icmp uge i32 SplitValue, StartValue
531 // c2 = icmp ult i32 SplitValue, ExitValue
533 bool SignedPredicate = ExitCondition->isSignedPredicate();
534 Instruction *C1 = new ICmpInst(SignedPredicate ?
535 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
536 SD.SplitValue, StartValue, "lisplit",
538 Instruction *C2 = new ICmpInst(SignedPredicate ?
539 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
540 SD.SplitValue, ExitValue, "lisplit",
542 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
544 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
545 SD.SplitCondition->eraseFromParent();
547 // Now, clear latch block. Remove instructions that are responsible
548 // to increment induction variable.
549 Instruction *LTerminator = Latch->getTerminator();
550 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
554 if (isa<PHINode>(I) || I == LTerminator)
557 if (I == IndVarIncrement)
558 I->replaceAllUsesWith(ExitValue);
560 I->replaceAllUsesWith(UndefValue::get(I->getType()));
561 I->eraseFromParent();
564 LPM->deleteLoopFromQueue(L);
566 // Update Dominator Info.
567 // Only CFG change done is to remove Latch to Header edge. This
568 // does not change dominator tree because Latch did not dominate
571 DominanceFrontier::iterator HeaderDF = DF->find(Header);
572 if (HeaderDF != DF->end())
573 DF->removeFromFrontier(HeaderDF, Header);
575 DominanceFrontier::iterator LatchDF = DF->find(Latch);
576 if (LatchDF != DF->end())
577 DF->removeFromFrontier(LatchDF, Header);
582 // If loop header includes loop variant instruction operands then
583 // this loop can not be eliminated. This is used by processOneIterationLoop().
584 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
586 Instruction *Terminator = Header->getTerminator();
587 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
595 // SplitCondition itself is OK.
596 if (I == SD.SplitCondition)
599 // Induction variable is OK.
603 // Induction variable increment is OK.
604 if (I == IndVarIncrement)
607 // Terminator is also harmless.
611 // Otherwise we have a instruction that may not be safe.
618 // If Exiting block includes loop variant instructions then this
619 // loop may not be eliminated. This is used by processOneIterationLoop().
620 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
621 BasicBlock *ExitingBlock) {
623 for (BasicBlock::iterator BI = ExitingBlock->begin(),
624 BE = ExitingBlock->end(); BI != BE; ++BI) {
631 // Induction variable increment is OK.
632 if (IndVarIncrement && IndVarIncrement == I)
635 // Check if I is induction variable increment instruction.
636 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
638 Value *Op0 = I->getOperand(0);
639 Value *Op1 = I->getOperand(1);
641 ConstantInt *CI = NULL;
643 if ((PN = dyn_cast<PHINode>(Op0))) {
644 if ((CI = dyn_cast<ConstantInt>(Op1)))
647 if ((PN = dyn_cast<PHINode>(Op1))) {
648 if ((CI = dyn_cast<ConstantInt>(Op0)))
652 if (IndVarIncrement && PN == IndVar && CI->isOne())
656 // I is an Exit condition if next instruction is block terminator.
657 // Exit condition is OK if it compares loop invariant exit value,
658 // which is checked below.
659 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
660 if (EC == ExitCondition)
664 if (I == ExitingBlock->getTerminator())
667 // Otherwise we have instruction that may not be safe.
671 // We could not find any reason to consider ExitingBlock unsafe.
675 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
676 /// This routine is used to remove split condition's dead branch, dominated by
677 /// DeadBB. LiveBB dominates split conidition's other branch.
678 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
679 BasicBlock *LiveBB) {
681 // First update DeadBB's dominance frontier.
682 SmallVector<BasicBlock *, 8> FrontierBBs;
683 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
684 if (DeadBBDF != DF->end()) {
685 SmallVector<BasicBlock *, 8> PredBlocks;
687 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
688 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
689 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
690 BasicBlock *FrontierBB = *DeadBBSetI;
691 FrontierBBs.push_back(FrontierBB);
693 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
695 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
698 if (P == DeadBB || DT->dominates(DeadBB, P))
699 PredBlocks.push_back(P);
702 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
704 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
705 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
706 PE = PredBlocks.end(); PI != PE; ++PI) {
708 PN->removeIncomingValue(P);
717 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
718 SmallVector<BasicBlock *, 32> WorkList;
719 DomTreeNode *DN = DT->getNode(DeadBB);
720 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
721 E = df_end(DN); DI != E; ++DI) {
722 BasicBlock *BB = DI->getBlock();
723 WorkList.push_back(BB);
724 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
727 while (!WorkList.empty()) {
728 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
729 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
731 Instruction *I = BBI;
732 I->replaceAllUsesWith(UndefValue::get(I->getType()));
733 I->eraseFromParent();
735 LPM->deleteSimpleAnalysisValue(BB, LP);
739 BB->eraseFromParent();
742 // Update Frontier BBs' dominator info.
743 while (!FrontierBBs.empty()) {
744 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
745 BasicBlock *NewDominator = FBB->getSinglePredecessor();
747 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
750 if (NewDominator != LiveBB) {
751 for(; PI != PE; ++PI) {
754 NewDominator = LiveBB;
757 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
761 assert (NewDominator && "Unable to fix dominator info.");
762 DT->changeImmediateDominator(FBB, NewDominator);
763 DF->changeImmediateDominator(FBB, NewDominator, DT);
768 /// safeSplitCondition - Return true if it is possible to
769 /// split loop using given split condition.
770 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
772 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
774 // Unable to handle triange loops at the moment.
775 // In triangle loop, split condition is in header and one of the
776 // the split destination is loop latch. If split condition is EQ
777 // then such loops are already handle in processOneIterationLoop().
778 BasicBlock *Latch = L->getLoopLatch();
779 BranchInst *SplitTerminator =
780 cast<BranchInst>(SplitCondBlock->getTerminator());
781 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
782 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
783 if (L->getHeader() == SplitCondBlock
784 && (Latch == Succ0 || Latch == Succ1))
787 // If split condition branches heads do not have single predecessor,
788 // SplitCondBlock, then is not possible to remove inactive branch.
789 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
792 // Finally this split condition is safe only if merge point for
793 // split condition branch is loop latch. This check along with previous
794 // check, to ensure that exit condition is in either loop latch or header,
795 // filters all loops with non-empty loop body between merge point
796 // and exit condition.
797 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
798 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
799 if (Succ0DF->second.count(Latch))
802 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
803 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
804 if (Succ1DF->second.count(Latch))
810 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
811 /// based on split value.
812 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
814 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
815 ICmpInst::Predicate SP = SC->getPredicate();
816 const Type *Ty = SD.SplitValue->getType();
817 bool Sign = ExitCondition->isSignedPredicate();
818 BasicBlock *Preheader = L->getLoopPreheader();
819 Instruction *PHTerminator = Preheader->getTerminator();
821 // Initially use split value as upper loop bound for first loop and lower loop
822 // bound for second loop.
823 Value *AEV = SD.SplitValue;
824 Value *BSV = SD.SplitValue;
826 switch (ExitCondition->getPredicate()) {
827 case ICmpInst::ICMP_SGT:
828 case ICmpInst::ICMP_UGT:
829 case ICmpInst::ICMP_SGE:
830 case ICmpInst::ICMP_UGE:
832 assert (0 && "Unexpected exit condition predicate");
834 case ICmpInst::ICMP_SLT:
835 case ICmpInst::ICMP_ULT:
838 case ICmpInst::ICMP_SLT:
839 case ICmpInst::ICMP_ULT:
841 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
843 // is transformed into
845 // for (i = LB; i < min(UB, AEV); ++i)
847 // for (i = max(LB, BSV); i < UB; ++i);
850 case ICmpInst::ICMP_SLE:
851 case ICmpInst::ICMP_ULE:
854 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
856 // is transformed into
860 // for (i = LB; i < min(UB, AEV); ++i)
862 // for (i = max(LB, BSV); i < UB; ++i)
864 BSV = BinaryOperator::createAdd(SD.SplitValue,
865 ConstantInt::get(Ty, 1, Sign),
866 "lsplit.add", PHTerminator);
870 case ICmpInst::ICMP_SGE:
871 case ICmpInst::ICMP_UGE:
873 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
875 // is transformed into
877 // for (i = LB; i < min(UB, AEV); ++i)
879 // for (i = max(BSV, LB); i < UB; ++i)
882 case ICmpInst::ICMP_SGT:
883 case ICmpInst::ICMP_UGT:
886 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
888 // is transformed into
890 // BSV = AEV = SV + 1
891 // for (i = LB; i < min(UB, AEV); ++i)
893 // for (i = max(LB, BSV); i < UB; ++i)
895 BSV = BinaryOperator::createAdd(SD.SplitValue,
896 ConstantInt::get(Ty, 1, Sign),
897 "lsplit.add", PHTerminator);
902 assert (0 && "Unexpected split condition predicate");
907 case ICmpInst::ICMP_SLE:
908 case ICmpInst::ICMP_ULE:
911 case ICmpInst::ICMP_SLT:
912 case ICmpInst::ICMP_ULT:
914 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
916 // is transformed into
919 // for (i = LB; i <= min(UB, AEV); ++i)
921 // for (i = max(LB, BSV); i <= UB; ++i)
923 AEV = BinaryOperator::createSub(SD.SplitValue,
924 ConstantInt::get(Ty, 1, Sign),
925 "lsplit.sub", PHTerminator);
927 case ICmpInst::ICMP_SLE:
928 case ICmpInst::ICMP_ULE:
930 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
932 // is transformed into
935 // for (i = LB; i <= min(UB, AEV); ++i)
937 // for (i = max(LB, BSV); i <= UB; ++i)
939 BSV = BinaryOperator::createAdd(SD.SplitValue,
940 ConstantInt::get(Ty, 1, Sign),
941 "lsplit.add", PHTerminator);
943 case ICmpInst::ICMP_SGT:
944 case ICmpInst::ICMP_UGT:
946 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
948 // is transformed into
951 // for (i = LB; i <= min(AEV, UB); ++i)
953 // for (i = max(LB, BSV); i <= UB; ++i)
955 BSV = BinaryOperator::createAdd(SD.SplitValue,
956 ConstantInt::get(Ty, 1, Sign),
957 "lsplit.add", PHTerminator);
959 case ICmpInst::ICMP_SGE:
960 case ICmpInst::ICMP_UGE:
963 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
965 // is transformed into
968 // for (i = LB; i <= min(AEV, UB); ++i)
970 // for (i = max(LB, BSV); i <= UB; ++i)
972 AEV = BinaryOperator::createSub(SD.SplitValue,
973 ConstantInt::get(Ty, 1, Sign),
974 "lsplit.sub", PHTerminator);
977 assert (0 && "Unexpected split condition predicate");
984 // Calculate ALoop induction variable's new exiting value and
985 // BLoop induction variable's new starting value. Calculuate these
986 // values in original loop's preheader.
987 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
988 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
989 Value *C1 = new ICmpInst(Sign ?
990 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
992 ExitCondition->getOperand(ExitValueNum),
993 "lsplit.ev", PHTerminator);
994 SD.A_ExitValue = new SelectInst(C1, AEV,
995 ExitCondition->getOperand(ExitValueNum),
996 "lsplit.ev", PHTerminator);
998 Value *C2 = new ICmpInst(Sign ?
999 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1000 BSV, StartValue, "lsplit.sv",
1002 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1003 "lsplit.sv", PHTerminator);
1006 /// splitLoop - Split current loop L in two loops using split information
1007 /// SD. Update dominator information. Maintain LCSSA form.
1008 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1010 if (!safeSplitCondition(SD))
1013 // After loop is cloned there are two loops.
1015 // First loop, referred as ALoop, executes first part of loop's iteration
1016 // space split. Second loop, referred as BLoop, executes remaining
1017 // part of loop's iteration space.
1019 // ALoop's exit edge enters BLoop's header through a forwarding block which
1020 // acts as a BLoop's preheader.
1021 BasicBlock *Preheader = L->getLoopPreheader();
1023 // Calculate ALoop induction variable's new exiting value and
1024 // BLoop induction variable's new starting value.
1025 calculateLoopBounds(SD);
1028 DenseMap<const Value *, Value *> ValueMap;
1029 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1031 BasicBlock *B_Header = BLoop->getHeader();
1033 //[*] ALoop's exiting edge BLoop's header.
1034 // ALoop's original exit block becomes BLoop's exit block.
1035 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1036 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1037 BranchInst *A_ExitInsn =
1038 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1039 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1040 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1041 if (L->contains(B_ExitBlock)) {
1042 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1043 A_ExitInsn->setSuccessor(0, B_Header);
1045 A_ExitInsn->setSuccessor(1, B_Header);
1047 //[*] Update ALoop's exit value using new exit value.
1048 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1050 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1051 // original loop's preheader. Add incoming PHINode values from
1052 // ALoop's exiting block. Update BLoop header's domiantor info.
1054 // Collect inverse map of Header PHINodes.
1055 DenseMap<Value *, Value *> InverseMap;
1056 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1057 BE = L->getHeader()->end(); BI != BE; ++BI) {
1058 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1059 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1060 InverseMap[PNClone] = PN;
1065 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1067 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1068 // Remove incoming value from original preheader.
1069 PN->removeIncomingValue(Preheader);
1071 // Add incoming value from A_ExitingBlock.
1073 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1075 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1076 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1077 PN->addIncoming(V2, A_ExitingBlock);
1082 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1083 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1085 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1086 // block. Remove incoming PHINode values from ALoop's exiting block.
1087 // Add new incoming values from BLoop's incoming exiting value.
1088 // Update BLoop exit block's dominator info..
1089 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1090 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1092 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1093 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1095 PN->removeIncomingValue(A_ExitingBlock);
1100 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1101 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1103 //[*] Split ALoop's exit edge. This creates a new block which
1104 // serves two purposes. First one is to hold PHINode defnitions
1105 // to ensure that ALoop's LCSSA form. Second use it to act
1106 // as a preheader for BLoop.
1107 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1109 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1110 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1111 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1113 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1114 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1115 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1116 newPHI->addIncoming(V1, A_ExitingBlock);
1117 A_ExitBlock->getInstList().push_front(newPHI);
1118 PN->removeIncomingValue(A_ExitBlock);
1119 PN->addIncoming(newPHI, A_ExitBlock);
1124 //[*] Eliminate split condition's inactive branch from ALoop.
1125 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1126 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1127 BasicBlock *A_InactiveBranch = NULL;
1128 BasicBlock *A_ActiveBranch = NULL;
1129 if (SD.UseTrueBranchFirst) {
1130 A_ActiveBranch = A_BR->getSuccessor(0);
1131 A_InactiveBranch = A_BR->getSuccessor(1);
1133 A_ActiveBranch = A_BR->getSuccessor(1);
1134 A_InactiveBranch = A_BR->getSuccessor(0);
1136 A_BR->setUnconditionalDest(A_ActiveBranch);
1137 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1139 //[*] Eliminate split condition's inactive branch in from BLoop.
1140 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1141 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1142 BasicBlock *B_InactiveBranch = NULL;
1143 BasicBlock *B_ActiveBranch = NULL;
1144 if (SD.UseTrueBranchFirst) {
1145 B_ActiveBranch = B_BR->getSuccessor(1);
1146 B_InactiveBranch = B_BR->getSuccessor(0);
1148 B_ActiveBranch = B_BR->getSuccessor(0);
1149 B_InactiveBranch = B_BR->getSuccessor(1);
1151 B_BR->setUnconditionalDest(B_ActiveBranch);
1152 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1154 BasicBlock *A_Header = L->getHeader();
1155 if (A_ExitingBlock == A_Header)
1158 //[*] Move exit condition into split condition block to avoid
1159 // executing dead loop iteration.
1160 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1161 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1162 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1164 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1165 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1168 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1169 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1174 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1175 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1176 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1177 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1179 BasicBlock *ExitingBB = EC->getParent();
1180 Instruction *CurrentBR = CondBB->getTerminator();
1182 // Move exit condition into split condition block.
1183 EC->moveBefore(CurrentBR);
1184 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1186 // Move exiting block's branch into split condition block. Update its branch
1188 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1189 ExitingBR->moveBefore(CurrentBR);
1190 if (ExitingBR->getSuccessor(0) == ExitBB)
1191 ExitingBR->setSuccessor(1, ActiveBB);
1193 ExitingBR->setSuccessor(0, ActiveBB);
1195 // Remove split condition and current split condition branch.
1196 SC->eraseFromParent();
1197 CurrentBR->eraseFromParent();
1199 // Connect exiting block to split condition block.
1200 new BranchInst(CondBB, ExitingBB);
1203 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1205 // Fix dominator info.
1206 // ExitBB is now dominated by CondBB
1207 DT->changeImmediateDominator(ExitBB, CondBB);
1208 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1210 // Basicblocks dominated by ActiveBB may have ExitingBB or
1211 // a basic block outside the loop in their DF list. If so,
1212 // replace it with CondBB.
1213 DomTreeNode *Node = DT->getNode(ActiveBB);
1214 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1216 BasicBlock *BB = DI->getBlock();
1217 DominanceFrontier::iterator BBDF = DF->find(BB);
1218 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1219 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1220 while (DomSetI != DomSetE) {
1221 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1223 BasicBlock *DFBB = *CurrentItr;
1224 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1225 BBDF->second.erase(DFBB);
1226 BBDF->second.insert(CondBB);
1232 /// updatePHINodes - CFG has been changed.
1234 /// - ExitBB's single predecessor was Latch
1235 /// - Latch's second successor was Header
1237 /// - ExitBB's single predecessor was Header
1238 /// - Latch's one and only successor was Header
1240 /// Update ExitBB PHINodes' to reflect this change.
1241 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1243 PHINode *IV, Instruction *IVIncrement) {
1245 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1247 PHINode *PN = dyn_cast<PHINode>(BI);
1251 Value *V = PN->getIncomingValueForBlock(Latch);
1252 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1253 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1255 // The second use is in Header and it is new incoming value for PN.
1259 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1262 U1 = cast<PHINode>(*UI);
1264 U2 = cast<PHINode>(*UI);
1266 assert ( 0 && "Unexpected third use of this PHINode");
1268 assert (U1 && U2 && "Unable to find two uses");
1270 if (U1->getParent() == Header)
1274 PN->addIncoming(NewV, Header);
1276 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1277 // If this instruction is IVIncrement then IV is new incoming value
1278 // from header otherwise this instruction must be incoming value from
1279 // header because loop is in LCSSA form.
1280 if (PHI == IVIncrement)
1281 PN->addIncoming(IV, Header);
1283 PN->addIncoming(V, Header);
1285 // Otherwise this is an incoming value from header because loop is in
1287 PN->addIncoming(V, Header);
1289 // Remove incoming value from Latch.
1290 PN->removeIncomingValue(Latch);