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/Support/Compiler.h"
22 #include "llvm/ADT/Statistic.h"
26 STATISTIC(NumIndexSplit, "Number of loops index split");
30 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33 static char ID; // Pass ID, replacement for typeid
34 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
36 // Index split Loop L. Return true if loop is split.
37 bool runOnLoop(Loop *L, LPPassManager &LPM);
39 void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<ScalarEvolution>();
41 AU.addPreserved<ScalarEvolution>();
42 AU.addRequiredID(LCSSAID);
43 AU.addPreservedID(LCSSAID);
44 AU.addPreserved<LoopInfo>();
45 AU.addRequiredID(LoopSimplifyID);
46 AU.addPreservedID(LoopSimplifyID);
47 AU.addRequired<DominatorTree>();
48 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
56 SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
57 SplitCondition(NULL), ExitCondition(NULL),
58 IndVarIncrement(NULL) {}
60 // Induction variable whose range is being split by this transformation.
63 // Induction variable's range is split at this value.
66 // Induction variable's final loop exit value.
69 // This compare instruction compares IndVar against SplitValue.
70 ICmpInst *SplitCondition;
72 // Loop exit condition.
73 ICmpInst *ExitCondition;
75 Instruction *IndVarIncrement;
82 SplitCondition = NULL;
84 IndVarIncrement = NULL;
87 /// Return true if V is a induction variable or induction variable's
88 /// increment for loop L.
89 bool findIndVar(Value *V, Loop *L);
93 /// Find condition inside a loop that is suitable candidate for index split.
94 void findSplitCondition();
96 /// processOneIterationLoop - Current loop L contains compare instruction
97 /// that compares induction variable, IndVar, agains loop invariant. If
98 /// entire (i.e. meaningful) loop body is dominated by this compare
99 /// instruction then loop body is executed only for one iteration. In
100 /// such case eliminate loop structure surrounding this loop body. For
101 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
103 /// If loop header includes loop variant instruction operands then
104 /// this loop may not be eliminated.
105 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
107 /// If Exit block includes loop variant instructions then this
108 /// loop may not be eliminated.
109 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
111 /// Find cost of spliting loop L.
112 unsigned findSplitCost(Loop *L, SplitInfo &SD);
113 bool splitLoop(SplitInfo &SD);
121 SmallVector<SplitInfo, 4> SplitData;
124 char LoopIndexSplit::ID = 0;
125 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
128 LoopPass *llvm::createLoopIndexSplitPass() {
129 return new LoopIndexSplit();
132 // Index split Loop L. Return true if loop is split.
133 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
134 bool Changed = false;
137 SE = &getAnalysis<ScalarEvolution>();
138 DT = &getAnalysis<DominatorTree>();
140 findSplitCondition();
142 if (SplitData.empty())
145 // First see if it is possible to eliminate loop itself or not.
146 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
147 E = SplitData.end(); SI != E; ++SI) {
149 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
150 Changed = processOneIterationLoop(SD,LPM);
153 // If is loop is eliminated then nothing else to do here.
159 unsigned MaxCost = 99;
161 unsigned MostProfitableSDIndex = 0;
162 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
163 E = SplitData.end(); SI != E; ++SI, ++Index) {
166 // ICM_EQs are already handled above.
167 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
170 unsigned Cost = findSplitCost(L, SD);
172 MostProfitableSDIndex = Index;
175 // Split most profitiable condition.
176 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
184 /// Return true if V is a induction variable or induction variable's
185 /// increment for loop L.
186 bool LoopIndexSplit::SplitInfo::findIndVar(Value *V, Loop *L) {
188 Instruction *I = dyn_cast<Instruction>(V);
192 // Check if I is a phi node from loop header or not.
193 if (PHINode *PN = dyn_cast<PHINode>(V)) {
194 if (PN->getParent() == L->getHeader()) {
200 // Check if I is a add instruction whose one operand is
201 // phi node from loop header and second operand is constant.
202 if (I->getOpcode() != Instruction::Add)
205 Value *Op0 = I->getOperand(0);
206 Value *Op1 = I->getOperand(1);
208 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
209 if (PN->getParent() == L->getHeader()
210 && isa<ConstantInt>(Op1)) {
217 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
218 if (PN->getParent() == L->getHeader()
219 && isa<ConstantInt>(Op0)) {
229 /// Find condition inside a loop that is suitable candidate for index split.
230 void LoopIndexSplit::findSplitCondition() {
233 // Check all basic block's terminators.
235 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
239 // If this basic block does not terminate in a conditional branch
240 // then terminator is not a suitable split condition.
241 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
245 if (BR->isUnconditional())
248 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
252 // If one operand is loop invariant and second operand is SCEVAddRecExpr
253 // based on induction variable then CI is a candidate split condition.
254 Value *V0 = CI->getOperand(0);
255 Value *V1 = CI->getOperand(1);
257 SCEVHandle SH0 = SE->getSCEV(V0);
258 SCEVHandle SH1 = SE->getSCEV(V1);
260 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
262 SD.SplitCondition = CI;
263 if (SD.findIndVar(V1, L))
264 SplitData.push_back(SD);
266 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
268 SD.SplitCondition = CI;
269 if (SD.findIndVar(V0, L))
270 SplitData.push_back(SD);
275 /// processOneIterationLoop - Current loop L contains compare instruction
276 /// that compares induction variable, IndVar, against loop invariant. If
277 /// entire (i.e. meaningful) loop body is dominated by this compare
278 /// instruction then loop body is executed only once. In such case eliminate
279 /// loop structure surrounding this loop body. For example,
280 /// for (int i = start; i < end; ++i) {
281 /// if ( i == somevalue) {
285 /// can be transformed into
286 /// if (somevalue >= start && somevalue < end) {
290 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
292 BasicBlock *Header = L->getHeader();
294 // First of all, check if SplitCondition dominates entire loop body
297 // If SplitCondition is not in loop header then this loop is not suitable
298 // for this transformation.
299 if (SD.SplitCondition->getParent() != Header)
302 // If one of the Header block's successor is not an exit block then this
303 // loop is not a suitable candidate.
304 BasicBlock *ExitBlock = NULL;
305 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
306 if (L->isLoopExit(*SI)) {
315 // If loop header includes loop variant instruction operands then
316 // this loop may not be eliminated.
317 if (!safeHeader(SD, Header))
320 // If Exit block includes loop variant instructions then this
321 // loop may not be eliminated.
322 if (!safeExitBlock(SD, ExitBlock))
327 // As a first step to break this loop, remove Latch to Header edge.
328 BasicBlock *Latch = L->getLoopLatch();
329 BasicBlock *LatchSucc = NULL;
330 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
333 Header->removePredecessor(Latch);
334 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
339 BR->setUnconditionalDest(LatchSucc);
341 BasicBlock *Preheader = L->getLoopPreheader();
342 Instruction *Terminator = Header->getTerminator();
343 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
345 // Replace split condition in header.
347 // SplitCondition : icmp eq i32 IndVar, SplitValue
349 // c1 = icmp uge i32 SplitValue, StartValue
350 // c2 = icmp ult i32 vSplitValue, ExitValue
352 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
353 Instruction *C1 = new ICmpInst(SignedPredicate ?
354 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
355 SD.SplitValue, StartValue, "lisplit",
357 Instruction *C2 = new ICmpInst(SignedPredicate ?
358 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
359 SD.SplitValue, SD.ExitValue, "lisplit",
361 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
363 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
364 SD.SplitCondition->eraseFromParent();
366 // Now, clear latch block. Remove instructions that are responsible
367 // to increment induction variable.
368 Instruction *LTerminator = Latch->getTerminator();
369 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
373 if (isa<PHINode>(I) || I == LTerminator)
376 I->replaceAllUsesWith(UndefValue::get(I->getType()));
377 I->eraseFromParent();
380 LPM.deleteLoopFromQueue(L);
382 // Update Dominator Info.
383 // Only CFG change done is to remove Latch to Header edge. This
384 // does not change dominator tree because Latch did not dominate
386 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
387 DominanceFrontier::iterator HeaderDF = DF->find(Header);
388 if (HeaderDF != DF->end())
389 DF->removeFromFrontier(HeaderDF, Header);
391 DominanceFrontier::iterator LatchDF = DF->find(Latch);
392 if (LatchDF != DF->end())
393 DF->removeFromFrontier(LatchDF, Header);
398 // If loop header includes loop variant instruction operands then
399 // this loop can not be eliminated. This is used by processOneIterationLoop().
400 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
402 Instruction *Terminator = Header->getTerminator();
403 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
407 // PHI Nodes are OK. FIXME : Handle last value assignments.
411 // SplitCondition itself is OK.
412 if (I == SD.SplitCondition)
415 // Induction variable is OK.
419 // Induction variable increment is OK.
420 if (I == SD.IndVarIncrement)
423 // Terminator is also harmless.
427 // Otherwise we have a instruction that may not be safe.
434 // If Exit block includes loop variant instructions then this
435 // loop may not be eliminated. This is used by processOneIterationLoop().
436 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
438 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
442 // PHI Nodes are OK. FIXME : Handle last value assignments.
446 // Induction variable increment is OK.
447 if (SD.IndVarIncrement && SD.IndVarIncrement == I)
450 // Check if I is induction variable increment instruction.
451 if (!SD.IndVarIncrement && I->getOpcode() == Instruction::Add) {
453 Value *Op0 = I->getOperand(0);
454 Value *Op1 = I->getOperand(1);
456 ConstantInt *CI = NULL;
458 if ((PN = dyn_cast<PHINode>(Op0))) {
459 if ((CI = dyn_cast<ConstantInt>(Op1)))
460 SD.IndVarIncrement = I;
462 if ((PN = dyn_cast<PHINode>(Op1))) {
463 if ((CI = dyn_cast<ConstantInt>(Op0)))
464 SD.IndVarIncrement = I;
467 if (SD.IndVarIncrement && PN == SD.IndVar && CI->isOne())
471 // I is an Exit condition if next instruction is block terminator.
472 // Exit condition is OK if it compares loop invariant exit value,
473 // which is checked below.
474 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
477 if (N == ExitBlock->getTerminator()) {
478 SD.ExitCondition = EC;
483 // Otherwise we have instruction that may not be safe.
487 // Check if Exit condition is comparing induction variable against
488 // loop invariant value. If one operand is induction variable and
489 // the other operand is loop invaraint then Exit condition is safe.
490 if (SD.ExitCondition) {
491 Value *Op0 = SD.ExitCondition->getOperand(0);
492 Value *Op1 = SD.ExitCondition->getOperand(1);
494 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
495 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
497 if (Insn0 && Insn0 == SD.IndVarIncrement)
499 else if (Insn1 && Insn1 == SD.IndVarIncrement)
502 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
503 if (!ValueSCEV->isLoopInvariant(L))
507 // We could not find any reason to consider ExitBlock unsafe.
511 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
512 /// Size is growth is calculated based on amount of code duplicated in second
514 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
517 BasicBlock *SDBlock = SD.SplitCondition->getParent();
518 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
521 // If a block is not dominated by split condition block then
522 // it must be duplicated in both loops.
523 if (!DT->dominates(SDBlock, BB))
530 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {