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/Function.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpander.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include "llvm/Support/Compiler.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.addPreserved<DominatorTree>();
52 AU.addPreserved<DominanceFrontier>();
59 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
61 // Induction variable's range is split at this value.
64 // This compare instruction compares IndVar against SplitValue.
65 ICmpInst *SplitCondition;
70 SplitCondition = NULL;
76 /// Find condition inside a loop that is suitable candidate for index split.
77 void findSplitCondition();
79 /// Find loop's exit condition.
80 void findLoopConditionals();
82 /// Return induction variable associated with value V.
83 void findIndVar(Value *V, Loop *L);
85 /// processOneIterationLoop - Current loop L contains compare instruction
86 /// that compares induction variable, IndVar, agains loop invariant. If
87 /// entire (i.e. meaningful) loop body is dominated by this compare
88 /// instruction then loop body is executed only for one iteration. In
89 /// such case eliminate loop structure surrounding this loop body. For
90 bool processOneIterationLoop(SplitInfo &SD);
92 /// If loop header includes loop variant instruction operands then
93 /// this loop may not be eliminated.
94 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
96 /// If Exit block includes loop variant instructions then this
97 /// loop may not be eliminated.
98 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
100 /// removeBlocks - Remove basic block BB and all blocks dominated by BB.
101 void removeBlocks(BasicBlock *InBB);
103 /// Find cost of spliting loop L.
104 unsigned findSplitCost(Loop *L, SplitInfo &SD);
105 bool splitLoop(SplitInfo &SD);
109 IndVarIncrement = NULL;
110 ExitCondition = NULL;
124 DominanceFrontier *DF;
125 SmallVector<SplitInfo, 4> SplitData;
127 // Induction variable whose range is being split by this transformation.
129 Instruction *IndVarIncrement;
131 // Loop exit condition.
132 ICmpInst *ExitCondition;
134 // Induction variable's initial value.
137 // Induction variable's final loop exit value operand number in exit condition..
138 unsigned ExitValueNum;
141 char LoopIndexSplit::ID = 0;
142 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
145 LoopPass *llvm::createLoopIndexSplitPass() {
146 return new LoopIndexSplit();
149 // Index split Loop L. Return true if loop is split.
150 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
151 bool Changed = false;
155 SE = &getAnalysis<ScalarEvolution>();
156 DT = &getAnalysis<DominatorTree>();
157 LI = &getAnalysis<LoopInfo>();
158 DF = getAnalysisToUpdate<DominanceFrontier>();
162 findLoopConditionals();
167 findSplitCondition();
169 if (SplitData.empty())
172 // First see if it is possible to eliminate loop itself or not.
173 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
174 E = SplitData.end(); SI != E; ++SI) {
176 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
177 Changed = processOneIterationLoop(SD);
180 // If is loop is eliminated then nothing else to do here.
186 unsigned MaxCost = 99;
188 unsigned MostProfitableSDIndex = 0;
189 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
190 E = SplitData.end(); SI != E; ++SI, ++Index) {
193 // ICM_EQs are already handled above.
194 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
197 unsigned Cost = findSplitCost(L, SD);
199 MostProfitableSDIndex = Index;
202 // Split most profitiable condition.
203 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
211 /// Return true if V is a induction variable or induction variable's
212 /// increment for loop L.
213 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
215 Instruction *I = dyn_cast<Instruction>(V);
219 // Check if I is a phi node from loop header or not.
220 if (PHINode *PN = dyn_cast<PHINode>(V)) {
221 if (PN->getParent() == L->getHeader()) {
227 // Check if I is a add instruction whose one operand is
228 // phi node from loop header and second operand is constant.
229 if (I->getOpcode() != Instruction::Add)
232 Value *Op0 = I->getOperand(0);
233 Value *Op1 = I->getOperand(1);
235 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
236 if (PN->getParent() == L->getHeader()
237 && isa<ConstantInt>(Op1)) {
244 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
245 if (PN->getParent() == L->getHeader()
246 && isa<ConstantInt>(Op0)) {
256 // Find loop's exit condition and associated induction variable.
257 void LoopIndexSplit::findLoopConditionals() {
259 BasicBlock *ExitBlock = NULL;
261 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
264 if (!L->isLoopExit(BB))
274 // If exit block's terminator is conditional branch inst then we have found
276 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
277 if (!BR || BR->isUnconditional())
280 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
286 // Exit condition's one operand is loop invariant exit value and second
287 // operand is SCEVAddRecExpr based on induction variable.
288 Value *V0 = CI->getOperand(0);
289 Value *V1 = CI->getOperand(1);
291 SCEVHandle SH0 = SE->getSCEV(V0);
292 SCEVHandle SH1 = SE->getSCEV(V1);
294 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
298 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
304 ExitCondition = NULL;
306 BasicBlock *Preheader = L->getLoopPreheader();
307 StartValue = IndVar->getIncomingValueForBlock(Preheader);
311 /// Find condition inside a loop that is suitable candidate for index split.
312 void LoopIndexSplit::findSplitCondition() {
315 // Check all basic block's terminators.
317 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
321 // If this basic block does not terminate in a conditional branch
322 // then terminator is not a suitable split condition.
323 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
327 if (BR->isUnconditional())
330 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
331 if (!CI || CI == ExitCondition)
334 // If one operand is loop invariant and second operand is SCEVAddRecExpr
335 // based on induction variable then CI is a candidate split condition.
336 Value *V0 = CI->getOperand(0);
337 Value *V1 = CI->getOperand(1);
339 SCEVHandle SH0 = SE->getSCEV(V0);
340 SCEVHandle SH1 = SE->getSCEV(V1);
342 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
344 SD.SplitCondition = CI;
345 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
347 SplitData.push_back(SD);
349 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
350 if (IndVarIncrement && IndVarIncrement == Insn)
351 SplitData.push_back(SD);
354 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
356 SD.SplitCondition = CI;
357 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
359 SplitData.push_back(SD);
361 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
362 if (IndVarIncrement && IndVarIncrement == Insn)
363 SplitData.push_back(SD);
369 /// processOneIterationLoop - Current loop L contains compare instruction
370 /// that compares induction variable, IndVar, against loop invariant. If
371 /// entire (i.e. meaningful) loop body is dominated by this compare
372 /// instruction then loop body is executed only once. In such case eliminate
373 /// loop structure surrounding this loop body. For example,
374 /// for (int i = start; i < end; ++i) {
375 /// if ( i == somevalue) {
379 /// can be transformed into
380 /// if (somevalue >= start && somevalue < end) {
384 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
386 BasicBlock *Header = L->getHeader();
388 // First of all, check if SplitCondition dominates entire loop body
391 // If SplitCondition is not in loop header then this loop is not suitable
392 // for this transformation.
393 if (SD.SplitCondition->getParent() != Header)
396 // If loop header includes loop variant instruction operands then
397 // this loop may not be eliminated.
398 if (!safeHeader(SD, Header))
401 // If Exit block includes loop variant instructions then this
402 // loop may not be eliminated.
403 if (!safeExitBlock(SD, ExitCondition->getParent()))
408 // As a first step to break this loop, remove Latch to Header edge.
409 BasicBlock *Latch = L->getLoopLatch();
410 BasicBlock *LatchSucc = NULL;
411 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
414 Header->removePredecessor(Latch);
415 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
420 BR->setUnconditionalDest(LatchSucc);
422 BasicBlock *Preheader = L->getLoopPreheader();
423 Instruction *Terminator = Header->getTerminator();
424 StartValue = IndVar->getIncomingValueForBlock(Preheader);
426 // Replace split condition in header.
428 // SplitCondition : icmp eq i32 IndVar, SplitValue
430 // c1 = icmp uge i32 SplitValue, StartValue
431 // c2 = icmp ult i32 vSplitValue, ExitValue
433 bool SignedPredicate = ExitCondition->isSignedPredicate();
434 Instruction *C1 = new ICmpInst(SignedPredicate ?
435 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
436 SD.SplitValue, StartValue, "lisplit",
438 Instruction *C2 = new ICmpInst(SignedPredicate ?
439 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
441 ExitCondition->getOperand(ExitValueNum), "lisplit",
443 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
445 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
446 SD.SplitCondition->eraseFromParent();
448 // Now, clear latch block. Remove instructions that are responsible
449 // to increment induction variable.
450 Instruction *LTerminator = Latch->getTerminator();
451 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
455 if (isa<PHINode>(I) || I == LTerminator)
458 I->replaceAllUsesWith(UndefValue::get(I->getType()));
459 I->eraseFromParent();
462 LPM->deleteLoopFromQueue(L);
464 // Update Dominator Info.
465 // Only CFG change done is to remove Latch to Header edge. This
466 // does not change dominator tree because Latch did not dominate
469 DominanceFrontier::iterator HeaderDF = DF->find(Header);
470 if (HeaderDF != DF->end())
471 DF->removeFromFrontier(HeaderDF, Header);
473 DominanceFrontier::iterator LatchDF = DF->find(Latch);
474 if (LatchDF != DF->end())
475 DF->removeFromFrontier(LatchDF, Header);
480 // If loop header includes loop variant instruction operands then
481 // this loop can not be eliminated. This is used by processOneIterationLoop().
482 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
484 Instruction *Terminator = Header->getTerminator();
485 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
489 // PHI Nodes are OK. FIXME : Handle last value assignments.
493 // SplitCondition itself is OK.
494 if (I == SD.SplitCondition)
497 // Induction variable is OK.
501 // Induction variable increment is OK.
502 if (I == IndVarIncrement)
505 // Terminator is also harmless.
509 // Otherwise we have a instruction that may not be safe.
516 // If Exit block includes loop variant instructions then this
517 // loop may not be eliminated. This is used by processOneIterationLoop().
518 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
520 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
524 // PHI Nodes are OK. FIXME : Handle last value assignments.
528 // Induction variable increment is OK.
529 if (IndVarIncrement && IndVarIncrement == I)
532 // Check if I is induction variable increment instruction.
533 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
535 Value *Op0 = I->getOperand(0);
536 Value *Op1 = I->getOperand(1);
538 ConstantInt *CI = NULL;
540 if ((PN = dyn_cast<PHINode>(Op0))) {
541 if ((CI = dyn_cast<ConstantInt>(Op1)))
544 if ((PN = dyn_cast<PHINode>(Op1))) {
545 if ((CI = dyn_cast<ConstantInt>(Op0)))
549 if (IndVarIncrement && PN == IndVar && CI->isOne())
553 // I is an Exit condition if next instruction is block terminator.
554 // Exit condition is OK if it compares loop invariant exit value,
555 // which is checked below.
556 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
557 if (EC == ExitCondition)
561 if (I == ExitBlock->getTerminator())
564 // Otherwise we have instruction that may not be safe.
568 // We could not find any reason to consider ExitBlock unsafe.
572 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
573 /// Size is growth is calculated based on amount of code duplicated in second
575 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
578 BasicBlock *SDBlock = SD.SplitCondition->getParent();
579 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
582 // If a block is not dominated by split condition block then
583 // it must be duplicated in both loops.
584 if (!DT->dominates(SDBlock, BB))
591 /// removeBlocks - Remove basic block BB and all blocks dominated by BB.
592 void LoopIndexSplit::removeBlocks(BasicBlock *InBB) {
594 SmallVector<std::pair<BasicBlock *, succ_iterator>, 8> WorkList;
595 WorkList.push_back(std::make_pair(InBB, succ_begin(InBB)));
596 while (!WorkList.empty()) {
597 BasicBlock *BB = WorkList.back(). first;
598 succ_iterator SIter =WorkList.back().second;
600 // If all successor's are processed then remove this block.
601 if (SIter == succ_end(BB)) {
603 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
605 Instruction *I = BBI;
606 I->replaceAllUsesWith(UndefValue::get(I->getType()));
607 I->eraseFromParent();
612 BB->eraseFromParent();
614 BasicBlock *SuccBB = *SIter;
615 ++WorkList.back().second;
617 if (DT->dominates(BB, SuccBB)) {
618 WorkList.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
621 // If SuccBB is not dominated by BB then it is not removed, however remove
622 // any PHI incoming edge from BB.
623 for(BasicBlock::iterator SBI = SuccBB->begin(), SBE = SuccBB->end();
625 if (PHINode *PN = dyn_cast<PHINode>(SBI))
626 PN->removeIncomingValue(BB);
631 // If BB is not dominating SuccBB then SuccBB is in BB's dominance
633 DominanceFrontier::iterator BBDF = DF->find(BB);
634 DF->removeFromFrontier(BBDF, SuccBB);
640 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
642 BasicBlock *Preheader = L->getLoopPreheader();
644 // True loop is original loop. False loop is cloned loop.
646 bool SignedPredicate = ExitCondition->isSignedPredicate();
647 //[*] Calculate True loop's new Exit Value in loop preheader.
648 // TLExitValue = min(SplitValue, ExitValue)
649 //[*] Calculate False loop's new Start Value in loop preheader.
650 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
651 Value *TLExitValue = NULL;
652 Value *FLStartValue = NULL;
653 if (isa<ConstantInt>(SD.SplitValue)) {
654 TLExitValue = SD.SplitValue;
655 FLStartValue = SD.SplitValue;
658 Value *C1 = new ICmpInst(SignedPredicate ?
659 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
661 ExitCondition->getOperand(ExitValueNum),
663 Preheader->getTerminator());
664 TLExitValue = new SelectInst(C1, SD.SplitValue,
665 ExitCondition->getOperand(ExitValueNum),
666 "lsplit.ev", Preheader->getTerminator());
668 Value *C2 = new ICmpInst(SignedPredicate ?
669 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
670 SD.SplitValue, StartValue, "lsplit.sv",
671 Preheader->getTerminator());
672 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
673 "lsplit.sv", Preheader->getTerminator());
676 //[*] Clone loop. Avoid true destination of split condition and
677 // the blocks dominated by true destination.
678 DenseMap<const Value *, Value *> ValueMap;
679 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
680 BasicBlock *FalseHeader = FalseLoop->getHeader();
682 //[*] True loop's exit edge enters False loop.
683 PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
684 BasicBlock *ExitBlock = ExitCondition->getParent();
685 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
686 assert (ExitInsn && "Unable to find suitable loop exit branch");
687 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
689 for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
691 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
692 PN->removeIncomingValue(Preheader);
693 if (PN == IndVarClone)
694 PN->addIncoming(FLStartValue, ExitBlock);
695 // else { FIXME : Handl last value assignments.}
701 if (L->contains(ExitDest)) {
702 ExitDest = ExitInsn->getSuccessor(0);
703 ExitInsn->setSuccessor(0, FalseHeader);
705 ExitInsn->setSuccessor(1, FalseHeader);
708 DT->changeImmediateDominator(FalseHeader, ExitBlock);
709 DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
712 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
714 //[*] Split Exit Edge.
715 SplitEdge(ExitBlock, FalseHeader, this);
717 //[*] Eliminate split condition's false branch from True loop.
718 BasicBlock *SplitBlock = SD.SplitCondition->getParent();
719 BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
720 BasicBlock *FBB = BR->getSuccessor(1);
721 BR->setUnconditionalDest(BR->getSuccessor(0));
724 //[*] Update True loop's exit value using new exit value.
725 ExitCondition->setOperand(ExitValueNum, TLExitValue);
727 //[*] Eliminate split condition's true branch in False loop CFG.
728 BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
729 BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
730 BasicBlock *TBB = FBR->getSuccessor(0);
731 FBR->setUnconditionalDest(FBR->getSuccessor(1));