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.
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 void updateLoopBounds(ICmpInst *CI);
116 /// updateLoopIterationSpace - Current loop body is covered by an AND
117 /// instruction whose operands compares induction variables with loop
118 /// invariants. If possible, hoist this check outside the loop by
119 /// updating appropriate start and end values for induction variable.
120 bool updateLoopIterationSpace(SplitInfo &SD);
122 /// If loop header includes loop variant instruction operands then
123 /// this loop may not be eliminated.
124 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
126 /// If Exiting block includes loop variant instructions then this
127 /// loop may not be eliminated.
128 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
130 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131 /// This routine is used to remove split condition's dead branch, dominated by
132 /// DeadBB. LiveBB dominates split conidition's other branch.
133 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
135 /// safeSplitCondition - Return true if it is possible to
136 /// split loop using given split condition.
137 bool safeSplitCondition(SplitInfo &SD);
139 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140 /// based on split value.
141 void calculateLoopBounds(SplitInfo &SD);
143 /// updatePHINodes - CFG has been changed.
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
156 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159 PHINode *IV, Instruction *IVAdd, Loop *LP);
161 /// splitLoop - Split current loop L in two loops using split information
162 /// SD. Update dominator information. Maintain LCSSA form.
163 bool splitLoop(SplitInfo &SD);
167 IndVarIncrement = NULL;
168 ExitCondition = NULL;
182 DominanceFrontier *DF;
183 SmallVector<SplitInfo, 4> SplitData;
185 // Induction variable whose range is being split by this transformation.
187 Instruction *IndVarIncrement;
189 // Loop exit condition.
190 ICmpInst *ExitCondition;
192 // Induction variable's initial value.
195 // Induction variable's final loop exit value operand number in exit condition..
196 unsigned ExitValueNum;
199 char LoopIndexSplit::ID = 0;
200 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
203 LoopPass *llvm::createLoopIndexSplitPass() {
204 return new LoopIndexSplit();
207 // Index split Loop L. Return true if loop is split.
208 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
209 bool Changed = false;
213 // FIXME - Nested loops make dominator info updates tricky.
214 if (!L->getSubLoops().empty())
217 SE = &getAnalysis<ScalarEvolution>();
218 DT = &getAnalysis<DominatorTree>();
219 LI = &getAnalysis<LoopInfo>();
220 DF = &getAnalysis<DominanceFrontier>();
224 findLoopConditionals();
229 findSplitCondition();
231 if (SplitData.empty())
234 // First see if it is possible to eliminate loop itself or not.
235 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
236 SI != SplitData.end();) {
238 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
239 if (SD.SplitCondition->getOpcode() == Instruction::And) {
240 Changed = updateLoopIterationSpace(SD);
243 // If is loop is eliminated then nothing else to do here.
246 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
247 SI = SplitData.erase(Delete_SI);
250 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
251 Changed = processOneIterationLoop(SD);
254 // If is loop is eliminated then nothing else to do here.
257 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
258 SI = SplitData.erase(Delete_SI);
264 if (SplitData.empty())
267 // Split most profitiable condition.
268 // FIXME : Implement cost analysis.
269 unsigned MostProfitableSDIndex = 0;
270 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
278 /// Return true if V is a induction variable or induction variable's
279 /// increment for loop L.
280 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
282 Instruction *I = dyn_cast<Instruction>(V);
286 // Check if I is a phi node from loop header or not.
287 if (PHINode *PN = dyn_cast<PHINode>(V)) {
288 if (PN->getParent() == L->getHeader()) {
294 // Check if I is a add instruction whose one operand is
295 // phi node from loop header and second operand is constant.
296 if (I->getOpcode() != Instruction::Add)
299 Value *Op0 = I->getOperand(0);
300 Value *Op1 = I->getOperand(1);
302 if (PHINode *PN = dyn_cast<PHINode>(Op0))
303 if (PN->getParent() == L->getHeader())
304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
311 if (PHINode *PN = dyn_cast<PHINode>(Op1))
312 if (PN->getParent() == L->getHeader())
313 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
323 // Find loop's exit condition and associated induction variable.
324 void LoopIndexSplit::findLoopConditionals() {
326 BasicBlock *ExitingBlock = NULL;
328 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
331 if (!L->isLoopExit(BB))
341 // If exiting block is neither loop header nor loop latch then this loop is
343 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
346 // If exit block's terminator is conditional branch inst then we have found
348 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
349 if (!BR || BR->isUnconditional())
352 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
357 if (CI->getPredicate() == ICmpInst::ICMP_EQ
358 || CI->getPredicate() == ICmpInst::ICMP_NE)
363 // Exit condition's one operand is loop invariant exit value and second
364 // operand is SCEVAddRecExpr based on induction variable.
365 Value *V0 = CI->getOperand(0);
366 Value *V1 = CI->getOperand(1);
368 SCEVHandle SH0 = SE->getSCEV(V0);
369 SCEVHandle SH1 = SE->getSCEV(V1);
371 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
375 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
381 ExitCondition = NULL;
383 BasicBlock *Preheader = L->getLoopPreheader();
384 StartValue = IndVar->getIncomingValueForBlock(Preheader);
388 /// Find condition inside a loop that is suitable candidate for index split.
389 void LoopIndexSplit::findSplitCondition() {
392 // Check all basic block's terminators.
393 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
398 // If this basic block does not terminate in a conditional branch
399 // then terminator is not a suitable split condition.
400 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
404 if (BR->isUnconditional())
407 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
408 if (AndI->getOpcode() == Instruction::And) {
409 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
410 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
415 if (!safeICmpInst(Op0, SD))
418 if (!safeICmpInst(Op1, SD))
421 SD.SplitCondition = AndI;
422 SplitData.push_back(SD);
426 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
427 if (!CI || CI == ExitCondition)
430 if (CI->getPredicate() == ICmpInst::ICMP_NE)
433 // If split condition predicate is GT or GE then first execute
434 // false branch of split condition.
435 if (CI->getPredicate() == ICmpInst::ICMP_UGT
436 || CI->getPredicate() == ICmpInst::ICMP_SGT
437 || CI->getPredicate() == ICmpInst::ICMP_UGE
438 || CI->getPredicate() == ICmpInst::ICMP_SGE)
439 SD.UseTrueBranchFirst = false;
441 // If one operand is loop invariant and second operand is SCEVAddRecExpr
442 // based on induction variable then CI is a candidate split condition.
443 if (safeICmpInst(CI, SD))
444 SplitData.push_back(SD);
448 // safeIcmpInst - CI is considered safe instruction if one of the operand
449 // is SCEVAddRecExpr based on induction variable and other operand is
450 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
452 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
454 Value *V0 = CI->getOperand(0);
455 Value *V1 = CI->getOperand(1);
457 SCEVHandle SH0 = SE->getSCEV(V0);
458 SCEVHandle SH1 = SE->getSCEV(V1);
460 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
462 SD.SplitCondition = CI;
463 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
467 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
468 if (IndVarIncrement && IndVarIncrement == Insn)
472 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
474 SD.SplitCondition = CI;
475 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
479 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
480 if (IndVarIncrement && IndVarIncrement == Insn)
488 /// processOneIterationLoop - Current loop L contains compare instruction
489 /// that compares induction variable, IndVar, against loop invariant. If
490 /// entire (i.e. meaningful) loop body is dominated by this compare
491 /// instruction then loop body is executed only once. In such case eliminate
492 /// loop structure surrounding this loop body. For example,
493 /// for (int i = start; i < end; ++i) {
494 /// if ( i == somevalue) {
498 /// can be transformed into
499 /// if (somevalue >= start && somevalue < end) {
503 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
505 BasicBlock *Header = L->getHeader();
507 // First of all, check if SplitCondition dominates entire loop body
510 // If SplitCondition is not in loop header then this loop is not suitable
511 // for this transformation.
512 if (SD.SplitCondition->getParent() != Header)
515 // If loop header includes loop variant instruction operands then
516 // this loop may not be eliminated.
517 if (!safeHeader(SD, Header))
520 // If Exiting block includes loop variant instructions then this
521 // loop may not be eliminated.
522 if (!safeExitingBlock(SD, ExitCondition->getParent()))
525 // Filter loops where split condition's false branch is not empty.
526 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
529 // If split condition is not safe then do not process this loop.
531 // for(int i = 0; i < N; i++) {
540 if (!safeSplitCondition(SD))
543 BasicBlock *Latch = L->getLoopLatch();
544 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
550 // Replace index variable with split value in loop body. Loop body is executed
551 // only when index variable is equal to split value.
552 IndVar->replaceAllUsesWith(SD.SplitValue);
554 // Remove Latch to Header edge.
555 BasicBlock *LatchSucc = NULL;
556 Header->removePredecessor(Latch);
557 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
562 BR->setUnconditionalDest(LatchSucc);
564 Instruction *Terminator = Header->getTerminator();
565 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
567 // Replace split condition in header.
569 // SplitCondition : icmp eq i32 IndVar, SplitValue
571 // c1 = icmp uge i32 SplitValue, StartValue
572 // c2 = icmp ult i32 SplitValue, ExitValue
574 bool SignedPredicate = ExitCondition->isSignedPredicate();
575 Instruction *C1 = new ICmpInst(SignedPredicate ?
576 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
577 SD.SplitValue, StartValue, "lisplit",
579 Instruction *C2 = new ICmpInst(SignedPredicate ?
580 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
581 SD.SplitValue, ExitValue, "lisplit",
583 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
585 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
586 SD.SplitCondition->eraseFromParent();
588 // Now, clear latch block. Remove instructions that are responsible
589 // to increment induction variable.
590 Instruction *LTerminator = Latch->getTerminator();
591 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
595 if (isa<PHINode>(I) || I == LTerminator)
598 if (I == IndVarIncrement)
599 I->replaceAllUsesWith(ExitValue);
601 I->replaceAllUsesWith(UndefValue::get(I->getType()));
602 I->eraseFromParent();
605 LPM->deleteLoopFromQueue(L);
607 // Update Dominator Info.
608 // Only CFG change done is to remove Latch to Header edge. This
609 // does not change dominator tree because Latch did not dominate
612 DominanceFrontier::iterator HeaderDF = DF->find(Header);
613 if (HeaderDF != DF->end())
614 DF->removeFromFrontier(HeaderDF, Header);
616 DominanceFrontier::iterator LatchDF = DF->find(Latch);
617 if (LatchDF != DF->end())
618 DF->removeFromFrontier(LatchDF, Header);
623 // If loop header includes loop variant instruction operands then
624 // this loop can not be eliminated. This is used by processOneIterationLoop().
625 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
627 Instruction *Terminator = Header->getTerminator();
628 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
636 // SplitCondition itself is OK.
637 if (I == SD.SplitCondition)
640 // Induction variable is OK.
644 // Induction variable increment is OK.
645 if (I == IndVarIncrement)
648 // Terminator is also harmless.
652 // Otherwise we have a instruction that may not be safe.
659 // If Exiting block includes loop variant instructions then this
660 // loop may not be eliminated. This is used by processOneIterationLoop().
661 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
662 BasicBlock *ExitingBlock) {
664 for (BasicBlock::iterator BI = ExitingBlock->begin(),
665 BE = ExitingBlock->end(); BI != BE; ++BI) {
672 // Induction variable increment is OK.
673 if (IndVarIncrement && IndVarIncrement == I)
676 // Check if I is induction variable increment instruction.
677 if (I->getOpcode() == Instruction::Add) {
679 Value *Op0 = I->getOperand(0);
680 Value *Op1 = I->getOperand(1);
682 ConstantInt *CI = NULL;
684 if ((PN = dyn_cast<PHINode>(Op0))) {
685 if ((CI = dyn_cast<ConstantInt>(Op1)))
687 if (!IndVarIncrement && PN == IndVar)
689 // else this is another loop induction variable
693 if ((PN = dyn_cast<PHINode>(Op1))) {
694 if ((CI = dyn_cast<ConstantInt>(Op0)))
696 if (!IndVarIncrement && PN == IndVar)
698 // else this is another loop induction variable
704 // I is an Exit condition if next instruction is block terminator.
705 // Exit condition is OK if it compares loop invariant exit value,
706 // which is checked below.
707 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
708 if (EC == ExitCondition)
712 if (I == ExitingBlock->getTerminator())
715 // Otherwise we have instruction that may not be safe.
719 // We could not find any reason to consider ExitingBlock unsafe.
723 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
725 Value *V0 = CI->getOperand(0);
726 Value *V1 = CI->getOperand(1);
729 SCEVHandle SH0 = SE->getSCEV(V0);
731 if (SH0->isLoopInvariant(L))
736 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
737 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
738 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
739 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
740 ExitCondition->swapOperands();
749 Value *UB = ExitCondition->getOperand(ExitValueNum);
750 const Type *Ty = NV->getType();
751 bool Sign = ExitCondition->isSignedPredicate();
752 BasicBlock *Preheader = L->getLoopPreheader();
753 Instruction *PHTerminator = Preheader->getTerminator();
755 assert (NV && "Unexpected value");
757 switch (CI->getPredicate()) {
758 case ICmpInst::ICMP_ULE:
759 case ICmpInst::ICMP_SLE:
760 // for (i = LB; i < UB; ++i)
761 // if (i <= NV && ...)
764 // is transformed into
765 // NUB = min (NV+1, UB)
766 // for (i = LB; i < NUB ; ++i)
769 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
770 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
771 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
772 "lsplit.add", PHTerminator);
773 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
774 A, UB,"lsplit,c", PHTerminator);
775 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
778 // for (i = LB; i <= UB; ++i)
779 // if (i <= NV && ...)
782 // is transformed into
783 // NUB = min (NV, UB)
784 // for (i = LB; i <= NUB ; ++i)
787 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
788 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
789 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
790 NV, UB, "lsplit.c", PHTerminator);
791 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
794 case ICmpInst::ICMP_ULT:
795 case ICmpInst::ICMP_SLT:
796 // for (i = LB; i < UB; ++i)
797 // if (i < NV && ...)
800 // is transformed into
801 // NUB = min (NV, UB)
802 // for (i = LB; i < NUB ; ++i)
805 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
806 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
807 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
808 NV, UB, "lsplit.c", PHTerminator);
809 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
812 // for (i = LB; i <= UB; ++i)
813 // if (i < NV && ...)
816 // is transformed into
817 // NUB = min (NV -1 , UB)
818 // for (i = LB; i <= NUB ; ++i)
821 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
822 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
823 Value *S = BinaryOperator::createSub(NV, ConstantInt::get(Ty, 1, Sign),
824 "lsplit.add", PHTerminator);
825 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
826 S, UB, "lsplit.c", PHTerminator);
827 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
830 case ICmpInst::ICMP_UGE:
831 case ICmpInst::ICMP_SGE:
832 // for (i = LB; i (< or <=) UB; ++i)
833 // if (i >= NV && ...)
836 // is transformed into
837 // NLB = max (NV, LB)
838 // for (i = NLB; i (< or <=) UB ; ++i)
842 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
843 NV, StartValue, "lsplit.c", PHTerminator);
844 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
847 case ICmpInst::ICMP_UGT:
848 case ICmpInst::ICMP_SGT:
849 // for (i = LB; i (< or <=) UB; ++i)
850 // if (i > NV && ...)
853 // is transformed into
854 // NLB = max (NV+1, LB)
855 // for (i = NLB; i (< or <=) UB ; ++i)
859 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
860 "lsplit.add", PHTerminator);
861 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
862 A, StartValue, "lsplit.c", PHTerminator);
863 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
867 assert ( 0 && "Unexpected split condition predicate");
871 unsigned i = IndVar->getBasicBlockIndex(Preheader);
872 IndVar->setIncomingValue(i, NLB);
876 ExitCondition->setOperand(ExitValueNum, NUB);
879 /// updateLoopIterationSpace - Current loop body is covered by an AND
880 /// instruction whose operands compares induction variables with loop
881 /// invariants. If possible, hoist this check outside the loop by
882 /// updating appropriate start and end values for induction variable.
883 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
884 BasicBlock *Header = L->getHeader();
885 BasicBlock *ExitingBlock = ExitCondition->getParent();
886 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
888 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
889 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
891 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
892 || Op0->getPredicate() == ICmpInst::ICMP_NE
893 || Op0->getPredicate() == ICmpInst::ICMP_EQ
894 || Op0->getPredicate() == ICmpInst::ICMP_NE)
897 // Check if SplitCondition dominates entire loop body
900 // If SplitCondition is not in loop header then this loop is not suitable
901 // for this transformation.
902 if (SD.SplitCondition->getParent() != Header)
905 // If loop header includes loop variant instruction operands then
906 // this loop may not be eliminated.
907 Instruction *Terminator = Header->getTerminator();
908 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
916 // SplitCondition itself is OK.
917 if (I == SD.SplitCondition)
919 if (I == Op0 || I == Op1)
922 // Induction variable is OK.
926 // Induction variable increment is OK.
927 if (I == IndVarIncrement)
930 // Terminator is also harmless.
934 // Otherwise we have a instruction that may not be safe.
938 // If Exiting block includes loop variant instructions then this
939 // loop may not be eliminated.
940 if (!safeExitingBlock(SD, ExitCondition->getParent()))
943 // Verify that loop exiting block has only two predecessor, where one predecessor
944 // is split condition block. The other predecessor will become exiting block's
945 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
946 // more then two predecessors. This requires extra work in updating dominator
948 BasicBlock *ExitingBBPred = NULL;
949 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
951 BasicBlock *BB = *PI;
952 if (SplitCondBlock == BB)
960 // Update loop bounds to absorb Op0 check.
961 updateLoopBounds(Op0);
962 // Update loop bounds to absorb Op1 check.
963 updateLoopBounds(Op1);
967 // Unconditionally connect split block to its remaining successor.
968 BranchInst *SplitTerminator =
969 cast<BranchInst>(SplitCondBlock->getTerminator());
970 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
971 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
972 if (Succ0 == ExitCondition->getParent())
973 SplitTerminator->setUnconditionalDest(Succ1);
975 SplitTerminator->setUnconditionalDest(Succ0);
977 // Remove split condition.
978 SD.SplitCondition->eraseFromParent();
979 if (Op0->use_begin() == Op0->use_end())
980 Op0->eraseFromParent();
981 if (Op1->use_begin() == Op1->use_end())
982 Op1->eraseFromParent();
984 BranchInst *ExitInsn =
985 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
986 assert (ExitInsn && "Unable to find suitable loop exit branch");
987 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
988 if (L->contains(ExitBlock))
989 ExitBlock = ExitInsn->getSuccessor(0);
991 // Update domiantor info. Now, ExitingBlock has only one predecessor,
992 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
993 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
995 // If ExitingBlock is a member of loop BB's DF list then replace it with
996 // loop header and exit block.
997 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1000 if (BB == Header || BB == ExitingBlock)
1002 DominanceFrontier::iterator BBDF = DF->find(BB);
1003 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1004 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1005 while (DomSetI != DomSetE) {
1006 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1008 BasicBlock *DFBB = *CurrentItr;
1009 if (DFBB == ExitingBlock) {
1010 BBDF->second.erase(DFBB);
1011 BBDF->second.insert(Header);
1012 if (Header != ExitingBlock)
1013 BBDF->second.insert(ExitBlock);
1022 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1023 /// This routine is used to remove split condition's dead branch, dominated by
1024 /// DeadBB. LiveBB dominates split conidition's other branch.
1025 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1026 BasicBlock *LiveBB) {
1028 // First update DeadBB's dominance frontier.
1029 SmallVector<BasicBlock *, 8> FrontierBBs;
1030 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1031 if (DeadBBDF != DF->end()) {
1032 SmallVector<BasicBlock *, 8> PredBlocks;
1034 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1035 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1036 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1037 BasicBlock *FrontierBB = *DeadBBSetI;
1038 FrontierBBs.push_back(FrontierBB);
1040 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1042 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1044 BasicBlock *P = *PI;
1045 if (P == DeadBB || DT->dominates(DeadBB, P))
1046 PredBlocks.push_back(P);
1049 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1050 FBI != FBE; ++FBI) {
1051 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1052 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1053 PE = PredBlocks.end(); PI != PE; ++PI) {
1054 BasicBlock *P = *PI;
1055 PN->removeIncomingValue(P);
1064 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1065 SmallVector<BasicBlock *, 32> WorkList;
1066 DomTreeNode *DN = DT->getNode(DeadBB);
1067 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1068 E = df_end(DN); DI != E; ++DI) {
1069 BasicBlock *BB = DI->getBlock();
1070 WorkList.push_back(BB);
1071 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1074 while (!WorkList.empty()) {
1075 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1076 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
1078 Instruction *I = BBI;
1080 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1081 I->eraseFromParent();
1083 LPM->deleteSimpleAnalysisValue(BB, LP);
1085 DF->removeBlock(BB);
1086 LI->removeBlock(BB);
1087 BB->eraseFromParent();
1090 // Update Frontier BBs' dominator info.
1091 while (!FrontierBBs.empty()) {
1092 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1093 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1094 if (!NewDominator) {
1095 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1098 if (NewDominator != LiveBB) {
1099 for(; PI != PE; ++PI) {
1100 BasicBlock *P = *PI;
1102 NewDominator = LiveBB;
1105 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1109 assert (NewDominator && "Unable to fix dominator info.");
1110 DT->changeImmediateDominator(FBB, NewDominator);
1111 DF->changeImmediateDominator(FBB, NewDominator, DT);
1116 /// safeSplitCondition - Return true if it is possible to
1117 /// split loop using given split condition.
1118 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1120 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1121 BasicBlock *Latch = L->getLoopLatch();
1122 BranchInst *SplitTerminator =
1123 cast<BranchInst>(SplitCondBlock->getTerminator());
1124 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1125 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1127 // Finally this split condition is safe only if merge point for
1128 // split condition branch is loop latch. This check along with previous
1129 // check, to ensure that exit condition is in either loop latch or header,
1130 // filters all loops with non-empty loop body between merge point
1131 // and exit condition.
1132 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1133 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1134 if (Succ0DF->second.count(Latch))
1137 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1138 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1139 if (Succ1DF->second.count(Latch))
1145 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1146 /// based on split value.
1147 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1149 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1150 ICmpInst::Predicate SP = SC->getPredicate();
1151 const Type *Ty = SD.SplitValue->getType();
1152 bool Sign = ExitCondition->isSignedPredicate();
1153 BasicBlock *Preheader = L->getLoopPreheader();
1154 Instruction *PHTerminator = Preheader->getTerminator();
1156 // Initially use split value as upper loop bound for first loop and lower loop
1157 // bound for second loop.
1158 Value *AEV = SD.SplitValue;
1159 Value *BSV = SD.SplitValue;
1161 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1162 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1163 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1164 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1165 ExitCondition->swapOperands();
1172 switch (ExitCondition->getPredicate()) {
1173 case ICmpInst::ICMP_SGT:
1174 case ICmpInst::ICMP_UGT:
1175 case ICmpInst::ICMP_SGE:
1176 case ICmpInst::ICMP_UGE:
1178 assert (0 && "Unexpected exit condition predicate");
1180 case ICmpInst::ICMP_SLT:
1181 case ICmpInst::ICMP_ULT:
1184 case ICmpInst::ICMP_SLT:
1185 case ICmpInst::ICMP_ULT:
1187 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1189 // is transformed into
1191 // for (i = LB; i < min(UB, AEV); ++i)
1193 // for (i = max(LB, BSV); i < UB; ++i);
1196 case ICmpInst::ICMP_SLE:
1197 case ICmpInst::ICMP_ULE:
1200 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1202 // is transformed into
1206 // for (i = LB; i < min(UB, AEV); ++i)
1208 // for (i = max(LB, BSV); i < UB; ++i)
1210 BSV = BinaryOperator::createAdd(SD.SplitValue,
1211 ConstantInt::get(Ty, 1, Sign),
1212 "lsplit.add", PHTerminator);
1216 case ICmpInst::ICMP_SGE:
1217 case ICmpInst::ICMP_UGE:
1219 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1221 // is transformed into
1223 // for (i = LB; i < min(UB, AEV); ++i)
1225 // for (i = max(BSV, LB); i < UB; ++i)
1228 case ICmpInst::ICMP_SGT:
1229 case ICmpInst::ICMP_UGT:
1232 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1234 // is transformed into
1236 // BSV = AEV = SV + 1
1237 // for (i = LB; i < min(UB, AEV); ++i)
1239 // for (i = max(LB, BSV); i < UB; ++i)
1241 BSV = BinaryOperator::createAdd(SD.SplitValue,
1242 ConstantInt::get(Ty, 1, Sign),
1243 "lsplit.add", PHTerminator);
1248 assert (0 && "Unexpected split condition predicate");
1250 } // end switch (SP)
1253 case ICmpInst::ICMP_SLE:
1254 case ICmpInst::ICMP_ULE:
1257 case ICmpInst::ICMP_SLT:
1258 case ICmpInst::ICMP_ULT:
1260 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1262 // is transformed into
1265 // for (i = LB; i <= min(UB, AEV); ++i)
1267 // for (i = max(LB, BSV); i <= UB; ++i)
1269 AEV = BinaryOperator::createSub(SD.SplitValue,
1270 ConstantInt::get(Ty, 1, Sign),
1271 "lsplit.sub", PHTerminator);
1273 case ICmpInst::ICMP_SLE:
1274 case ICmpInst::ICMP_ULE:
1276 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1278 // is transformed into
1281 // for (i = LB; i <= min(UB, AEV); ++i)
1283 // for (i = max(LB, BSV); i <= UB; ++i)
1285 BSV = BinaryOperator::createAdd(SD.SplitValue,
1286 ConstantInt::get(Ty, 1, Sign),
1287 "lsplit.add", PHTerminator);
1289 case ICmpInst::ICMP_SGT:
1290 case ICmpInst::ICMP_UGT:
1292 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1294 // is transformed into
1297 // for (i = LB; i <= min(AEV, UB); ++i)
1299 // for (i = max(LB, BSV); i <= UB; ++i)
1301 BSV = BinaryOperator::createAdd(SD.SplitValue,
1302 ConstantInt::get(Ty, 1, Sign),
1303 "lsplit.add", PHTerminator);
1305 case ICmpInst::ICMP_SGE:
1306 case ICmpInst::ICMP_UGE:
1309 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1311 // is transformed into
1314 // for (i = LB; i <= min(AEV, UB); ++i)
1316 // for (i = max(LB, BSV); i <= UB; ++i)
1318 AEV = BinaryOperator::createSub(SD.SplitValue,
1319 ConstantInt::get(Ty, 1, Sign),
1320 "lsplit.sub", PHTerminator);
1323 assert (0 && "Unexpected split condition predicate");
1325 } // end switch (SP)
1330 // Calculate ALoop induction variable's new exiting value and
1331 // BLoop induction variable's new starting value. Calculuate these
1332 // values in original loop's preheader.
1333 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1334 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
1335 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1337 // If ExitValue operand is also defined in Loop header then
1338 // insert new ExitValue after this operand definition.
1339 if (Instruction *EVN =
1340 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1341 if (!isa<PHINode>(EVN))
1342 if (InsertPt->getParent() == EVN->getParent()) {
1343 BasicBlock::iterator LHBI = L->getHeader()->begin();
1344 BasicBlock::iterator LHBE = L->getHeader()->end();
1345 for(;LHBI != LHBE; ++LHBI) {
1346 Instruction *I = LHBI;
1353 Value *C1 = new ICmpInst(Sign ?
1354 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1356 ExitCondition->getOperand(ExitValueNum),
1357 "lsplit.ev", InsertPt);
1359 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1360 ExitCondition->getOperand(ExitValueNum),
1361 "lsplit.ev", InsertPt);
1363 Value *C2 = new ICmpInst(Sign ?
1364 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1365 BSV, StartValue, "lsplit.sv",
1367 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1368 "lsplit.sv", PHTerminator);
1371 /// splitLoop - Split current loop L in two loops using split information
1372 /// SD. Update dominator information. Maintain LCSSA form.
1373 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1375 if (!safeSplitCondition(SD))
1378 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1380 // Unable to handle triange loops at the moment.
1381 // In triangle loop, split condition is in header and one of the
1382 // the split destination is loop latch. If split condition is EQ
1383 // then such loops are already handle in processOneIterationLoop().
1384 BasicBlock *Latch = L->getLoopLatch();
1385 BranchInst *SplitTerminator =
1386 cast<BranchInst>(SplitCondBlock->getTerminator());
1387 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1388 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1389 if (L->getHeader() == SplitCondBlock
1390 && (Latch == Succ0 || Latch == Succ1))
1393 // If split condition branches heads do not have single predecessor,
1394 // SplitCondBlock, then is not possible to remove inactive branch.
1395 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1398 // If Exiting block includes loop variant instructions then this
1399 // loop may not be split safely.
1400 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1403 // After loop is cloned there are two loops.
1405 // First loop, referred as ALoop, executes first part of loop's iteration
1406 // space split. Second loop, referred as BLoop, executes remaining
1407 // part of loop's iteration space.
1409 // ALoop's exit edge enters BLoop's header through a forwarding block which
1410 // acts as a BLoop's preheader.
1411 BasicBlock *Preheader = L->getLoopPreheader();
1413 // Calculate ALoop induction variable's new exiting value and
1414 // BLoop induction variable's new starting value.
1415 calculateLoopBounds(SD);
1418 DenseMap<const Value *, Value *> ValueMap;
1419 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1421 BasicBlock *B_Header = BLoop->getHeader();
1423 //[*] ALoop's exiting edge BLoop's header.
1424 // ALoop's original exit block becomes BLoop's exit block.
1425 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1426 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1427 BranchInst *A_ExitInsn =
1428 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1429 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1430 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1431 if (L->contains(B_ExitBlock)) {
1432 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1433 A_ExitInsn->setSuccessor(0, B_Header);
1435 A_ExitInsn->setSuccessor(1, B_Header);
1437 //[*] Update ALoop's exit value using new exit value.
1438 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1440 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1441 // original loop's preheader. Add incoming PHINode values from
1442 // ALoop's exiting block. Update BLoop header's domiantor info.
1444 // Collect inverse map of Header PHINodes.
1445 DenseMap<Value *, Value *> InverseMap;
1446 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1447 BE = L->getHeader()->end(); BI != BE; ++BI) {
1448 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1449 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1450 InverseMap[PNClone] = PN;
1455 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1457 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1458 // Remove incoming value from original preheader.
1459 PN->removeIncomingValue(Preheader);
1461 // Add incoming value from A_ExitingBlock.
1463 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1465 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1467 // If loop header is also loop exiting block then
1468 // OrigPN is incoming value for B loop header.
1469 if (A_ExitingBlock == L->getHeader())
1472 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1473 PN->addIncoming(V2, A_ExitingBlock);
1478 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1479 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1481 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1482 // block. Remove incoming PHINode values from ALoop's exiting block.
1483 // Add new incoming values from BLoop's incoming exiting value.
1484 // Update BLoop exit block's dominator info..
1485 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1486 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1488 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1489 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1491 PN->removeIncomingValue(A_ExitingBlock);
1496 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1497 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1499 //[*] Split ALoop's exit edge. This creates a new block which
1500 // serves two purposes. First one is to hold PHINode defnitions
1501 // to ensure that ALoop's LCSSA form. Second use it to act
1502 // as a preheader for BLoop.
1503 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1505 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1506 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1507 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1509 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1510 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1511 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1512 newPHI->addIncoming(V1, A_ExitingBlock);
1513 A_ExitBlock->getInstList().push_front(newPHI);
1514 PN->removeIncomingValue(A_ExitBlock);
1515 PN->addIncoming(newPHI, A_ExitBlock);
1520 //[*] Eliminate split condition's inactive branch from ALoop.
1521 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1522 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1523 BasicBlock *A_InactiveBranch = NULL;
1524 BasicBlock *A_ActiveBranch = NULL;
1525 if (SD.UseTrueBranchFirst) {
1526 A_ActiveBranch = A_BR->getSuccessor(0);
1527 A_InactiveBranch = A_BR->getSuccessor(1);
1529 A_ActiveBranch = A_BR->getSuccessor(1);
1530 A_InactiveBranch = A_BR->getSuccessor(0);
1532 A_BR->setUnconditionalDest(A_ActiveBranch);
1533 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1535 //[*] Eliminate split condition's inactive branch in from BLoop.
1536 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1537 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1538 BasicBlock *B_InactiveBranch = NULL;
1539 BasicBlock *B_ActiveBranch = NULL;
1540 if (SD.UseTrueBranchFirst) {
1541 B_ActiveBranch = B_BR->getSuccessor(1);
1542 B_InactiveBranch = B_BR->getSuccessor(0);
1544 B_ActiveBranch = B_BR->getSuccessor(0);
1545 B_InactiveBranch = B_BR->getSuccessor(1);
1547 B_BR->setUnconditionalDest(B_ActiveBranch);
1548 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1550 BasicBlock *A_Header = L->getHeader();
1551 if (A_ExitingBlock == A_Header)
1554 //[*] Move exit condition into split condition block to avoid
1555 // executing dead loop iteration.
1556 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1557 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1558 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1560 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1561 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1564 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1565 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1570 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1571 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1572 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1573 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1575 BasicBlock *ExitingBB = EC->getParent();
1576 Instruction *CurrentBR = CondBB->getTerminator();
1578 // Move exit condition into split condition block.
1579 EC->moveBefore(CurrentBR);
1580 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1582 // Move exiting block's branch into split condition block. Update its branch
1584 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1585 ExitingBR->moveBefore(CurrentBR);
1586 BasicBlock *OrigDestBB = NULL;
1587 if (ExitingBR->getSuccessor(0) == ExitBB) {
1588 OrigDestBB = ExitingBR->getSuccessor(1);
1589 ExitingBR->setSuccessor(1, ActiveBB);
1592 OrigDestBB = ExitingBR->getSuccessor(0);
1593 ExitingBR->setSuccessor(0, ActiveBB);
1596 // Remove split condition and current split condition branch.
1597 SC->eraseFromParent();
1598 CurrentBR->eraseFromParent();
1600 // Connect exiting block to original destination.
1601 BranchInst::Create(OrigDestBB, ExitingBB);
1604 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1606 // Fix dominator info.
1607 // ExitBB is now dominated by CondBB
1608 DT->changeImmediateDominator(ExitBB, CondBB);
1609 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1611 // Basicblocks dominated by ActiveBB may have ExitingBB or
1612 // a basic block outside the loop in their DF list. If so,
1613 // replace it with CondBB.
1614 DomTreeNode *Node = DT->getNode(ActiveBB);
1615 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1617 BasicBlock *BB = DI->getBlock();
1618 DominanceFrontier::iterator BBDF = DF->find(BB);
1619 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1620 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1621 while (DomSetI != DomSetE) {
1622 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1624 BasicBlock *DFBB = *CurrentItr;
1625 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1626 BBDF->second.erase(DFBB);
1627 BBDF->second.insert(CondBB);
1633 /// updatePHINodes - CFG has been changed.
1635 /// - ExitBB's single predecessor was Latch
1636 /// - Latch's second successor was Header
1638 /// - ExitBB's single predecessor is Header
1639 /// - Latch's one and only successor is Header
1641 /// Update ExitBB PHINodes' to reflect this change.
1642 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1644 PHINode *IV, Instruction *IVIncrement,
1647 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1649 PHINode *PN = dyn_cast<PHINode>(BI);
1654 Value *V = PN->getIncomingValueForBlock(Latch);
1655 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1656 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1657 // in Header which is new incoming value for PN.
1659 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1661 if (PHINode *U = dyn_cast<PHINode>(*UI))
1662 if (LP->contains(U->getParent())) {
1667 // Add incoming value from header only if PN has any use inside the loop.
1669 PN->addIncoming(NewV, Header);
1671 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1672 // If this instruction is IVIncrement then IV is new incoming value
1673 // from header otherwise this instruction must be incoming value from
1674 // header because loop is in LCSSA form.
1675 if (PHI == IVIncrement)
1676 PN->addIncoming(IV, Header);
1678 PN->addIncoming(V, Header);
1680 // Otherwise this is an incoming value from header because loop is in
1682 PN->addIncoming(V, Header);
1684 // Remove incoming value from Latch.
1685 PN->removeIncomingValue(Latch);