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;
92 /// Find condition inside a loop that is suitable candidate for index split.
93 void findSplitCondition();
95 /// Find loop's exit condition.
96 void findLoopConditionals();
98 /// Return induction variable associated with value V.
99 void findIndVar(Value *V, Loop *L);
101 /// processOneIterationLoop - Current loop L contains compare instruction
102 /// that compares induction variable, IndVar, agains loop invariant. If
103 /// entire (i.e. meaningful) loop body is dominated by this compare
104 /// instruction then loop body is executed only for one iteration. In
105 /// such case eliminate loop structure surrounding this loop body. For
106 bool processOneIterationLoop(SplitInfo &SD);
108 /// If loop header includes loop variant instruction operands then
109 /// this loop may not be eliminated.
110 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
112 /// If Exiting block includes loop variant instructions then this
113 /// loop may not be eliminated.
114 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
116 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117 /// This routine is used to remove split condition's dead branch, dominated by
118 /// DeadBB. LiveBB dominates split conidition's other branch.
119 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
121 /// safeSplitCondition - Return true if it is possible to
122 /// split loop using given split condition.
123 bool safeSplitCondition(SplitInfo &SD);
125 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126 /// based on split value.
127 void calculateLoopBounds(SplitInfo &SD);
129 /// updatePHINodes - CFG has been changed.
131 /// - ExitBB's single predecessor was Latch
132 /// - Latch's second successor was Header
134 /// - ExitBB's single predecessor was Header
135 /// - Latch's one and only successor was Header
137 /// Update ExitBB PHINodes' to reflect this change.
138 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
140 PHINode *IV, Instruction *IVIncrement);
142 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
143 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
144 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
145 PHINode *IV, Instruction *IVAdd, Loop *LP);
147 /// splitLoop - Split current loop L in two loops using split information
148 /// SD. Update dominator information. Maintain LCSSA form.
149 bool splitLoop(SplitInfo &SD);
153 IndVarIncrement = NULL;
154 ExitCondition = NULL;
168 DominanceFrontier *DF;
169 SmallVector<SplitInfo, 4> SplitData;
171 // Induction variable whose range is being split by this transformation.
173 Instruction *IndVarIncrement;
175 // Loop exit condition.
176 ICmpInst *ExitCondition;
178 // Induction variable's initial value.
181 // Induction variable's final loop exit value operand number in exit condition..
182 unsigned ExitValueNum;
185 char LoopIndexSplit::ID = 0;
186 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
189 LoopPass *llvm::createLoopIndexSplitPass() {
190 return new LoopIndexSplit();
193 // Index split Loop L. Return true if loop is split.
194 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
195 bool Changed = false;
199 // FIXME - Nested loops make dominator info updates tricky.
200 if (!L->getSubLoops().empty())
203 SE = &getAnalysis<ScalarEvolution>();
204 DT = &getAnalysis<DominatorTree>();
205 LI = &getAnalysis<LoopInfo>();
206 DF = &getAnalysis<DominanceFrontier>();
210 findLoopConditionals();
215 findSplitCondition();
217 if (SplitData.empty())
220 // First see if it is possible to eliminate loop itself or not.
221 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
222 E = SplitData.end(); SI != E;) {
224 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
225 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
226 Changed = processOneIterationLoop(SD);
229 // If is loop is eliminated then nothing else to do here.
232 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
234 SplitData.erase(Delete_SI);
240 if (SplitData.empty())
243 // Split most profitiable condition.
244 // FIXME : Implement cost analysis.
245 unsigned MostProfitableSDIndex = 0;
246 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
254 /// Return true if V is a induction variable or induction variable's
255 /// increment for loop L.
256 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
258 Instruction *I = dyn_cast<Instruction>(V);
262 // Check if I is a phi node from loop header or not.
263 if (PHINode *PN = dyn_cast<PHINode>(V)) {
264 if (PN->getParent() == L->getHeader()) {
270 // Check if I is a add instruction whose one operand is
271 // phi node from loop header and second operand is constant.
272 if (I->getOpcode() != Instruction::Add)
275 Value *Op0 = I->getOperand(0);
276 Value *Op1 = I->getOperand(1);
278 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
279 if (PN->getParent() == L->getHeader()
280 && isa<ConstantInt>(Op1)) {
287 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
288 if (PN->getParent() == L->getHeader()
289 && isa<ConstantInt>(Op0)) {
299 // Find loop's exit condition and associated induction variable.
300 void LoopIndexSplit::findLoopConditionals() {
302 BasicBlock *ExitingBlock = NULL;
304 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
307 if (!L->isLoopExit(BB))
317 // If exiting block is neither loop header nor loop latch then this loop is
319 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
322 // If exit block's terminator is conditional branch inst then we have found
324 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
325 if (!BR || BR->isUnconditional())
328 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
333 if (CI->getPredicate() == ICmpInst::ICMP_EQ
334 || CI->getPredicate() == ICmpInst::ICMP_NE)
337 if (CI->getPredicate() == ICmpInst::ICMP_SGT
338 || CI->getPredicate() == ICmpInst::ICMP_UGT
339 || CI->getPredicate() == ICmpInst::ICMP_SGE
340 || CI->getPredicate() == ICmpInst::ICMP_UGE) {
342 BasicBlock *FirstSuccessor = BR->getSuccessor(0);
343 // splitLoop() is expecting LT/LE as exit condition predicate.
344 // Swap operands here if possible to meet this requirement.
345 if (!L->contains(FirstSuccessor))
353 // Exit condition's one operand is loop invariant exit value and second
354 // operand is SCEVAddRecExpr based on induction variable.
355 Value *V0 = CI->getOperand(0);
356 Value *V1 = CI->getOperand(1);
358 SCEVHandle SH0 = SE->getSCEV(V0);
359 SCEVHandle SH1 = SE->getSCEV(V1);
361 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
365 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
371 ExitCondition = NULL;
373 BasicBlock *Preheader = L->getLoopPreheader();
374 StartValue = IndVar->getIncomingValueForBlock(Preheader);
378 /// Find condition inside a loop that is suitable candidate for index split.
379 void LoopIndexSplit::findSplitCondition() {
382 // Check all basic block's terminators.
383 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
387 // If this basic block does not terminate in a conditional branch
388 // then terminator is not a suitable split condition.
389 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
393 if (BR->isUnconditional())
396 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
397 if (!CI || CI == ExitCondition)
400 if (CI->getPredicate() == ICmpInst::ICMP_NE)
403 // If split condition predicate is GT or GE then first execute
404 // false branch of split condition.
405 if (CI->getPredicate() != ICmpInst::ICMP_ULT
406 && CI->getPredicate() != ICmpInst::ICMP_SLT
407 && CI->getPredicate() != ICmpInst::ICMP_ULE
408 && CI->getPredicate() != ICmpInst::ICMP_SLE)
409 SD.UseTrueBranchFirst = false;
411 // If one operand is loop invariant and second operand is SCEVAddRecExpr
412 // based on induction variable then CI is a candidate split condition.
413 Value *V0 = CI->getOperand(0);
414 Value *V1 = CI->getOperand(1);
416 SCEVHandle SH0 = SE->getSCEV(V0);
417 SCEVHandle SH1 = SE->getSCEV(V1);
419 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
421 SD.SplitCondition = CI;
422 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
424 SplitData.push_back(SD);
426 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
427 if (IndVarIncrement && IndVarIncrement == Insn)
428 SplitData.push_back(SD);
431 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
433 SD.SplitCondition = CI;
434 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
436 SplitData.push_back(SD);
438 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
439 if (IndVarIncrement && IndVarIncrement == Insn)
440 SplitData.push_back(SD);
446 /// processOneIterationLoop - Current loop L contains compare instruction
447 /// that compares induction variable, IndVar, against loop invariant. If
448 /// entire (i.e. meaningful) loop body is dominated by this compare
449 /// instruction then loop body is executed only once. In such case eliminate
450 /// loop structure surrounding this loop body. For example,
451 /// for (int i = start; i < end; ++i) {
452 /// if ( i == somevalue) {
456 /// can be transformed into
457 /// if (somevalue >= start && somevalue < end) {
461 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
463 BasicBlock *Header = L->getHeader();
465 // First of all, check if SplitCondition dominates entire loop body
468 // If SplitCondition is not in loop header then this loop is not suitable
469 // for this transformation.
470 if (SD.SplitCondition->getParent() != Header)
473 // If loop header includes loop variant instruction operands then
474 // this loop may not be eliminated.
475 if (!safeHeader(SD, Header))
478 // If Exiting block includes loop variant instructions then this
479 // loop may not be eliminated.
480 if (!safeExitingBlock(SD, ExitCondition->getParent()))
485 // Replace index variable with split value in loop body. Loop body is executed
486 // only when index variable is equal to split value.
487 IndVar->replaceAllUsesWith(SD.SplitValue);
489 // Remove Latch to Header edge.
490 BasicBlock *Latch = L->getLoopLatch();
491 BasicBlock *LatchSucc = NULL;
492 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
495 Header->removePredecessor(Latch);
496 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
501 BR->setUnconditionalDest(LatchSucc);
503 Instruction *Terminator = Header->getTerminator();
504 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
506 // Replace split condition in header.
508 // SplitCondition : icmp eq i32 IndVar, SplitValue
510 // c1 = icmp uge i32 SplitValue, StartValue
511 // c2 = icmp ult i32 SplitValue, ExitValue
513 bool SignedPredicate = ExitCondition->isSignedPredicate();
514 Instruction *C1 = new ICmpInst(SignedPredicate ?
515 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
516 SD.SplitValue, StartValue, "lisplit",
518 Instruction *C2 = new ICmpInst(SignedPredicate ?
519 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
520 SD.SplitValue, ExitValue, "lisplit",
522 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
524 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
525 SD.SplitCondition->eraseFromParent();
527 // Now, clear latch block. Remove instructions that are responsible
528 // to increment induction variable.
529 Instruction *LTerminator = Latch->getTerminator();
530 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
534 if (isa<PHINode>(I) || I == LTerminator)
537 if (I == IndVarIncrement)
538 I->replaceAllUsesWith(ExitValue);
540 I->replaceAllUsesWith(UndefValue::get(I->getType()));
541 I->eraseFromParent();
544 LPM->deleteLoopFromQueue(L);
546 // Update Dominator Info.
547 // Only CFG change done is to remove Latch to Header edge. This
548 // does not change dominator tree because Latch did not dominate
551 DominanceFrontier::iterator HeaderDF = DF->find(Header);
552 if (HeaderDF != DF->end())
553 DF->removeFromFrontier(HeaderDF, Header);
555 DominanceFrontier::iterator LatchDF = DF->find(Latch);
556 if (LatchDF != DF->end())
557 DF->removeFromFrontier(LatchDF, Header);
562 // If loop header includes loop variant instruction operands then
563 // this loop can not be eliminated. This is used by processOneIterationLoop().
564 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
566 Instruction *Terminator = Header->getTerminator();
567 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
575 // SplitCondition itself is OK.
576 if (I == SD.SplitCondition)
579 // Induction variable is OK.
583 // Induction variable increment is OK.
584 if (I == IndVarIncrement)
587 // Terminator is also harmless.
591 // Otherwise we have a instruction that may not be safe.
598 // If Exiting block includes loop variant instructions then this
599 // loop may not be eliminated. This is used by processOneIterationLoop().
600 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
601 BasicBlock *ExitingBlock) {
603 for (BasicBlock::iterator BI = ExitingBlock->begin(),
604 BE = ExitingBlock->end(); BI != BE; ++BI) {
611 // Induction variable increment is OK.
612 if (IndVarIncrement && IndVarIncrement == I)
615 // Check if I is induction variable increment instruction.
616 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
618 Value *Op0 = I->getOperand(0);
619 Value *Op1 = I->getOperand(1);
621 ConstantInt *CI = NULL;
623 if ((PN = dyn_cast<PHINode>(Op0))) {
624 if ((CI = dyn_cast<ConstantInt>(Op1)))
627 if ((PN = dyn_cast<PHINode>(Op1))) {
628 if ((CI = dyn_cast<ConstantInt>(Op0)))
632 if (IndVarIncrement && PN == IndVar && CI->isOne())
636 // I is an Exit condition if next instruction is block terminator.
637 // Exit condition is OK if it compares loop invariant exit value,
638 // which is checked below.
639 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
640 if (EC == ExitCondition)
644 if (I == ExitingBlock->getTerminator())
647 // Otherwise we have instruction that may not be safe.
651 // We could not find any reason to consider ExitingBlock unsafe.
655 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
656 /// This routine is used to remove split condition's dead branch, dominated by
657 /// DeadBB. LiveBB dominates split conidition's other branch.
658 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
659 BasicBlock *LiveBB) {
661 // First update DeadBB's dominance frontier.
662 SmallVector<BasicBlock *, 8> FrontierBBs;
663 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
664 if (DeadBBDF != DF->end()) {
665 SmallVector<BasicBlock *, 8> PredBlocks;
667 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
668 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
669 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
670 BasicBlock *FrontierBB = *DeadBBSetI;
671 FrontierBBs.push_back(FrontierBB);
673 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
675 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
678 if (P == DeadBB || DT->dominates(DeadBB, P))
679 PredBlocks.push_back(P);
682 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
684 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
685 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
686 PE = PredBlocks.end(); PI != PE; ++PI) {
688 PN->removeIncomingValue(P);
697 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
698 SmallVector<BasicBlock *, 32> WorkList;
699 DomTreeNode *DN = DT->getNode(DeadBB);
700 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
701 E = df_end(DN); DI != E; ++DI) {
702 BasicBlock *BB = DI->getBlock();
703 WorkList.push_back(BB);
704 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
707 while (!WorkList.empty()) {
708 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
709 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
711 Instruction *I = BBI;
712 I->replaceAllUsesWith(UndefValue::get(I->getType()));
713 I->eraseFromParent();
715 LPM->deleteSimpleAnalysisValue(BB, LP);
719 BB->eraseFromParent();
722 // Update Frontier BBs' dominator info.
723 while (!FrontierBBs.empty()) {
724 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
725 BasicBlock *NewDominator = FBB->getSinglePredecessor();
727 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
730 if (NewDominator != LiveBB) {
731 for(; PI != PE; ++PI) {
734 NewDominator = LiveBB;
737 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
741 assert (NewDominator && "Unable to fix dominator info.");
742 DT->changeImmediateDominator(FBB, NewDominator);
743 DF->changeImmediateDominator(FBB, NewDominator, DT);
748 /// safeSplitCondition - Return true if it is possible to
749 /// split loop using given split condition.
750 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
752 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
754 // Unable to handle triange loops at the moment.
755 // In triangle loop, split condition is in header and one of the
756 // the split destination is loop latch. If split condition is EQ
757 // then such loops are already handle in processOneIterationLoop().
758 BasicBlock *Latch = L->getLoopLatch();
759 BranchInst *SplitTerminator =
760 cast<BranchInst>(SplitCondBlock->getTerminator());
761 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
762 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
763 if (L->getHeader() == SplitCondBlock
764 && (Latch == Succ0 || Latch == Succ1))
767 // If split condition branches heads do not have single predecessor,
768 // SplitCondBlock, then is not possible to remove inactive branch.
769 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
772 // Finally this split condition is safe only if merge point for
773 // split condition branch is loop latch. This check along with previous
774 // check, to ensure that exit condition is in either loop latch or header,
775 // filters all loops with non-empty loop body between merge point
776 // and exit condition.
777 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
778 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
779 if (Succ0DF->second.count(Latch))
782 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
783 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
784 if (Succ1DF->second.count(Latch))
790 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
791 /// based on split value.
792 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
794 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
795 ICmpInst::Predicate SP = SC->getPredicate();
796 const Type *Ty = SD.SplitValue->getType();
797 bool Sign = ExitCondition->isSignedPredicate();
798 BasicBlock *Preheader = L->getLoopPreheader();
799 Instruction *PHTerminator = Preheader->getTerminator();
801 // Initially use split value as upper loop bound for first loop and lower loop
802 // bound for second loop.
803 Value *AEV = SD.SplitValue;
804 Value *BSV = SD.SplitValue;
806 switch (ExitCondition->getPredicate()) {
807 case ICmpInst::ICMP_SGT:
808 case ICmpInst::ICMP_UGT:
809 case ICmpInst::ICMP_SGE:
810 case ICmpInst::ICMP_UGE:
812 assert (0 && "Unexpected exit condition predicate");
814 case ICmpInst::ICMP_SLT:
815 case ICmpInst::ICMP_ULT:
818 case ICmpInst::ICMP_SLT:
819 case ICmpInst::ICMP_ULT:
821 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
823 // is transformed into
825 // for (i = LB; i < min(UB, AEV); ++i)
827 // for (i = max(LB, BSV); i < UB; ++i);
830 case ICmpInst::ICMP_SLE:
831 case ICmpInst::ICMP_ULE:
834 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
836 // is transformed into
840 // for (i = LB; i < min(UB, AEV); ++i)
842 // for (i = max(LB, BSV); i < UB; ++i)
844 BSV = BinaryOperator::createAdd(SD.SplitValue,
845 ConstantInt::get(Ty, 1, Sign),
846 "lsplit.add", PHTerminator);
850 case ICmpInst::ICMP_SGE:
851 case ICmpInst::ICMP_UGE:
853 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
855 // is transformed into
857 // for (i = LB; i < min(UB, AEV); ++i)
859 // for (i = max(BSV, LB); i < UB; ++i)
862 case ICmpInst::ICMP_SGT:
863 case ICmpInst::ICMP_UGT:
866 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
868 // is transformed into
870 // BSV = AEV = SV + 1
871 // for (i = LB; i < min(UB, AEV); ++i)
873 // for (i = max(LB, BSV); i < UB; ++i)
875 BSV = BinaryOperator::createAdd(SD.SplitValue,
876 ConstantInt::get(Ty, 1, Sign),
877 "lsplit.add", PHTerminator);
882 assert (0 && "Unexpected split condition predicate");
887 case ICmpInst::ICMP_SLE:
888 case ICmpInst::ICMP_ULE:
891 case ICmpInst::ICMP_SLT:
892 case ICmpInst::ICMP_ULT:
894 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
896 // is transformed into
899 // for (i = LB; i <= min(UB, AEV); ++i)
901 // for (i = max(LB, BSV); i <= UB; ++i)
903 AEV = BinaryOperator::createSub(SD.SplitValue,
904 ConstantInt::get(Ty, 1, Sign),
905 "lsplit.sub", PHTerminator);
907 case ICmpInst::ICMP_SLE:
908 case ICmpInst::ICMP_ULE:
910 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
912 // is transformed into
915 // for (i = LB; i <= min(UB, AEV); ++i)
917 // for (i = max(LB, BSV); i <= UB; ++i)
919 BSV = BinaryOperator::createAdd(SD.SplitValue,
920 ConstantInt::get(Ty, 1, Sign),
921 "lsplit.add", PHTerminator);
923 case ICmpInst::ICMP_SGT:
924 case ICmpInst::ICMP_UGT:
926 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
928 // is transformed into
931 // for (i = LB; i <= min(AEV, UB); ++i)
933 // for (i = max(LB, BSV); i <= UB; ++i)
935 BSV = BinaryOperator::createAdd(SD.SplitValue,
936 ConstantInt::get(Ty, 1, Sign),
937 "lsplit.add", PHTerminator);
939 case ICmpInst::ICMP_SGE:
940 case ICmpInst::ICMP_UGE:
943 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
945 // is transformed into
948 // for (i = LB; i <= min(AEV, UB); ++i)
950 // for (i = max(LB, BSV); i <= UB; ++i)
952 AEV = BinaryOperator::createSub(SD.SplitValue,
953 ConstantInt::get(Ty, 1, Sign),
954 "lsplit.sub", PHTerminator);
957 assert (0 && "Unexpected split condition predicate");
964 // Calculate ALoop induction variable's new exiting value and
965 // BLoop induction variable's new starting value. Calculuate these
966 // values in original loop's preheader.
967 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
968 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
969 Value *C1 = new ICmpInst(Sign ?
970 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
972 ExitCondition->getOperand(ExitValueNum),
973 "lsplit.ev", PHTerminator);
974 SD.A_ExitValue = new SelectInst(C1, AEV,
975 ExitCondition->getOperand(ExitValueNum),
976 "lsplit.ev", PHTerminator);
978 Value *C2 = new ICmpInst(Sign ?
979 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
980 BSV, StartValue, "lsplit.sv",
982 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
983 "lsplit.sv", PHTerminator);
986 /// splitLoop - Split current loop L in two loops using split information
987 /// SD. Update dominator information. Maintain LCSSA form.
988 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
990 if (!safeSplitCondition(SD))
993 // After loop is cloned there are two loops.
995 // First loop, referred as ALoop, executes first part of loop's iteration
996 // space split. Second loop, referred as BLoop, executes remaining
997 // part of loop's iteration space.
999 // ALoop's exit edge enters BLoop's header through a forwarding block which
1000 // acts as a BLoop's preheader.
1001 BasicBlock *Preheader = L->getLoopPreheader();
1003 // Calculate ALoop induction variable's new exiting value and
1004 // BLoop induction variable's new starting value.
1005 calculateLoopBounds(SD);
1008 DenseMap<const Value *, Value *> ValueMap;
1009 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1011 BasicBlock *B_Header = BLoop->getHeader();
1013 //[*] ALoop's exiting edge BLoop's header.
1014 // ALoop's original exit block becomes BLoop's exit block.
1015 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1016 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1017 BranchInst *A_ExitInsn =
1018 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1019 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1020 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1021 if (L->contains(B_ExitBlock)) {
1022 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1023 A_ExitInsn->setSuccessor(0, B_Header);
1025 A_ExitInsn->setSuccessor(1, B_Header);
1027 //[*] Update ALoop's exit value using new exit value.
1028 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1030 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1031 // original loop's preheader. Add incoming PHINode values from
1032 // ALoop's exiting block. Update BLoop header's domiantor info.
1034 // Collect inverse map of Header PHINodes.
1035 DenseMap<Value *, Value *> InverseMap;
1036 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1037 BE = L->getHeader()->end(); BI != BE; ++BI) {
1038 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1039 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1040 InverseMap[PNClone] = PN;
1045 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1047 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1048 // Remove incoming value from original preheader.
1049 PN->removeIncomingValue(Preheader);
1051 // Add incoming value from A_ExitingBlock.
1053 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1055 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1056 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1057 PN->addIncoming(V2, A_ExitingBlock);
1062 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1063 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1065 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1066 // block. Remove incoming PHINode values from ALoop's exiting block.
1067 // Add new incoming values from BLoop's incoming exiting value.
1068 // Update BLoop exit block's dominator info..
1069 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1070 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1072 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1073 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1075 PN->removeIncomingValue(A_ExitingBlock);
1080 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1081 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1083 //[*] Split ALoop's exit edge. This creates a new block which
1084 // serves two purposes. First one is to hold PHINode defnitions
1085 // to ensure that ALoop's LCSSA form. Second use it to act
1086 // as a preheader for BLoop.
1087 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1089 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1090 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1091 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1093 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1094 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1095 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1096 newPHI->addIncoming(V1, A_ExitingBlock);
1097 A_ExitBlock->getInstList().push_front(newPHI);
1098 PN->removeIncomingValue(A_ExitBlock);
1099 PN->addIncoming(newPHI, A_ExitBlock);
1104 //[*] Eliminate split condition's inactive branch from ALoop.
1105 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1106 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1107 BasicBlock *A_InactiveBranch = NULL;
1108 BasicBlock *A_ActiveBranch = NULL;
1109 if (SD.UseTrueBranchFirst) {
1110 A_ActiveBranch = A_BR->getSuccessor(0);
1111 A_InactiveBranch = A_BR->getSuccessor(1);
1113 A_ActiveBranch = A_BR->getSuccessor(1);
1114 A_InactiveBranch = A_BR->getSuccessor(0);
1116 A_BR->setUnconditionalDest(A_ActiveBranch);
1117 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1119 //[*] Eliminate split condition's inactive branch in from BLoop.
1120 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1121 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1122 BasicBlock *B_InactiveBranch = NULL;
1123 BasicBlock *B_ActiveBranch = NULL;
1124 if (SD.UseTrueBranchFirst) {
1125 B_ActiveBranch = B_BR->getSuccessor(1);
1126 B_InactiveBranch = B_BR->getSuccessor(0);
1128 B_ActiveBranch = B_BR->getSuccessor(0);
1129 B_InactiveBranch = B_BR->getSuccessor(1);
1131 B_BR->setUnconditionalDest(B_ActiveBranch);
1132 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1134 BasicBlock *A_Header = L->getHeader();
1135 if (A_ExitingBlock == A_Header)
1138 //[*] Move exit condition into split condition block to avoid
1139 // executing dead loop iteration.
1140 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1141 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1142 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1144 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1145 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1148 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1149 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1154 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1155 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1156 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1157 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1159 BasicBlock *ExitingBB = EC->getParent();
1160 Instruction *CurrentBR = CondBB->getTerminator();
1162 // Move exit condition into split condition block.
1163 EC->moveBefore(CurrentBR);
1164 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1166 // Move exiting block's branch into split condition block. Update its branch
1168 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1169 ExitingBR->moveBefore(CurrentBR);
1170 if (ExitingBR->getSuccessor(0) == ExitBB)
1171 ExitingBR->setSuccessor(1, ActiveBB);
1173 ExitingBR->setSuccessor(0, ActiveBB);
1175 // Remove split condition and current split condition branch.
1176 SC->eraseFromParent();
1177 CurrentBR->eraseFromParent();
1179 // Connect exiting block to split condition block.
1180 new BranchInst(CondBB, ExitingBB);
1183 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1185 // Fix dominator info.
1186 // ExitBB is now dominated by CondBB
1187 DT->changeImmediateDominator(ExitBB, CondBB);
1188 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1190 // Basicblocks dominated by ActiveBB may have ExitingBB or
1191 // a basic block outside the loop in their DF list. If so,
1192 // replace it with CondBB.
1193 DomTreeNode *Node = DT->getNode(ActiveBB);
1194 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1196 BasicBlock *BB = DI->getBlock();
1197 DominanceFrontier::iterator BBDF = DF->find(BB);
1198 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1199 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1200 while (DomSetI != DomSetE) {
1201 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1203 BasicBlock *DFBB = *CurrentItr;
1204 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1205 BBDF->second.erase(DFBB);
1206 BBDF->second.insert(CondBB);
1212 /// updatePHINodes - CFG has been changed.
1214 /// - ExitBB's single predecessor was Latch
1215 /// - Latch's second successor was Header
1217 /// - ExitBB's single predecessor was Header
1218 /// - Latch's one and only successor was Header
1220 /// Update ExitBB PHINodes' to reflect this change.
1221 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1223 PHINode *IV, Instruction *IVIncrement) {
1225 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1227 PHINode *PN = dyn_cast<PHINode>(BI);
1231 Value *V = PN->getIncomingValueForBlock(Latch);
1232 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1233 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1235 // The second use is in Header and it is new incoming value for PN.
1239 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1242 U1 = cast<PHINode>(*UI);
1244 U2 = cast<PHINode>(*UI);
1246 assert ( 0 && "Unexpected third use of this PHINode");
1248 assert (U1 && U2 && "Unable to find two uses");
1250 if (U1->getParent() == Header)
1254 PN->addIncoming(NewV, Header);
1256 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1257 // If this instruction is IVIncrement then IV is new incoming value
1258 // from header otherwise this instruction must be incoming value from
1259 // header because loop is in LCSSA form.
1260 if (PHI == IVIncrement)
1261 PN->addIncoming(IV, Header);
1263 PN->addIncoming(V, Header);
1265 // Otherwise this is an incoming value from header because loop is in
1267 PN->addIncoming(V, Header);
1269 // Remove incoming value from Latch.
1270 PN->removeIncomingValue(Latch);