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(&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 /// isOneIterationLoop - Return true if split condition is EQ and
116 /// the IV is not used outside the loop.
117 bool isOneIterationLoop(ICmpInst *CI);
119 void updateLoopBounds(ICmpInst *CI);
120 /// updateLoopIterationSpace - Current loop body is covered by an AND
121 /// instruction whose operands compares induction variables with loop
122 /// invariants. If possible, hoist this check outside the loop by
123 /// updating appropriate start and end values for induction variable.
124 bool updateLoopIterationSpace(SplitInfo &SD);
126 /// If loop header includes loop variant instruction operands then
127 /// this loop may not be eliminated.
128 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
130 /// If Exiting block includes loop variant instructions then this
131 /// loop may not be eliminated.
132 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
134 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
135 /// This routine is used to remove split condition's dead branch, dominated by
136 /// DeadBB. LiveBB dominates split conidition's other branch.
137 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
139 /// safeSplitCondition - Return true if it is possible to
140 /// split loop using given split condition.
141 bool safeSplitCondition(SplitInfo &SD);
143 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
144 /// based on split value.
145 void calculateLoopBounds(SplitInfo &SD);
147 /// updatePHINodes - CFG has been changed.
149 /// - ExitBB's single predecessor was Latch
150 /// - Latch's second successor was Header
152 /// - ExitBB's single predecessor was Header
153 /// - Latch's one and only successor was Header
155 /// Update ExitBB PHINodes' to reflect this change.
156 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
158 PHINode *IV, Instruction *IVIncrement, Loop *LP);
160 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
161 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
162 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
163 PHINode *IV, Instruction *IVAdd, Loop *LP);
165 /// splitLoop - Split current loop L in two loops using split information
166 /// SD. Update dominator information. Maintain LCSSA form.
167 bool splitLoop(SplitInfo &SD);
171 IndVarIncrement = NULL;
172 ExitCondition = NULL;
186 DominanceFrontier *DF;
187 SmallVector<SplitInfo, 4> SplitData;
189 // Induction variable whose range is being split by this transformation.
191 Instruction *IndVarIncrement;
193 // Loop exit condition.
194 ICmpInst *ExitCondition;
196 // Induction variable's initial value.
199 // Induction variable's final loop exit value operand number in exit condition..
200 unsigned ExitValueNum;
204 char LoopIndexSplit::ID = 0;
205 static RegisterPass<LoopIndexSplit>
206 X("loop-index-split", "Index Split Loops");
208 LoopPass *llvm::createLoopIndexSplitPass() {
209 return new LoopIndexSplit();
212 // Index split Loop L. Return true if loop is split.
213 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
214 bool Changed = false;
218 // FIXME - Nested loops make dominator info updates tricky.
219 if (!L->getSubLoops().empty())
222 SE = &getAnalysis<ScalarEvolution>();
223 DT = &getAnalysis<DominatorTree>();
224 LI = &getAnalysis<LoopInfo>();
225 DF = &getAnalysis<DominanceFrontier>();
229 findLoopConditionals();
234 findSplitCondition();
236 if (SplitData.empty())
239 // First see if it is possible to eliminate loop itself or not.
240 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
241 SI != SplitData.end();) {
243 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
244 if (SD.SplitCondition->getOpcode() == Instruction::And) {
245 Changed = updateLoopIterationSpace(SD);
248 // If is loop is eliminated then nothing else to do here.
251 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
252 SI = SplitData.erase(Delete_SI);
255 else if (isOneIterationLoop(CI)) {
256 Changed = processOneIterationLoop(SD);
259 // If is loop is eliminated then nothing else to do here.
262 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
263 SI = SplitData.erase(Delete_SI);
269 if (SplitData.empty())
272 // Split most profitiable condition.
273 // FIXME : Implement cost analysis.
274 unsigned MostProfitableSDIndex = 0;
275 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
283 /// isOneIterationLoop - Return true if split condition is EQ and
284 /// the IV is not used outside the loop.
285 bool LoopIndexSplit::isOneIterationLoop(ICmpInst *CI) {
288 if (CI->getPredicate() != ICmpInst::ICMP_EQ)
291 Value *Incr = IndVar->getIncomingValueForBlock(L->getLoopLatch());
292 for (Value::use_iterator UI = Incr->use_begin(), E = Incr->use_end();
294 if (!L->contains(cast<Instruction>(*UI)->getParent()))
299 /// Return true if V is a induction variable or induction variable's
300 /// increment for loop L.
301 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
303 Instruction *I = dyn_cast<Instruction>(V);
307 // Check if I is a phi node from loop header or not.
308 if (PHINode *PN = dyn_cast<PHINode>(V)) {
309 if (PN->getParent() == L->getHeader()) {
315 // Check if I is a add instruction whose one operand is
316 // phi node from loop header and second operand is constant.
317 if (I->getOpcode() != Instruction::Add)
320 Value *Op0 = I->getOperand(0);
321 Value *Op1 = I->getOperand(1);
323 if (PHINode *PN = dyn_cast<PHINode>(Op0))
324 if (PN->getParent() == L->getHeader())
325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
332 if (PHINode *PN = dyn_cast<PHINode>(Op1))
333 if (PN->getParent() == L->getHeader())
334 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
344 // Find loop's exit condition and associated induction variable.
345 void LoopIndexSplit::findLoopConditionals() {
347 BasicBlock *ExitingBlock = NULL;
349 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
352 if (!L->isLoopExit(BB))
362 // If exiting block is neither loop header nor loop latch then this loop is
364 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
367 // If exit block's terminator is conditional branch inst then we have found
369 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
370 if (!BR || BR->isUnconditional())
373 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
378 if (CI->getPredicate() == ICmpInst::ICMP_EQ
379 || CI->getPredicate() == ICmpInst::ICMP_NE)
384 // Exit condition's one operand is loop invariant exit value and second
385 // operand is SCEVAddRecExpr based on induction variable.
386 Value *V0 = CI->getOperand(0);
387 Value *V1 = CI->getOperand(1);
389 SCEVHandle SH0 = SE->getSCEV(V0);
390 SCEVHandle SH1 = SE->getSCEV(V1);
392 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
396 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
402 ExitCondition = NULL;
404 BasicBlock *Preheader = L->getLoopPreheader();
405 StartValue = IndVar->getIncomingValueForBlock(Preheader);
408 // If start value is more then exit value where induction variable
409 // increments by 1 then we are potentially dealing with an infinite loop.
410 // Do not index split this loop.
412 ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
414 dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
415 if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
416 ExitCondition = NULL;
417 else if (EV && EV->isZero())
418 ExitCondition = NULL;
422 /// Find condition inside a loop that is suitable candidate for index split.
423 void LoopIndexSplit::findSplitCondition() {
426 // Check all basic block's terminators.
427 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
432 // If this basic block does not terminate in a conditional branch
433 // then terminator is not a suitable split condition.
434 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
438 if (BR->isUnconditional())
441 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
442 if (AndI->getOpcode() == Instruction::And) {
443 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
444 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
449 if (!safeICmpInst(Op0, SD))
452 if (!safeICmpInst(Op1, SD))
455 SD.SplitCondition = AndI;
456 SplitData.push_back(SD);
460 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
461 if (!CI || CI == ExitCondition)
464 if (CI->getPredicate() == ICmpInst::ICMP_NE)
467 // If split condition predicate is GT or GE then first execute
468 // false branch of split condition.
469 if (CI->getPredicate() == ICmpInst::ICMP_UGT
470 || CI->getPredicate() == ICmpInst::ICMP_SGT
471 || CI->getPredicate() == ICmpInst::ICMP_UGE
472 || CI->getPredicate() == ICmpInst::ICMP_SGE)
473 SD.UseTrueBranchFirst = false;
475 // If one operand is loop invariant and second operand is SCEVAddRecExpr
476 // based on induction variable then CI is a candidate split condition.
477 if (safeICmpInst(CI, SD))
478 SplitData.push_back(SD);
482 // safeIcmpInst - CI is considered safe instruction if one of the operand
483 // is SCEVAddRecExpr based on induction variable and other operand is
484 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
486 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
488 Value *V0 = CI->getOperand(0);
489 Value *V1 = CI->getOperand(1);
491 SCEVHandle SH0 = SE->getSCEV(V0);
492 SCEVHandle SH1 = SE->getSCEV(V1);
494 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
496 SD.SplitCondition = CI;
497 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
501 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
502 if (IndVarIncrement && IndVarIncrement == Insn)
506 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
508 SD.SplitCondition = CI;
509 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
513 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
514 if (IndVarIncrement && IndVarIncrement == Insn)
522 /// processOneIterationLoop - Current loop L contains compare instruction
523 /// that compares induction variable, IndVar, against loop invariant. If
524 /// entire (i.e. meaningful) loop body is dominated by this compare
525 /// instruction then loop body is executed only once. In such case eliminate
526 /// loop structure surrounding this loop body. For example,
527 /// for (int i = start; i < end; ++i) {
528 /// if ( i == somevalue) {
532 /// can be transformed into
533 /// if (somevalue >= start && somevalue < end) {
537 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
539 BasicBlock *Header = L->getHeader();
541 // First of all, check if SplitCondition dominates entire loop body
544 // If SplitCondition is not in loop header then this loop is not suitable
545 // for this transformation.
546 if (SD.SplitCondition->getParent() != Header)
549 // If loop header includes loop variant instruction operands then
550 // this loop may not be eliminated.
551 if (!safeHeader(SD, Header))
554 // If Exiting block includes loop variant instructions then this
555 // loop may not be eliminated.
556 if (!safeExitingBlock(SD, ExitCondition->getParent()))
559 // Filter loops where split condition's false branch is not empty.
560 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
563 // If split condition is not safe then do not process this loop.
565 // for(int i = 0; i < N; i++) {
574 if (!safeSplitCondition(SD))
577 BasicBlock *Latch = L->getLoopLatch();
578 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
584 // Replace index variable with split value in loop body. Loop body is executed
585 // only when index variable is equal to split value.
586 IndVar->replaceAllUsesWith(SD.SplitValue);
588 Instruction *LTerminator = Latch->getTerminator();
589 Instruction *Terminator = Header->getTerminator();
590 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
592 // Replace split condition in header.
594 // SplitCondition : icmp eq i32 IndVar, SplitValue
596 // c1 = icmp uge i32 SplitValue, StartValue
597 // c2 = icmp ult i32 SplitValue, ExitValue
599 bool SignedPredicate = ExitCondition->isSignedPredicate();
600 CmpInst::Predicate C2Predicate = ExitCondition->getPredicate();
601 if (LTerminator->getOperand(0) != Header)
602 C2Predicate = CmpInst::getInversePredicate(C2Predicate);
603 Instruction *C1 = new ICmpInst(SignedPredicate ?
604 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
605 SD.SplitValue, StartValue, "lisplit",
607 Instruction *C2 = new ICmpInst(C2Predicate,
608 SD.SplitValue, ExitValue, "lisplit",
610 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
612 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
613 SD.SplitCondition->eraseFromParent();
615 // Remove Latch to Header edge.
616 BasicBlock *LatchSucc = NULL;
617 Header->removePredecessor(Latch);
618 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
623 BR->setUnconditionalDest(LatchSucc);
625 // Now, clear latch block. Remove instructions that are responsible
626 // to increment induction variable.
627 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
631 if (isa<PHINode>(I) || I == LTerminator)
634 if (I == IndVarIncrement) {
635 // Replace induction variable increment if it is not used outside
637 bool UsedOutsideLoop = false;
638 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
640 if (Instruction *Use = dyn_cast<Instruction>(UI))
641 if (!L->contains(Use->getParent())) {
642 UsedOutsideLoop = true;
646 if (!UsedOutsideLoop) {
647 I->replaceAllUsesWith(ExitValue);
648 I->eraseFromParent();
652 I->replaceAllUsesWith(UndefValue::get(I->getType()));
653 I->eraseFromParent();
657 LPM->deleteLoopFromQueue(L);
659 // Update Dominator Info.
660 // Only CFG change done is to remove Latch to Header edge. This
661 // does not change dominator tree because Latch did not dominate
664 DominanceFrontier::iterator HeaderDF = DF->find(Header);
665 if (HeaderDF != DF->end())
666 DF->removeFromFrontier(HeaderDF, Header);
668 DominanceFrontier::iterator LatchDF = DF->find(Latch);
669 if (LatchDF != DF->end())
670 DF->removeFromFrontier(LatchDF, Header);
675 // If loop header includes loop variant instruction operands then
676 // this loop can not be eliminated. This is used by processOneIterationLoop().
677 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
679 Instruction *Terminator = Header->getTerminator();
680 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
688 // SplitCondition itself is OK.
689 if (I == SD.SplitCondition)
692 // Induction variable is OK.
696 // Induction variable increment is OK.
697 if (I == IndVarIncrement)
700 // Terminator is also harmless.
704 // Otherwise we have a instruction that may not be safe.
711 // If Exiting block includes loop variant instructions then this
712 // loop may not be eliminated. This is used by processOneIterationLoop().
713 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
714 BasicBlock *ExitingBlock) {
716 for (BasicBlock::iterator BI = ExitingBlock->begin(),
717 BE = ExitingBlock->end(); BI != BE; ++BI) {
724 // Induction variable increment is OK.
725 if (IndVarIncrement && IndVarIncrement == I)
728 // Check if I is induction variable increment instruction.
729 if (I->getOpcode() == Instruction::Add) {
731 Value *Op0 = I->getOperand(0);
732 Value *Op1 = I->getOperand(1);
734 ConstantInt *CI = NULL;
736 if ((PN = dyn_cast<PHINode>(Op0))) {
737 if ((CI = dyn_cast<ConstantInt>(Op1)))
739 if (!IndVarIncrement && PN == IndVar)
741 // else this is another loop induction variable
745 if ((PN = dyn_cast<PHINode>(Op1))) {
746 if ((CI = dyn_cast<ConstantInt>(Op0)))
748 if (!IndVarIncrement && PN == IndVar)
750 // else this is another loop induction variable
756 // I is an Exit condition if next instruction is block terminator.
757 // Exit condition is OK if it compares loop invariant exit value,
758 // which is checked below.
759 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
760 if (EC == ExitCondition)
764 if (I == ExitingBlock->getTerminator())
767 // Otherwise we have instruction that may not be safe.
771 // We could not find any reason to consider ExitingBlock unsafe.
775 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
777 Value *V0 = CI->getOperand(0);
778 Value *V1 = CI->getOperand(1);
781 SCEVHandle SH0 = SE->getSCEV(V0);
783 if (SH0->isLoopInvariant(L))
788 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
789 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
790 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
791 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
792 ExitCondition->swapOperands();
801 Value *UB = ExitCondition->getOperand(ExitValueNum);
802 const Type *Ty = NV->getType();
803 bool Sign = ExitCondition->isSignedPredicate();
804 BasicBlock *Preheader = L->getLoopPreheader();
805 Instruction *PHTerminator = Preheader->getTerminator();
807 assert (NV && "Unexpected value");
809 switch (CI->getPredicate()) {
810 case ICmpInst::ICMP_ULE:
811 case ICmpInst::ICMP_SLE:
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 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
822 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
823 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
824 "lsplit.add", PHTerminator);
825 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
826 A, UB,"lsplit,c", PHTerminator);
827 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
830 // for (i = LB; i <= UB; ++i)
831 // if (i <= NV && ...)
834 // is transformed into
835 // NUB = min (NV, UB)
836 // for (i = LB; i <= NUB ; ++i)
839 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
840 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
841 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
842 NV, UB, "lsplit.c", PHTerminator);
843 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
846 case ICmpInst::ICMP_ULT:
847 case ICmpInst::ICMP_SLT:
848 // for (i = LB; i < UB; ++i)
849 // if (i < NV && ...)
852 // is transformed into
853 // NUB = min (NV, UB)
854 // for (i = LB; i < NUB ; ++i)
857 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
858 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
859 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
860 NV, UB, "lsplit.c", PHTerminator);
861 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
864 // for (i = LB; i <= UB; ++i)
865 // if (i < NV && ...)
868 // is transformed into
869 // NUB = min (NV -1 , UB)
870 // for (i = LB; i <= NUB ; ++i)
873 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
874 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
875 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
876 "lsplit.add", PHTerminator);
877 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
878 S, UB, "lsplit.c", PHTerminator);
879 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
882 case ICmpInst::ICMP_UGE:
883 case ICmpInst::ICMP_SGE:
884 // for (i = LB; i (< or <=) UB; ++i)
885 // if (i >= NV && ...)
888 // is transformed into
889 // NLB = max (NV, LB)
890 // for (i = NLB; i (< or <=) UB ; ++i)
894 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
895 NV, StartValue, "lsplit.c", PHTerminator);
896 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
899 case ICmpInst::ICMP_UGT:
900 case ICmpInst::ICMP_SGT:
901 // for (i = LB; i (< or <=) UB; ++i)
902 // if (i > NV && ...)
905 // is transformed into
906 // NLB = max (NV+1, LB)
907 // for (i = NLB; i (< or <=) UB ; ++i)
911 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
912 "lsplit.add", PHTerminator);
913 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
914 A, StartValue, "lsplit.c", PHTerminator);
915 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
919 assert ( 0 && "Unexpected split condition predicate");
923 unsigned i = IndVar->getBasicBlockIndex(Preheader);
924 IndVar->setIncomingValue(i, NLB);
928 ExitCondition->setOperand(ExitValueNum, NUB);
931 /// updateLoopIterationSpace - Current loop body is covered by an AND
932 /// instruction whose operands compares induction variables with loop
933 /// invariants. If possible, hoist this check outside the loop by
934 /// updating appropriate start and end values for induction variable.
935 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
936 BasicBlock *Header = L->getHeader();
937 BasicBlock *ExitingBlock = ExitCondition->getParent();
938 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
940 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
941 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
943 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
944 || Op0->getPredicate() == ICmpInst::ICMP_NE
945 || Op1->getPredicate() == ICmpInst::ICMP_EQ
946 || Op1->getPredicate() == ICmpInst::ICMP_NE)
949 // Check if SplitCondition dominates entire loop body
952 // If SplitCondition is not in loop header then this loop is not suitable
953 // for this transformation.
954 if (SD.SplitCondition->getParent() != Header)
957 // If loop header includes loop variant instruction operands then
958 // this loop may not be eliminated.
959 Instruction *Terminator = Header->getTerminator();
960 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
968 // SplitCondition itself is OK.
969 if (I == SD.SplitCondition)
971 if (I == Op0 || I == Op1)
974 // Induction variable is OK.
978 // Induction variable increment is OK.
979 if (I == IndVarIncrement)
982 // Terminator is also harmless.
986 // Otherwise we have a instruction that may not be safe.
990 // If Exiting block includes loop variant instructions then this
991 // loop may not be eliminated.
992 if (!safeExitingBlock(SD, ExitCondition->getParent()))
995 // Verify that loop exiting block has only two predecessor, where one predecessor
996 // is split condition block. The other predecessor will become exiting block's
997 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
998 // more then two predecessors. This requires extra work in updating dominator
1000 BasicBlock *ExitingBBPred = NULL;
1001 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
1003 BasicBlock *BB = *PI;
1004 if (SplitCondBlock == BB)
1012 // Update loop bounds to absorb Op0 check.
1013 updateLoopBounds(Op0);
1014 // Update loop bounds to absorb Op1 check.
1015 updateLoopBounds(Op1);
1019 // Unconditionally connect split block to its remaining successor.
1020 BranchInst *SplitTerminator =
1021 cast<BranchInst>(SplitCondBlock->getTerminator());
1022 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1023 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1024 if (Succ0 == ExitCondition->getParent())
1025 SplitTerminator->setUnconditionalDest(Succ1);
1027 SplitTerminator->setUnconditionalDest(Succ0);
1029 // Remove split condition.
1030 SD.SplitCondition->eraseFromParent();
1031 if (Op0->use_empty())
1032 Op0->eraseFromParent();
1033 if (Op1->use_empty())
1034 Op1->eraseFromParent();
1036 BranchInst *ExitInsn =
1037 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1038 assert (ExitInsn && "Unable to find suitable loop exit branch");
1039 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1040 if (L->contains(ExitBlock))
1041 ExitBlock = ExitInsn->getSuccessor(0);
1043 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1044 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1045 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1047 // If ExitingBlock is a member of loop BB's DF list then replace it with
1048 // loop header and exit block.
1049 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1051 BasicBlock *BB = *I;
1052 if (BB == Header || BB == ExitingBlock)
1054 DominanceFrontier::iterator BBDF = DF->find(BB);
1055 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1056 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1057 while (DomSetI != DomSetE) {
1058 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1060 BasicBlock *DFBB = *CurrentItr;
1061 if (DFBB == ExitingBlock) {
1062 BBDF->second.erase(DFBB);
1063 BBDF->second.insert(Header);
1064 if (Header != ExitingBlock)
1065 BBDF->second.insert(ExitBlock);
1074 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1075 /// This routine is used to remove split condition's dead branch, dominated by
1076 /// DeadBB. LiveBB dominates split conidition's other branch.
1077 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1078 BasicBlock *LiveBB) {
1080 // First update DeadBB's dominance frontier.
1081 SmallVector<BasicBlock *, 8> FrontierBBs;
1082 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1083 if (DeadBBDF != DF->end()) {
1084 SmallVector<BasicBlock *, 8> PredBlocks;
1086 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1087 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1088 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1089 BasicBlock *FrontierBB = *DeadBBSetI;
1090 FrontierBBs.push_back(FrontierBB);
1092 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1094 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1096 BasicBlock *P = *PI;
1097 if (P == DeadBB || DT->dominates(DeadBB, P))
1098 PredBlocks.push_back(P);
1101 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1102 FBI != FBE; ++FBI) {
1103 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1104 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1105 PE = PredBlocks.end(); PI != PE; ++PI) {
1106 BasicBlock *P = *PI;
1107 PN->removeIncomingValue(P);
1116 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1117 SmallVector<BasicBlock *, 32> WorkList;
1118 DomTreeNode *DN = DT->getNode(DeadBB);
1119 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1120 E = df_end(DN); DI != E; ++DI) {
1121 BasicBlock *BB = DI->getBlock();
1122 WorkList.push_back(BB);
1123 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1126 while (!WorkList.empty()) {
1127 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1128 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
1130 Instruction *I = BBI;
1132 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1133 I->eraseFromParent();
1135 LPM->deleteSimpleAnalysisValue(BB, LP);
1137 DF->removeBlock(BB);
1138 LI->removeBlock(BB);
1139 BB->eraseFromParent();
1142 // Update Frontier BBs' dominator info.
1143 while (!FrontierBBs.empty()) {
1144 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1145 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1146 if (!NewDominator) {
1147 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1150 if (NewDominator != LiveBB) {
1151 for(; PI != PE; ++PI) {
1152 BasicBlock *P = *PI;
1154 NewDominator = LiveBB;
1157 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1161 assert (NewDominator && "Unable to fix dominator info.");
1162 DT->changeImmediateDominator(FBB, NewDominator);
1163 DF->changeImmediateDominator(FBB, NewDominator, DT);
1168 /// safeSplitCondition - Return true if it is possible to
1169 /// split loop using given split condition.
1170 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1172 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1173 BasicBlock *Latch = L->getLoopLatch();
1174 BranchInst *SplitTerminator =
1175 cast<BranchInst>(SplitCondBlock->getTerminator());
1176 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1177 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1179 // If split block does not dominate the latch then this is not a diamond.
1180 // Such loop may not benefit from index split.
1181 if (!DT->dominates(SplitCondBlock, Latch))
1184 // Finally this split condition is safe only if merge point for
1185 // split condition branch is loop latch. This check along with previous
1186 // check, to ensure that exit condition is in either loop latch or header,
1187 // filters all loops with non-empty loop body between merge point
1188 // and exit condition.
1189 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1190 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1191 if (Succ0DF->second.count(Latch))
1194 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1195 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1196 if (Succ1DF->second.count(Latch))
1202 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1203 /// based on split value.
1204 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1206 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1207 ICmpInst::Predicate SP = SC->getPredicate();
1208 const Type *Ty = SD.SplitValue->getType();
1209 bool Sign = ExitCondition->isSignedPredicate();
1210 BasicBlock *Preheader = L->getLoopPreheader();
1211 Instruction *PHTerminator = Preheader->getTerminator();
1213 // Initially use split value as upper loop bound for first loop and lower loop
1214 // bound for second loop.
1215 Value *AEV = SD.SplitValue;
1216 Value *BSV = SD.SplitValue;
1218 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1219 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1220 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1221 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1222 ExitCondition->swapOperands();
1229 switch (ExitCondition->getPredicate()) {
1230 case ICmpInst::ICMP_SGT:
1231 case ICmpInst::ICMP_UGT:
1232 case ICmpInst::ICMP_SGE:
1233 case ICmpInst::ICMP_UGE:
1235 assert (0 && "Unexpected exit condition predicate");
1237 case ICmpInst::ICMP_SLT:
1238 case ICmpInst::ICMP_ULT:
1241 case ICmpInst::ICMP_SLT:
1242 case ICmpInst::ICMP_ULT:
1244 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1246 // is transformed into
1248 // for (i = LB; i < min(UB, AEV); ++i)
1250 // for (i = max(LB, BSV); i < UB; ++i);
1253 case ICmpInst::ICMP_SLE:
1254 case ICmpInst::ICMP_ULE:
1257 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1259 // is transformed into
1263 // for (i = LB; i < min(UB, AEV); ++i)
1265 // for (i = max(LB, BSV); i < UB; ++i)
1267 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1268 ConstantInt::get(Ty, 1, Sign),
1269 "lsplit.add", PHTerminator);
1273 case ICmpInst::ICMP_SGE:
1274 case ICmpInst::ICMP_UGE:
1276 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1278 // is transformed into
1280 // for (i = LB; i < min(UB, AEV); ++i)
1282 // for (i = max(BSV, LB); i < UB; ++i)
1285 case ICmpInst::ICMP_SGT:
1286 case ICmpInst::ICMP_UGT:
1289 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1291 // is transformed into
1293 // BSV = AEV = SV + 1
1294 // for (i = LB; i < min(UB, AEV); ++i)
1296 // for (i = max(LB, BSV); i < UB; ++i)
1298 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1299 ConstantInt::get(Ty, 1, Sign),
1300 "lsplit.add", PHTerminator);
1305 assert (0 && "Unexpected split condition predicate");
1307 } // end switch (SP)
1310 case ICmpInst::ICMP_SLE:
1311 case ICmpInst::ICMP_ULE:
1314 case ICmpInst::ICMP_SLT:
1315 case ICmpInst::ICMP_ULT:
1317 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1319 // is transformed into
1322 // for (i = LB; i <= min(UB, AEV); ++i)
1324 // for (i = max(LB, BSV); i <= UB; ++i)
1326 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1327 ConstantInt::get(Ty, 1, Sign),
1328 "lsplit.sub", PHTerminator);
1330 case ICmpInst::ICMP_SLE:
1331 case ICmpInst::ICMP_ULE:
1333 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1335 // is transformed into
1338 // for (i = LB; i <= min(UB, AEV); ++i)
1340 // for (i = max(LB, BSV); i <= UB; ++i)
1342 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1343 ConstantInt::get(Ty, 1, Sign),
1344 "lsplit.add", PHTerminator);
1346 case ICmpInst::ICMP_SGT:
1347 case ICmpInst::ICMP_UGT:
1349 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1351 // is transformed into
1354 // for (i = LB; i <= min(AEV, UB); ++i)
1356 // for (i = max(LB, BSV); i <= UB; ++i)
1358 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1359 ConstantInt::get(Ty, 1, Sign),
1360 "lsplit.add", PHTerminator);
1362 case ICmpInst::ICMP_SGE:
1363 case ICmpInst::ICMP_UGE:
1366 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1368 // is transformed into
1371 // for (i = LB; i <= min(AEV, UB); ++i)
1373 // for (i = max(LB, BSV); i <= UB; ++i)
1375 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1376 ConstantInt::get(Ty, 1, Sign),
1377 "lsplit.sub", PHTerminator);
1380 assert (0 && "Unexpected split condition predicate");
1382 } // end switch (SP)
1387 // Calculate ALoop induction variable's new exiting value and
1388 // BLoop induction variable's new starting value. Calculuate these
1389 // values in original loop's preheader.
1390 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1391 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
1392 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1394 // If ExitValue operand is also defined in Loop header then
1395 // insert new ExitValue after this operand definition.
1396 if (Instruction *EVN =
1397 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1398 if (!isa<PHINode>(EVN))
1399 if (InsertPt->getParent() == EVN->getParent()) {
1400 BasicBlock::iterator LHBI = L->getHeader()->begin();
1401 BasicBlock::iterator LHBE = L->getHeader()->end();
1402 for(;LHBI != LHBE; ++LHBI) {
1403 Instruction *I = LHBI;
1410 Value *C1 = new ICmpInst(Sign ?
1411 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1413 ExitCondition->getOperand(ExitValueNum),
1414 "lsplit.ev", InsertPt);
1416 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1417 ExitCondition->getOperand(ExitValueNum),
1418 "lsplit.ev", InsertPt);
1420 Value *C2 = new ICmpInst(Sign ?
1421 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1422 BSV, StartValue, "lsplit.sv",
1424 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1425 "lsplit.sv", PHTerminator);
1428 /// splitLoop - Split current loop L in two loops using split information
1429 /// SD. Update dominator information. Maintain LCSSA form.
1430 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1432 if (!safeSplitCondition(SD))
1435 // If split condition EQ is not handled.
1436 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(SD.SplitCondition)) {
1437 if (ICMP->getPredicate() == ICmpInst::ICMP_EQ)
1441 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1443 // Unable to handle triangle loops at the moment.
1444 // In triangle loop, split condition is in header and one of the
1445 // the split destination is loop latch. If split condition is EQ
1446 // then such loops are already handle in processOneIterationLoop().
1447 BasicBlock *Latch = L->getLoopLatch();
1448 BranchInst *SplitTerminator =
1449 cast<BranchInst>(SplitCondBlock->getTerminator());
1450 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1451 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1452 if (L->getHeader() == SplitCondBlock
1453 && (Latch == Succ0 || Latch == Succ1))
1456 // If split condition branches heads do not have single predecessor,
1457 // SplitCondBlock, then is not possible to remove inactive branch.
1458 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1461 // If Exiting block includes loop variant instructions then this
1462 // loop may not be split safely.
1463 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1466 // After loop is cloned there are two loops.
1468 // First loop, referred as ALoop, executes first part of loop's iteration
1469 // space split. Second loop, referred as BLoop, executes remaining
1470 // part of loop's iteration space.
1472 // ALoop's exit edge enters BLoop's header through a forwarding block which
1473 // acts as a BLoop's preheader.
1474 BasicBlock *Preheader = L->getLoopPreheader();
1476 // Calculate ALoop induction variable's new exiting value and
1477 // BLoop induction variable's new starting value.
1478 calculateLoopBounds(SD);
1481 DenseMap<const Value *, Value *> ValueMap;
1482 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1484 BasicBlock *B_Header = BLoop->getHeader();
1486 //[*] ALoop's exiting edge BLoop's header.
1487 // ALoop's original exit block becomes BLoop's exit block.
1488 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1489 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1490 BranchInst *A_ExitInsn =
1491 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1492 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1493 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1494 if (L->contains(B_ExitBlock)) {
1495 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1496 A_ExitInsn->setSuccessor(0, B_Header);
1498 A_ExitInsn->setSuccessor(1, B_Header);
1500 //[*] Update ALoop's exit value using new exit value.
1501 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1503 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1504 // original loop's preheader. Add incoming PHINode values from
1505 // ALoop's exiting block. Update BLoop header's domiantor info.
1507 // Collect inverse map of Header PHINodes.
1508 DenseMap<Value *, Value *> InverseMap;
1509 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1510 BE = L->getHeader()->end(); BI != BE; ++BI) {
1511 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1512 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1513 InverseMap[PNClone] = PN;
1518 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1520 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1521 // Remove incoming value from original preheader.
1522 PN->removeIncomingValue(Preheader);
1524 // Add incoming value from A_ExitingBlock.
1526 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1528 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1530 // If loop header is also loop exiting block then
1531 // OrigPN is incoming value for B loop header.
1532 if (A_ExitingBlock == L->getHeader())
1535 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1536 PN->addIncoming(V2, A_ExitingBlock);
1541 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1542 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1544 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1545 // block. Remove incoming PHINode values from ALoop's exiting block.
1546 // Add new incoming values from BLoop's incoming exiting value.
1547 // Update BLoop exit block's dominator info..
1548 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1549 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1551 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1552 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1554 PN->removeIncomingValue(A_ExitingBlock);
1559 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1560 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1562 //[*] Split ALoop's exit edge. This creates a new block which
1563 // serves two purposes. First one is to hold PHINode defnitions
1564 // to ensure that ALoop's LCSSA form. Second use it to act
1565 // as a preheader for BLoop.
1566 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1568 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1569 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1570 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1572 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1573 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1574 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1575 newPHI->addIncoming(V1, A_ExitingBlock);
1576 A_ExitBlock->getInstList().push_front(newPHI);
1577 PN->removeIncomingValue(A_ExitBlock);
1578 PN->addIncoming(newPHI, A_ExitBlock);
1583 //[*] Eliminate split condition's inactive branch from ALoop.
1584 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1585 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1586 BasicBlock *A_InactiveBranch = NULL;
1587 BasicBlock *A_ActiveBranch = NULL;
1588 if (SD.UseTrueBranchFirst) {
1589 A_ActiveBranch = A_BR->getSuccessor(0);
1590 A_InactiveBranch = A_BR->getSuccessor(1);
1592 A_ActiveBranch = A_BR->getSuccessor(1);
1593 A_InactiveBranch = A_BR->getSuccessor(0);
1595 A_BR->setUnconditionalDest(A_ActiveBranch);
1596 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1598 //[*] Eliminate split condition's inactive branch in from BLoop.
1599 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1600 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1601 BasicBlock *B_InactiveBranch = NULL;
1602 BasicBlock *B_ActiveBranch = NULL;
1603 if (SD.UseTrueBranchFirst) {
1604 B_ActiveBranch = B_BR->getSuccessor(1);
1605 B_InactiveBranch = B_BR->getSuccessor(0);
1607 B_ActiveBranch = B_BR->getSuccessor(0);
1608 B_InactiveBranch = B_BR->getSuccessor(1);
1610 B_BR->setUnconditionalDest(B_ActiveBranch);
1611 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1613 BasicBlock *A_Header = L->getHeader();
1614 if (A_ExitingBlock == A_Header)
1617 //[*] Move exit condition into split condition block to avoid
1618 // executing dead loop iteration.
1619 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1620 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1621 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1623 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1624 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1627 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1628 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1633 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1634 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1635 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1636 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1638 BasicBlock *ExitingBB = EC->getParent();
1639 Instruction *CurrentBR = CondBB->getTerminator();
1641 // Move exit condition into split condition block.
1642 EC->moveBefore(CurrentBR);
1643 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1645 // Move exiting block's branch into split condition block. Update its branch
1647 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1648 ExitingBR->moveBefore(CurrentBR);
1649 BasicBlock *OrigDestBB = NULL;
1650 if (ExitingBR->getSuccessor(0) == ExitBB) {
1651 OrigDestBB = ExitingBR->getSuccessor(1);
1652 ExitingBR->setSuccessor(1, ActiveBB);
1655 OrigDestBB = ExitingBR->getSuccessor(0);
1656 ExitingBR->setSuccessor(0, ActiveBB);
1659 // Remove split condition and current split condition branch.
1660 SC->eraseFromParent();
1661 CurrentBR->eraseFromParent();
1663 // Connect exiting block to original destination.
1664 BranchInst::Create(OrigDestBB, ExitingBB);
1667 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1669 // Fix dominator info.
1670 // ExitBB is now dominated by CondBB
1671 DT->changeImmediateDominator(ExitBB, CondBB);
1672 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1674 // Basicblocks dominated by ActiveBB may have ExitingBB or
1675 // a basic block outside the loop in their DF list. If so,
1676 // replace it with CondBB.
1677 DomTreeNode *Node = DT->getNode(ActiveBB);
1678 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1680 BasicBlock *BB = DI->getBlock();
1681 DominanceFrontier::iterator BBDF = DF->find(BB);
1682 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1683 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1684 while (DomSetI != DomSetE) {
1685 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1687 BasicBlock *DFBB = *CurrentItr;
1688 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1689 BBDF->second.erase(DFBB);
1690 BBDF->second.insert(CondBB);
1696 /// updatePHINodes - CFG has been changed.
1698 /// - ExitBB's single predecessor was Latch
1699 /// - Latch's second successor was Header
1701 /// - ExitBB's single predecessor is Header
1702 /// - Latch's one and only successor is Header
1704 /// Update ExitBB PHINodes' to reflect this change.
1705 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1707 PHINode *IV, Instruction *IVIncrement,
1710 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1712 PHINode *PN = dyn_cast<PHINode>(BI);
1717 Value *V = PN->getIncomingValueForBlock(Latch);
1718 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1719 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1720 // in Header which is new incoming value for PN.
1722 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1724 if (PHINode *U = dyn_cast<PHINode>(*UI))
1725 if (LP->contains(U->getParent())) {
1730 // Add incoming value from header only if PN has any use inside the loop.
1732 PN->addIncoming(NewV, Header);
1734 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1735 // If this instruction is IVIncrement then IV is new incoming value
1736 // from header otherwise this instruction must be incoming value from
1737 // header because loop is in LCSSA form.
1738 if (PHI == IVIncrement)
1739 PN->addIncoming(IV, Header);
1741 PN->addIncoming(V, Header);
1743 // Otherwise this is an incoming value from header because loop is in
1745 PN->addIncoming(V, Header);
1747 // Remove incoming value from Latch.
1748 PN->removeIncomingValue(Latch);