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/Support/Compiler.h"
21 #include "llvm/ADT/Statistic.h"
25 STATISTIC(NumIndexSplit, "Number of loops index split");
29 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
32 static char ID; // Pass ID, replacement for typeid
33 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35 // Index split Loop L. Return true if loop is split.
36 bool runOnLoop(Loop *L, LPPassManager &LPM);
38 void getAnalysisUsage(AnalysisUsage &AU) const {
39 AU.addRequired<ScalarEvolution>();
40 AU.addPreserved<ScalarEvolution>();
41 AU.addRequiredID(LCSSAID);
42 AU.addPreservedID(LCSSAID);
43 AU.addPreserved<LoopInfo>();
44 AU.addRequiredID(LoopSimplifyID);
45 AU.addPreservedID(LoopSimplifyID);
52 SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
53 SplitCondition(NULL), ExitCondition(NULL) {}
54 // Induction variable whose range is being split by this transformation.
57 // Induction variable's range is split at this value.
60 // Induction variable's final loop exit value.
63 // This compare instruction compares IndVar against SplitValue.
64 ICmpInst *SplitCondition;
66 // Loop exit condition.
67 ICmpInst *ExitCondition;
71 /// Find condition inside a loop that is suitable candidate for index split.
72 void findSplitCondition();
74 /// processOneIterationLoop - Current loop L contains compare instruction
75 /// that compares induction variable, IndVar, agains loop invariant. If
76 /// entire (i.e. meaningful) loop body is dominated by this compare
77 /// instruction then loop body is executed only for one iteration. In
78 /// such case eliminate loop structure surrounding this loop body. For
79 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
81 // If loop header includes loop variant instruction operands then
82 // this loop may not be eliminated.
83 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
85 // If Exit block includes loop variant instructions then this
86 // loop may not be eliminated.
87 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
89 bool splitLoop(SplitInfo &SD);
97 SmallVector<SplitInfo, 4> SplitData;
100 char LoopIndexSplit::ID = 0;
101 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
104 LoopPass *llvm::createLoopIndexSplitPass() {
105 return new LoopIndexSplit();
108 // Index split Loop L. Return true if loop is split.
109 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
110 bool Changed = false;
113 SE = &getAnalysis<ScalarEvolution>();
115 findSplitCondition();
117 if (SplitData.empty())
120 // First see if it is possible to eliminate loop itself or not.
121 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
122 E = SplitData.end(); SI != E; ++SI) {
124 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
125 Changed = processOneIterationLoop(SD,LPM);
128 // If is loop is eliminated then nothing else to do here.
134 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
135 E = SplitData.end(); SI != E; ++SI) {
138 // ICM_EQs are already handled above.
139 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
142 // FIXME : Collect Spliting cost for all SD. Only operate on profitable SDs.
143 Changed = splitLoop(SD);
152 /// Find condition inside a loop that is suitable candidate for index split.
153 void LoopIndexSplit::findSplitCondition() {
156 BasicBlock *Header = L->getHeader();
158 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
159 PHINode *PN = cast<PHINode>(I);
161 if (!PN->getType()->isInteger())
164 SCEVHandle SCEV = SE->getSCEV(PN);
165 if (!isa<SCEVAddRecExpr>(SCEV))
168 // If this phi node is used in a compare instruction then it is a
169 // split condition candidate.
170 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
172 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
173 SD.SplitCondition = CI;
178 // Valid SplitCondition's one operand is phi node and the other operand
179 // is loop invariant.
180 if (SD.SplitCondition) {
181 if (SD.SplitCondition->getOperand(0) != PN)
182 SD.SplitValue = SD.SplitCondition->getOperand(0);
184 SD.SplitValue = SD.SplitCondition->getOperand(1);
185 SCEVHandle ValueSCEV = SE->getSCEV(SD.SplitValue);
187 // If SplitValue is not invariant then SplitCondition is not appropriate.
188 if (!ValueSCEV->isLoopInvariant(L))
189 SD.SplitCondition = NULL;
192 // We are looking for only one split condition.
193 if (SD.SplitCondition) {
195 SplitData.push_back(SD);
200 /// processOneIterationLoop - Current loop L contains compare instruction
201 /// that compares induction variable, IndVar, against loop invariant. If
202 /// entire (i.e. meaningful) loop body is dominated by this compare
203 /// instruction then loop body is executed only once. In such case eliminate
204 /// loop structure surrounding this loop body. For example,
205 /// for (int i = start; i < end; ++i) {
206 /// if ( i == somevalue) {
210 /// can be transformed into
211 /// if (somevalue >= start && somevalue < end) {
215 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
217 BasicBlock *Header = L->getHeader();
219 // First of all, check if SplitCondition dominates entire loop body
222 // If SplitCondition is not in loop header then this loop is not suitable
223 // for this transformation.
224 if (SD.SplitCondition->getParent() != Header)
227 // If one of the Header block's successor is not an exit block then this
228 // loop is not a suitable candidate.
229 BasicBlock *ExitBlock = NULL;
230 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
231 if (L->isLoopExit(*SI)) {
240 // If loop header includes loop variant instruction operands then
241 // this loop may not be eliminated.
242 if (!safeHeader(SD, Header))
245 // If Exit block includes loop variant instructions then this
246 // loop may not be eliminated.
247 if (!safeExitBlock(SD, ExitBlock))
252 // As a first step to break this loop, remove Latch to Header edge.
253 BasicBlock *Latch = L->getLoopLatch();
254 BasicBlock *LatchSucc = NULL;
255 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
258 Header->removePredecessor(Latch);
259 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
264 BR->setUnconditionalDest(LatchSucc);
266 BasicBlock *Preheader = L->getLoopPreheader();
267 Instruction *Terminator = Header->getTerminator();
268 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
270 // Replace split condition in header.
272 // SplitCondition : icmp eq i32 IndVar, SplitValue
274 // c1 = icmp uge i32 SplitValue, StartValue
275 // c2 = icmp ult i32 vSplitValue, ExitValue
277 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
278 Instruction *C1 = new ICmpInst(SignedPredicate ?
279 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
280 SD.SplitValue, StartValue, "lisplit",
282 Instruction *C2 = new ICmpInst(SignedPredicate ?
283 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
284 SD.SplitValue, SD.ExitValue, "lisplit",
286 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
288 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
289 SD.SplitCondition->eraseFromParent();
291 // Now, clear latch block. Remove instructions that are responsible
292 // to increment induction variable.
293 Instruction *LTerminator = Latch->getTerminator();
294 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
298 if (isa<PHINode>(I) || I == LTerminator)
301 I->replaceAllUsesWith(UndefValue::get(I->getType()));
302 I->eraseFromParent();
305 LPM.deleteLoopFromQueue(L);
309 // If loop header includes loop variant instruction operands then
310 // this loop can not be eliminated. This is used by processOneIterationLoop().
311 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
313 Instruction *Terminator = Header->getTerminator();
314 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
318 // PHI Nodes are OK. FIXME : Handle last value assignments.
322 // SplitCondition itself is OK.
323 if (I == SD.SplitCondition)
326 // Terminator is also harmless.
330 // Otherwise we have a instruction that may not be safe.
337 // If Exit block includes loop variant instructions then this
338 // loop may not be eliminated. This is used by processOneIterationLoop().
339 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
341 Instruction *IndVarIncrement = NULL;
343 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
347 // PHI Nodes are OK. FIXME : Handle last value assignments.
351 // Check if I is induction variable increment instruction.
352 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
353 if (BOp->getOpcode() != Instruction::Add)
356 Value *Op0 = BOp->getOperand(0);
357 Value *Op1 = BOp->getOperand(1);
359 ConstantInt *CI = NULL;
361 if ((PN = dyn_cast<PHINode>(Op0))) {
362 if ((CI = dyn_cast<ConstantInt>(Op1)))
365 if ((PN = dyn_cast<PHINode>(Op1))) {
366 if ((CI = dyn_cast<ConstantInt>(Op0)))
370 if (IndVarIncrement && PN == SD.IndVar && CI->isOne())
374 // I is an Exit condition if next instruction is block terminator.
375 // Exit condition is OK if it compares loop invariant exit value,
376 // which is checked below.
377 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
380 if (N == ExitBlock->getTerminator()) {
381 SD.ExitCondition = EC;
386 // Otherwise we have instruction that may not be safe.
390 // Check if Exit condition is comparing induction variable against
391 // loop invariant value. If one operand is induction variable and
392 // the other operand is loop invaraint then Exit condition is safe.
393 if (SD.ExitCondition) {
394 Value *Op0 = SD.ExitCondition->getOperand(0);
395 Value *Op1 = SD.ExitCondition->getOperand(1);
397 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
398 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
400 if (Insn0 && Insn0 == IndVarIncrement)
402 else if (Insn1 && Insn1 == IndVarIncrement)
405 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
406 if (!ValueSCEV->isLoopInvariant(L))
410 // We could not find any reason to consider ExitBlock unsafe.
414 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {