1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Index Splitting Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-index-split"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
28 STATISTIC(NumIndexSplit, "Number of loops index split");
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
46 AU.addRequired<LoopInfo>();
47 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
50 AU.addRequired<DominatorTree>();
51 AU.addRequired<DominanceFrontier>();
52 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
60 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
61 UseTrueBranchFirst(true), A_ExitValue(NULL),
64 // Induction variable's range is split at this value.
67 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
70 // True if after loop index split, first loop will execute split condition's
72 bool UseTrueBranchFirst;
74 // Exit value for first loop after loop split.
77 // Start value for second loop after loop split.
83 SplitCondition = NULL;
84 UseTrueBranchFirst = true;
93 // safeIcmpInst - CI is considered safe instruction if one of the operand
94 // is SCEVAddRecExpr based on induction variable and other operand is
95 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
99 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
102 /// Find loop's exit condition.
103 void findLoopConditionals();
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
108 /// processOneIterationLoop - Current loop L contains compare instruction
109 /// that compares induction variable, IndVar, agains loop invariant. If
110 /// entire (i.e. meaningful) loop body is dominated by this compare
111 /// instruction then loop body is executed only for one iteration. In
112 /// such case eliminate loop structure surrounding this loop body. For
113 bool processOneIterationLoop(SplitInfo &SD);
115 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);
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 E = SplitData.end(); SI != E;) {
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;
248 SplitData.erase(Delete_SI);
251 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
252 Changed = processOneIterationLoop(SD);
255 // If is loop is eliminated then nothing else to do here.
258 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
260 SplitData.erase(Delete_SI);
266 if (SplitData.empty())
269 // Split most profitiable condition.
270 // FIXME : Implement cost analysis.
271 unsigned MostProfitableSDIndex = 0;
272 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
280 /// Return true if V is a induction variable or induction variable's
281 /// increment for loop L.
282 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
284 Instruction *I = dyn_cast<Instruction>(V);
288 // Check if I is a phi node from loop header or not.
289 if (PHINode *PN = dyn_cast<PHINode>(V)) {
290 if (PN->getParent() == L->getHeader()) {
296 // Check if I is a add instruction whose one operand is
297 // phi node from loop header and second operand is constant.
298 if (I->getOpcode() != Instruction::Add)
301 Value *Op0 = I->getOperand(0);
302 Value *Op1 = I->getOperand(1);
304 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
305 if (PN->getParent() == L->getHeader()
306 && isa<ConstantInt>(Op1)) {
313 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
314 if (PN->getParent() == L->getHeader()
315 && isa<ConstantInt>(Op0)) {
325 // Find loop's exit condition and associated induction variable.
326 void LoopIndexSplit::findLoopConditionals() {
328 BasicBlock *ExitingBlock = NULL;
330 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
333 if (!L->isLoopExit(BB))
343 // If exiting block is neither loop header nor loop latch then this loop is
345 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
348 // If exit block's terminator is conditional branch inst then we have found
350 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
351 if (!BR || BR->isUnconditional())
354 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
359 if (CI->getPredicate() == ICmpInst::ICMP_EQ
360 || CI->getPredicate() == ICmpInst::ICMP_NE)
365 // Exit condition's one operand is loop invariant exit value and second
366 // operand is SCEVAddRecExpr based on induction variable.
367 Value *V0 = CI->getOperand(0);
368 Value *V1 = CI->getOperand(1);
370 SCEVHandle SH0 = SE->getSCEV(V0);
371 SCEVHandle SH1 = SE->getSCEV(V1);
373 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
377 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
383 ExitCondition = NULL;
385 BasicBlock *Preheader = L->getLoopPreheader();
386 StartValue = IndVar->getIncomingValueForBlock(Preheader);
390 /// Find condition inside a loop that is suitable candidate for index split.
391 void LoopIndexSplit::findSplitCondition() {
394 // Check all basic block's terminators.
395 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
400 // If this basic block does not terminate in a conditional branch
401 // then terminator is not a suitable split condition.
402 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
406 if (BR->isUnconditional())
409 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
410 if (AndI->getOpcode() == Instruction::And) {
411 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
412 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
417 if (!safeICmpInst(Op0, SD))
420 if (!safeICmpInst(Op1, SD))
423 SD.SplitCondition = AndI;
424 SplitData.push_back(SD);
428 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
429 if (!CI || CI == ExitCondition)
432 if (CI->getPredicate() == ICmpInst::ICMP_NE)
435 // If split condition predicate is GT or GE then first execute
436 // false branch of split condition.
437 if (CI->getPredicate() == ICmpInst::ICMP_UGT
438 || CI->getPredicate() == ICmpInst::ICMP_SGT
439 || CI->getPredicate() == ICmpInst::ICMP_UGE
440 || CI->getPredicate() == ICmpInst::ICMP_SGE)
441 SD.UseTrueBranchFirst = false;
443 // If one operand is loop invariant and second operand is SCEVAddRecExpr
444 // based on induction variable then CI is a candidate split condition.
445 if (safeICmpInst(CI, SD))
446 SplitData.push_back(SD);
450 // safeIcmpInst - CI is considered safe instruction if one of the operand
451 // is SCEVAddRecExpr based on induction variable and other operand is
452 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
454 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
456 Value *V0 = CI->getOperand(0);
457 Value *V1 = CI->getOperand(1);
459 SCEVHandle SH0 = SE->getSCEV(V0);
460 SCEVHandle SH1 = SE->getSCEV(V1);
462 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
464 SD.SplitCondition = CI;
465 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
469 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
470 if (IndVarIncrement && IndVarIncrement == Insn)
474 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
476 SD.SplitCondition = CI;
477 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
481 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
482 if (IndVarIncrement && IndVarIncrement == Insn)
490 /// processOneIterationLoop - Current loop L contains compare instruction
491 /// that compares induction variable, IndVar, against loop invariant. If
492 /// entire (i.e. meaningful) loop body is dominated by this compare
493 /// instruction then loop body is executed only once. In such case eliminate
494 /// loop structure surrounding this loop body. For example,
495 /// for (int i = start; i < end; ++i) {
496 /// if ( i == somevalue) {
500 /// can be transformed into
501 /// if (somevalue >= start && somevalue < end) {
505 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
507 BasicBlock *Header = L->getHeader();
509 // First of all, check if SplitCondition dominates entire loop body
512 // If SplitCondition is not in loop header then this loop is not suitable
513 // for this transformation.
514 if (SD.SplitCondition->getParent() != Header)
517 // If loop header includes loop variant instruction operands then
518 // this loop may not be eliminated.
519 if (!safeHeader(SD, Header))
522 // If Exiting block includes loop variant instructions then this
523 // loop may not be eliminated.
524 if (!safeExitingBlock(SD, ExitCondition->getParent()))
527 // Filter loops where split condition's false branch is not empty.
528 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
531 // If split condition is not safe then do not process this loop.
533 // for(int i = 0; i < N; i++) {
542 if (!safeSplitCondition(SD))
545 BasicBlock *Latch = L->getLoopLatch();
546 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
552 // Replace index variable with split value in loop body. Loop body is executed
553 // only when index variable is equal to split value.
554 IndVar->replaceAllUsesWith(SD.SplitValue);
556 // Remove Latch to Header edge.
557 BasicBlock *LatchSucc = NULL;
558 Header->removePredecessor(Latch);
559 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
564 BR->setUnconditionalDest(LatchSucc);
566 Instruction *Terminator = Header->getTerminator();
567 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
569 // Replace split condition in header.
571 // SplitCondition : icmp eq i32 IndVar, SplitValue
573 // c1 = icmp uge i32 SplitValue, StartValue
574 // c2 = icmp ult i32 SplitValue, ExitValue
576 bool SignedPredicate = ExitCondition->isSignedPredicate();
577 Instruction *C1 = new ICmpInst(SignedPredicate ?
578 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
579 SD.SplitValue, StartValue, "lisplit",
581 Instruction *C2 = new ICmpInst(SignedPredicate ?
582 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
583 SD.SplitValue, ExitValue, "lisplit",
585 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
587 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
588 SD.SplitCondition->eraseFromParent();
590 // Now, clear latch block. Remove instructions that are responsible
591 // to increment induction variable.
592 Instruction *LTerminator = Latch->getTerminator();
593 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
597 if (isa<PHINode>(I) || I == LTerminator)
600 if (I == IndVarIncrement)
601 I->replaceAllUsesWith(ExitValue);
603 I->replaceAllUsesWith(UndefValue::get(I->getType()));
604 I->eraseFromParent();
607 LPM->deleteLoopFromQueue(L);
609 // Update Dominator Info.
610 // Only CFG change done is to remove Latch to Header edge. This
611 // does not change dominator tree because Latch did not dominate
614 DominanceFrontier::iterator HeaderDF = DF->find(Header);
615 if (HeaderDF != DF->end())
616 DF->removeFromFrontier(HeaderDF, Header);
618 DominanceFrontier::iterator LatchDF = DF->find(Latch);
619 if (LatchDF != DF->end())
620 DF->removeFromFrontier(LatchDF, Header);
625 // If loop header includes loop variant instruction operands then
626 // this loop can not be eliminated. This is used by processOneIterationLoop().
627 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
629 Instruction *Terminator = Header->getTerminator();
630 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
638 // SplitCondition itself is OK.
639 if (I == SD.SplitCondition)
642 // Induction variable is OK.
646 // Induction variable increment is OK.
647 if (I == IndVarIncrement)
650 // Terminator is also harmless.
654 // Otherwise we have a instruction that may not be safe.
661 // If Exiting block includes loop variant instructions then this
662 // loop may not be eliminated. This is used by processOneIterationLoop().
663 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
664 BasicBlock *ExitingBlock) {
666 for (BasicBlock::iterator BI = ExitingBlock->begin(),
667 BE = ExitingBlock->end(); BI != BE; ++BI) {
674 // Induction variable increment is OK.
675 if (IndVarIncrement && IndVarIncrement == I)
678 // Check if I is induction variable increment instruction.
679 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
681 Value *Op0 = I->getOperand(0);
682 Value *Op1 = I->getOperand(1);
684 ConstantInt *CI = NULL;
686 if ((PN = dyn_cast<PHINode>(Op0))) {
687 if ((CI = dyn_cast<ConstantInt>(Op1)))
690 if ((PN = dyn_cast<PHINode>(Op1))) {
691 if ((CI = dyn_cast<ConstantInt>(Op0)))
695 if (IndVarIncrement && PN == IndVar && CI->isOne())
699 // I is an Exit condition if next instruction is block terminator.
700 // Exit condition is OK if it compares loop invariant exit value,
701 // which is checked below.
702 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
703 if (EC == ExitCondition)
707 if (I == ExitingBlock->getTerminator())
710 // Otherwise we have instruction that may not be safe.
714 // We could not find any reason to consider ExitingBlock unsafe.
718 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
720 Value *V0 = CI->getOperand(0);
721 Value *V1 = CI->getOperand(1);
724 SCEVHandle SH0 = SE->getSCEV(V0);
726 if (SH0->isLoopInvariant(L))
731 switch (CI->getPredicate()) {
732 case ICmpInst::ICMP_ULE:
733 case ICmpInst::ICMP_SLE:
734 // for (i = LB; i < UB; ++i)
735 // if (i <= NV && ...)
738 // is transformed into
739 // NUB = min (NV+1, UB)
740 // for (i = LB; i < NUB ; ++i)
746 // for (i = LB; i <= UB; ++i)
747 // if (i <= NV && ...)
750 // is transformed into
751 // NUB = min (NV, UB)
752 // for (i = LB; i <= NUB ; ++i)
756 case ICmpInst::ICMP_ULT:
757 case ICmpInst::ICMP_SLT:
758 // for (i = LB; i < UB; ++i)
759 // if (i < NV && ...)
762 // is transformed into
763 // NUB = min (NV, UB)
764 // for (i = LB; i < NUB ; ++i)
770 // for (i = LB; i <= UB; ++i)
771 // if (i < NV && ...)
774 // is transformed into
775 // NUB = min (NV -1 , UB)
776 // for (i = LB; i <= NUB ; ++i)
780 case ICmpInst::ICMP_UGE:
781 case ICmpInst::ICMP_SGE:
782 // for (i = LB; i (< or <=) UB; ++i)
783 // if (i >= NV && ...)
786 // is transformed into
787 // NLB = max (NV, LB)
788 // for (i = NLB; i (< or <=) UB ; ++i)
792 case ICmpInst::ICMP_UGT:
793 case ICmpInst::ICMP_SGT:
794 // for (i = LB; i (< or <=) UB; ++i)
795 // if (i > NV && ...)
798 // is transformed into
799 // NLB = max (NV+1, LB)
800 // for (i = NLB; i (< or <=) UB ; ++i)
805 assert ( 0 && "Unexpected split condition predicate");
808 /// updateLoopIterationSpace - Current loop body is covered by an AND
809 /// instruction whose operands compares induction variables with loop
810 /// invariants. If possible, hoist this check outside the loop by
811 /// updating appropriate start and end values for induction variable.
812 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
813 BasicBlock *Header = L->getHeader();
814 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
815 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
817 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
818 || Op0->getPredicate() == ICmpInst::ICMP_NE
819 || Op0->getPredicate() == ICmpInst::ICMP_EQ
820 || Op0->getPredicate() == ICmpInst::ICMP_NE)
823 // Check if SplitCondition dominates entire loop body
826 // If SplitCondition is not in loop header then this loop is not suitable
827 // for this transformation.
828 if (SD.SplitCondition->getParent() != Header)
831 // If loop header includes loop variant instruction operands then
832 // this loop may not be eliminated.
833 Instruction *Terminator = Header->getTerminator();
834 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
842 // SplitCondition itself is OK.
843 if (I == SD.SplitCondition)
845 if (I == Op0 || I == Op1)
848 // Induction variable is OK.
852 // Induction variable increment is OK.
853 if (I == IndVarIncrement)
856 // Terminator is also harmless.
860 // Otherwise we have a instruction that may not be safe.
864 // If Exiting block includes loop variant instructions then this
865 // loop may not be eliminated.
866 if (!safeExitingBlock(SD, ExitCondition->getParent()))
869 updateLoopBounds(Op0);
870 updateLoopBounds(Op1);
876 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
877 /// This routine is used to remove split condition's dead branch, dominated by
878 /// DeadBB. LiveBB dominates split conidition's other branch.
879 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
880 BasicBlock *LiveBB) {
882 // First update DeadBB's dominance frontier.
883 SmallVector<BasicBlock *, 8> FrontierBBs;
884 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
885 if (DeadBBDF != DF->end()) {
886 SmallVector<BasicBlock *, 8> PredBlocks;
888 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
889 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
890 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
891 BasicBlock *FrontierBB = *DeadBBSetI;
892 FrontierBBs.push_back(FrontierBB);
894 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
896 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
899 if (P == DeadBB || DT->dominates(DeadBB, P))
900 PredBlocks.push_back(P);
903 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
905 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
906 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
907 PE = PredBlocks.end(); PI != PE; ++PI) {
909 PN->removeIncomingValue(P);
918 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
919 SmallVector<BasicBlock *, 32> WorkList;
920 DomTreeNode *DN = DT->getNode(DeadBB);
921 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
922 E = df_end(DN); DI != E; ++DI) {
923 BasicBlock *BB = DI->getBlock();
924 WorkList.push_back(BB);
925 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
928 while (!WorkList.empty()) {
929 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
930 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
932 Instruction *I = BBI;
933 I->replaceAllUsesWith(UndefValue::get(I->getType()));
934 I->eraseFromParent();
936 LPM->deleteSimpleAnalysisValue(BB, LP);
940 BB->eraseFromParent();
943 // Update Frontier BBs' dominator info.
944 while (!FrontierBBs.empty()) {
945 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
946 BasicBlock *NewDominator = FBB->getSinglePredecessor();
948 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
951 if (NewDominator != LiveBB) {
952 for(; PI != PE; ++PI) {
955 NewDominator = LiveBB;
958 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
962 assert (NewDominator && "Unable to fix dominator info.");
963 DT->changeImmediateDominator(FBB, NewDominator);
964 DF->changeImmediateDominator(FBB, NewDominator, DT);
969 /// safeSplitCondition - Return true if it is possible to
970 /// split loop using given split condition.
971 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
973 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
974 BasicBlock *Latch = L->getLoopLatch();
975 BranchInst *SplitTerminator =
976 cast<BranchInst>(SplitCondBlock->getTerminator());
977 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
978 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
980 // Finally this split condition is safe only if merge point for
981 // split condition branch is loop latch. This check along with previous
982 // check, to ensure that exit condition is in either loop latch or header,
983 // filters all loops with non-empty loop body between merge point
984 // and exit condition.
985 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
986 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
987 if (Succ0DF->second.count(Latch))
990 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
991 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
992 if (Succ1DF->second.count(Latch))
998 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
999 /// based on split value.
1000 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1002 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1003 ICmpInst::Predicate SP = SC->getPredicate();
1004 const Type *Ty = SD.SplitValue->getType();
1005 bool Sign = ExitCondition->isSignedPredicate();
1006 BasicBlock *Preheader = L->getLoopPreheader();
1007 Instruction *PHTerminator = Preheader->getTerminator();
1009 // Initially use split value as upper loop bound for first loop and lower loop
1010 // bound for second loop.
1011 Value *AEV = SD.SplitValue;
1012 Value *BSV = SD.SplitValue;
1014 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1015 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1016 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1017 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)
1018 ExitCondition->swapOperands();
1020 switch (ExitCondition->getPredicate()) {
1021 case ICmpInst::ICMP_SGT:
1022 case ICmpInst::ICMP_UGT:
1023 case ICmpInst::ICMP_SGE:
1024 case ICmpInst::ICMP_UGE:
1026 assert (0 && "Unexpected exit condition predicate");
1028 case ICmpInst::ICMP_SLT:
1029 case ICmpInst::ICMP_ULT:
1032 case ICmpInst::ICMP_SLT:
1033 case ICmpInst::ICMP_ULT:
1035 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1037 // is transformed into
1039 // for (i = LB; i < min(UB, AEV); ++i)
1041 // for (i = max(LB, BSV); i < UB; ++i);
1044 case ICmpInst::ICMP_SLE:
1045 case ICmpInst::ICMP_ULE:
1048 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1050 // is transformed into
1054 // for (i = LB; i < min(UB, AEV); ++i)
1056 // for (i = max(LB, BSV); i < UB; ++i)
1058 BSV = BinaryOperator::createAdd(SD.SplitValue,
1059 ConstantInt::get(Ty, 1, Sign),
1060 "lsplit.add", PHTerminator);
1064 case ICmpInst::ICMP_SGE:
1065 case ICmpInst::ICMP_UGE:
1067 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1069 // is transformed into
1071 // for (i = LB; i < min(UB, AEV); ++i)
1073 // for (i = max(BSV, LB); i < UB; ++i)
1076 case ICmpInst::ICMP_SGT:
1077 case ICmpInst::ICMP_UGT:
1080 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1082 // is transformed into
1084 // BSV = AEV = SV + 1
1085 // for (i = LB; i < min(UB, AEV); ++i)
1087 // for (i = max(LB, BSV); i < UB; ++i)
1089 BSV = BinaryOperator::createAdd(SD.SplitValue,
1090 ConstantInt::get(Ty, 1, Sign),
1091 "lsplit.add", PHTerminator);
1096 assert (0 && "Unexpected split condition predicate");
1098 } // end switch (SP)
1101 case ICmpInst::ICMP_SLE:
1102 case ICmpInst::ICMP_ULE:
1105 case ICmpInst::ICMP_SLT:
1106 case ICmpInst::ICMP_ULT:
1108 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1110 // is transformed into
1113 // for (i = LB; i <= min(UB, AEV); ++i)
1115 // for (i = max(LB, BSV); i <= UB; ++i)
1117 AEV = BinaryOperator::createSub(SD.SplitValue,
1118 ConstantInt::get(Ty, 1, Sign),
1119 "lsplit.sub", PHTerminator);
1121 case ICmpInst::ICMP_SLE:
1122 case ICmpInst::ICMP_ULE:
1124 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1126 // is transformed into
1129 // for (i = LB; i <= min(UB, AEV); ++i)
1131 // for (i = max(LB, BSV); i <= UB; ++i)
1133 BSV = BinaryOperator::createAdd(SD.SplitValue,
1134 ConstantInt::get(Ty, 1, Sign),
1135 "lsplit.add", PHTerminator);
1137 case ICmpInst::ICMP_SGT:
1138 case ICmpInst::ICMP_UGT:
1140 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1142 // is transformed into
1145 // for (i = LB; i <= min(AEV, UB); ++i)
1147 // for (i = max(LB, BSV); i <= UB; ++i)
1149 BSV = BinaryOperator::createAdd(SD.SplitValue,
1150 ConstantInt::get(Ty, 1, Sign),
1151 "lsplit.add", PHTerminator);
1153 case ICmpInst::ICMP_SGE:
1154 case ICmpInst::ICMP_UGE:
1157 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1159 // is transformed into
1162 // for (i = LB; i <= min(AEV, UB); ++i)
1164 // for (i = max(LB, BSV); i <= UB; ++i)
1166 AEV = BinaryOperator::createSub(SD.SplitValue,
1167 ConstantInt::get(Ty, 1, Sign),
1168 "lsplit.sub", PHTerminator);
1171 assert (0 && "Unexpected split condition predicate");
1173 } // end switch (SP)
1178 // Calculate ALoop induction variable's new exiting value and
1179 // BLoop induction variable's new starting value. Calculuate these
1180 // values in original loop's preheader.
1181 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1182 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
1183 Value *C1 = new ICmpInst(Sign ?
1184 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1186 ExitCondition->getOperand(ExitValueNum),
1187 "lsplit.ev", PHTerminator);
1188 SD.A_ExitValue = new SelectInst(C1, AEV,
1189 ExitCondition->getOperand(ExitValueNum),
1190 "lsplit.ev", PHTerminator);
1192 Value *C2 = new ICmpInst(Sign ?
1193 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1194 BSV, StartValue, "lsplit.sv",
1196 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1197 "lsplit.sv", PHTerminator);
1200 /// splitLoop - Split current loop L in two loops using split information
1201 /// SD. Update dominator information. Maintain LCSSA form.
1202 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1204 if (!safeSplitCondition(SD))
1207 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1209 // Unable to handle triange loops at the moment.
1210 // In triangle loop, split condition is in header and one of the
1211 // the split destination is loop latch. If split condition is EQ
1212 // then such loops are already handle in processOneIterationLoop().
1213 BasicBlock *Latch = L->getLoopLatch();
1214 BranchInst *SplitTerminator =
1215 cast<BranchInst>(SplitCondBlock->getTerminator());
1216 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1217 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1218 if (L->getHeader() == SplitCondBlock
1219 && (Latch == Succ0 || Latch == Succ1))
1222 // If split condition branches heads do not have single predecessor,
1223 // SplitCondBlock, then is not possible to remove inactive branch.
1224 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1227 // After loop is cloned there are two loops.
1229 // First loop, referred as ALoop, executes first part of loop's iteration
1230 // space split. Second loop, referred as BLoop, executes remaining
1231 // part of loop's iteration space.
1233 // ALoop's exit edge enters BLoop's header through a forwarding block which
1234 // acts as a BLoop's preheader.
1235 BasicBlock *Preheader = L->getLoopPreheader();
1237 // Calculate ALoop induction variable's new exiting value and
1238 // BLoop induction variable's new starting value.
1239 calculateLoopBounds(SD);
1242 DenseMap<const Value *, Value *> ValueMap;
1243 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1245 BasicBlock *B_Header = BLoop->getHeader();
1247 //[*] ALoop's exiting edge BLoop's header.
1248 // ALoop's original exit block becomes BLoop's exit block.
1249 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1250 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1251 BranchInst *A_ExitInsn =
1252 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1253 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1254 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1255 if (L->contains(B_ExitBlock)) {
1256 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1257 A_ExitInsn->setSuccessor(0, B_Header);
1259 A_ExitInsn->setSuccessor(1, B_Header);
1261 //[*] Update ALoop's exit value using new exit value.
1262 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1264 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1265 // original loop's preheader. Add incoming PHINode values from
1266 // ALoop's exiting block. Update BLoop header's domiantor info.
1268 // Collect inverse map of Header PHINodes.
1269 DenseMap<Value *, Value *> InverseMap;
1270 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1271 BE = L->getHeader()->end(); BI != BE; ++BI) {
1272 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1273 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1274 InverseMap[PNClone] = PN;
1279 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1281 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1282 // Remove incoming value from original preheader.
1283 PN->removeIncomingValue(Preheader);
1285 // Add incoming value from A_ExitingBlock.
1287 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1289 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1290 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1291 PN->addIncoming(V2, A_ExitingBlock);
1296 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1297 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1299 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1300 // block. Remove incoming PHINode values from ALoop's exiting block.
1301 // Add new incoming values from BLoop's incoming exiting value.
1302 // Update BLoop exit block's dominator info..
1303 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1304 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1306 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1307 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1309 PN->removeIncomingValue(A_ExitingBlock);
1314 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1315 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1317 //[*] Split ALoop's exit edge. This creates a new block which
1318 // serves two purposes. First one is to hold PHINode defnitions
1319 // to ensure that ALoop's LCSSA form. Second use it to act
1320 // as a preheader for BLoop.
1321 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1323 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1324 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1325 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1327 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1328 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1329 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1330 newPHI->addIncoming(V1, A_ExitingBlock);
1331 A_ExitBlock->getInstList().push_front(newPHI);
1332 PN->removeIncomingValue(A_ExitBlock);
1333 PN->addIncoming(newPHI, A_ExitBlock);
1338 //[*] Eliminate split condition's inactive branch from ALoop.
1339 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1340 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1341 BasicBlock *A_InactiveBranch = NULL;
1342 BasicBlock *A_ActiveBranch = NULL;
1343 if (SD.UseTrueBranchFirst) {
1344 A_ActiveBranch = A_BR->getSuccessor(0);
1345 A_InactiveBranch = A_BR->getSuccessor(1);
1347 A_ActiveBranch = A_BR->getSuccessor(1);
1348 A_InactiveBranch = A_BR->getSuccessor(0);
1350 A_BR->setUnconditionalDest(A_ActiveBranch);
1351 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1353 //[*] Eliminate split condition's inactive branch in from BLoop.
1354 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1355 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1356 BasicBlock *B_InactiveBranch = NULL;
1357 BasicBlock *B_ActiveBranch = NULL;
1358 if (SD.UseTrueBranchFirst) {
1359 B_ActiveBranch = B_BR->getSuccessor(1);
1360 B_InactiveBranch = B_BR->getSuccessor(0);
1362 B_ActiveBranch = B_BR->getSuccessor(0);
1363 B_InactiveBranch = B_BR->getSuccessor(1);
1365 B_BR->setUnconditionalDest(B_ActiveBranch);
1366 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1368 BasicBlock *A_Header = L->getHeader();
1369 if (A_ExitingBlock == A_Header)
1372 //[*] Move exit condition into split condition block to avoid
1373 // executing dead loop iteration.
1374 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1375 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1376 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1378 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1379 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1382 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1383 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1388 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1389 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1390 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1391 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1393 BasicBlock *ExitingBB = EC->getParent();
1394 Instruction *CurrentBR = CondBB->getTerminator();
1396 // Move exit condition into split condition block.
1397 EC->moveBefore(CurrentBR);
1398 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1400 // Move exiting block's branch into split condition block. Update its branch
1402 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1403 ExitingBR->moveBefore(CurrentBR);
1404 if (ExitingBR->getSuccessor(0) == ExitBB)
1405 ExitingBR->setSuccessor(1, ActiveBB);
1407 ExitingBR->setSuccessor(0, ActiveBB);
1409 // Remove split condition and current split condition branch.
1410 SC->eraseFromParent();
1411 CurrentBR->eraseFromParent();
1413 // Connect exiting block to split condition block.
1414 new BranchInst(CondBB, ExitingBB);
1417 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1419 // Fix dominator info.
1420 // ExitBB is now dominated by CondBB
1421 DT->changeImmediateDominator(ExitBB, CondBB);
1422 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1424 // Basicblocks dominated by ActiveBB may have ExitingBB or
1425 // a basic block outside the loop in their DF list. If so,
1426 // replace it with CondBB.
1427 DomTreeNode *Node = DT->getNode(ActiveBB);
1428 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1430 BasicBlock *BB = DI->getBlock();
1431 DominanceFrontier::iterator BBDF = DF->find(BB);
1432 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1433 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1434 while (DomSetI != DomSetE) {
1435 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1437 BasicBlock *DFBB = *CurrentItr;
1438 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1439 BBDF->second.erase(DFBB);
1440 BBDF->second.insert(CondBB);
1446 /// updatePHINodes - CFG has been changed.
1448 /// - ExitBB's single predecessor was Latch
1449 /// - Latch's second successor was Header
1451 /// - ExitBB's single predecessor was Header
1452 /// - Latch's one and only successor was Header
1454 /// Update ExitBB PHINodes' to reflect this change.
1455 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1457 PHINode *IV, Instruction *IVIncrement) {
1459 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1461 PHINode *PN = dyn_cast<PHINode>(BI);
1465 Value *V = PN->getIncomingValueForBlock(Latch);
1466 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1467 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1469 // The second use is in Header and it is new incoming value for PN.
1473 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1476 U1 = cast<PHINode>(*UI);
1478 U2 = cast<PHINode>(*UI);
1480 assert ( 0 && "Unexpected third use of this PHINode");
1482 assert (U1 && U2 && "Unable to find two uses");
1484 if (U1->getParent() == Header)
1488 PN->addIncoming(NewV, Header);
1490 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1491 // If this instruction is IVIncrement then IV is new incoming value
1492 // from header otherwise this instruction must be incoming value from
1493 // header because loop is in LCSSA form.
1494 if (PHI == IVIncrement)
1495 PN->addIncoming(IV, Header);
1497 PN->addIncoming(V, Header);
1499 // Otherwise this is an incoming value from header because loop is in
1501 PN->addIncoming(V, Header);
1503 // Remove incoming value from Latch.
1504 PN->removeIncomingValue(Latch);