8234317444a110986fa05e9ed6a3b87d527c0557
[oota-llvm.git] / lib / Transforms / Scalar / LoopIndexSplit.cpp
1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Index Splitting Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "loop-index-split"
15
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"
23
24 using namespace llvm;
25
26 STATISTIC(NumIndexSplit, "Number of loops index split");
27
28 namespace {
29
30   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
31
32   public:
33     static char ID; // Pass ID, replacement for typeid
34     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35
36     // Index split Loop L. Return true if loop is split.
37     bool runOnLoop(Loop *L, LPPassManager &LPM);
38
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>();
50     }
51
52   private:
53
54     class SplitInfo {
55     public:
56       SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
57
58       // Induction variable's range is split at this value.
59       Value *SplitValue;
60       
61       // This compare instruction compares IndVar against SplitValue.
62       ICmpInst *SplitCondition;
63
64       // Clear split info.
65       void clear() {
66         SplitValue = NULL;
67         SplitCondition = NULL;
68       }
69
70     };
71     
72   private:
73     /// Find condition inside a loop that is suitable candidate for index split.
74     void findSplitCondition();
75
76     /// Find loop's exit condition.
77     void findLoopConditionals();
78
79     /// Return induction variable associated with value V.
80     void findIndVar(Value *V, Loop *L);
81
82     /// processOneIterationLoop - Current loop L contains compare instruction
83     /// that compares induction variable, IndVar, agains loop invariant. If
84     /// entire (i.e. meaningful) loop body is dominated by this compare
85     /// instruction then loop body is executed only for one iteration. In
86     /// such case eliminate loop structure surrounding this loop body. For
87     bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
88     
89     /// If loop header includes loop variant instruction operands then
90     /// this loop may not be eliminated.
91     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
92
93     /// If Exit block includes loop variant instructions then this
94     /// loop may not be eliminated.
95     bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
96
97     /// Find cost of spliting loop L.
98     unsigned findSplitCost(Loop *L, SplitInfo &SD);
99     bool splitLoop(SplitInfo &SD);
100
101     void initialize() {
102       IndVar = NULL; 
103       IndVarIncrement = NULL;
104       ExitCondition = NULL;
105       StartValue = ExitValue = NULL;
106     }
107
108   private:
109
110     // Current Loop.
111     Loop *L;
112     ScalarEvolution *SE;
113     DominatorTree *DT;
114     SmallVector<SplitInfo, 4> SplitData;
115
116     // Induction variable whose range is being split by this transformation.
117     PHINode *IndVar;
118     Instruction *IndVarIncrement;
119       
120     // Loop exit condition.
121     ICmpInst *ExitCondition;
122
123     // Induction variable's initial value.
124     Value *StartValue;
125
126     // Induction variable's final loop exit value.
127     Value *ExitValue;
128   };
129
130   char LoopIndexSplit::ID = 0;
131   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
132 }
133
134 LoopPass *llvm::createLoopIndexSplitPass() {
135   return new LoopIndexSplit();
136 }
137
138 // Index split Loop L. Return true if loop is split.
139 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
140   bool Changed = false;
141   L = IncomingLoop;
142
143   SE = &getAnalysis<ScalarEvolution>();
144   DT = &getAnalysis<DominatorTree>();
145
146   initialize();
147
148   findLoopConditionals();
149
150   if (!ExitCondition)
151     return false;
152
153   findSplitCondition();
154
155   if (SplitData.empty())
156     return false;
157
158   // First see if it is possible to eliminate loop itself or not.
159   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
160          E = SplitData.end(); SI != E; ++SI) {
161     SplitInfo &SD = *SI;
162     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
163       Changed = processOneIterationLoop(SD,LPM);
164       if (Changed) {
165         ++NumIndexSplit;
166         // If is loop is eliminated then nothing else to do here.
167         return Changed;
168       }
169     }
170   }
171
172   unsigned MaxCost = 99;
173   unsigned Index = 0;
174   unsigned MostProfitableSDIndex = 0;
175   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
176          E = SplitData.end(); SI != E; ++SI, ++Index) {
177     SplitInfo SD = *SI;
178
179     // ICM_EQs are already handled above.
180     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
181       continue;
182     
183     unsigned Cost = findSplitCost(L, SD);
184     if (Cost < MaxCost)
185       MostProfitableSDIndex = Index;
186   }
187
188   // Split most profitiable condition.
189   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
190
191   if (Changed)
192     ++NumIndexSplit;
193   
194   return Changed;
195 }
196
197 /// Return true if V is a induction variable or induction variable's
198 /// increment for loop L.
199 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
200   
201   Instruction *I = dyn_cast<Instruction>(V);
202   if (!I)
203     return;
204
205   // Check if I is a phi node from loop header or not.
206   if (PHINode *PN = dyn_cast<PHINode>(V)) {
207     if (PN->getParent() == L->getHeader()) {
208       IndVar = PN;
209       return;
210     }
211   }
212  
213   // Check if I is a add instruction whose one operand is
214   // phi node from loop header and second operand is constant.
215   if (I->getOpcode() != Instruction::Add)
216     return;
217   
218   Value *Op0 = I->getOperand(0);
219   Value *Op1 = I->getOperand(1);
220   
221   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
222     if (PN->getParent() == L->getHeader()
223         && isa<ConstantInt>(Op1)) {
224       IndVar = PN;
225       IndVarIncrement = I;
226       return;
227     }
228   }
229   
230   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
231     if (PN->getParent() == L->getHeader()
232         && isa<ConstantInt>(Op0)) {
233       IndVar = PN;
234       IndVarIncrement = I;
235       return;
236     }
237   }
238   
239   return;
240 }
241
242 // Find loop's exit condition and associated induction variable.
243 void LoopIndexSplit::findLoopConditionals() {
244
245   BasicBlock *ExitBlock = NULL;
246
247   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
248        I != E; ++I) {
249     BasicBlock *BB = *I;
250     if (!L->isLoopExit(BB))
251       continue;
252     if (ExitBlock)
253       return;
254     ExitBlock = BB;
255   }
256
257   if (!ExitBlock)
258     return;
259   
260   // If exit block's terminator is conditional branch inst then we have found
261   // exit condition.
262   BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
263   if (!BR || BR->isUnconditional())
264     return;
265   
266   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
267   if (!CI)
268     return;
269   
270   ExitCondition = CI;
271
272   // Exit condition's one operand is loop invariant exit value and second 
273   // operand is SCEVAddRecExpr based on induction variable.
274   Value *V0 = CI->getOperand(0);
275   Value *V1 = CI->getOperand(1);
276   
277   SCEVHandle SH0 = SE->getSCEV(V0);
278   SCEVHandle SH1 = SE->getSCEV(V1);
279   
280   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
281     ExitValue = V0;
282     findIndVar(V1, L);
283   }
284   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
285     ExitValue =  V1;
286     findIndVar(V0, L);
287   }
288
289   if (!ExitValue || !IndVar)
290     ExitCondition = NULL;
291   else if (IndVar) {
292     BasicBlock *Preheader = L->getLoopPreheader();
293     StartValue = IndVar->getIncomingValueForBlock(Preheader);
294   }
295 }
296
297 /// Find condition inside a loop that is suitable candidate for index split.
298 void LoopIndexSplit::findSplitCondition() {
299
300   SplitInfo SD;
301   // Check all basic block's terminators.
302
303   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
304        I != E; ++I) {
305     BasicBlock *BB = *I;
306
307     // If this basic block does not terminate in a conditional branch
308     // then terminator is not a suitable split condition.
309     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
310     if (!BR)
311       continue;
312     
313     if (BR->isUnconditional())
314       continue;
315
316     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
317     if (!CI || CI == ExitCondition)
318       return;
319
320     // If one operand is loop invariant and second operand is SCEVAddRecExpr
321     // based on induction variable then CI is a candidate split condition.
322     Value *V0 = CI->getOperand(0);
323     Value *V1 = CI->getOperand(1);
324
325     SCEVHandle SH0 = SE->getSCEV(V0);
326     SCEVHandle SH1 = SE->getSCEV(V1);
327
328     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
329       SD.SplitValue = V0;
330       SD.SplitCondition = CI;
331       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
332         if (PN == IndVar)
333           SplitData.push_back(SD);
334       }
335       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
336         if (IndVarIncrement && IndVarIncrement == Insn)
337           SplitData.push_back(SD);
338       }
339     }
340     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
341       SD.SplitValue =  V1;
342       SD.SplitCondition = CI;
343       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
344         if (PN == IndVar)
345           SplitData.push_back(SD);
346       }
347       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
348         if (IndVarIncrement && IndVarIncrement == Insn)
349           SplitData.push_back(SD);
350       }
351     }
352   }
353 }
354
355 /// processOneIterationLoop - Current loop L contains compare instruction
356 /// that compares induction variable, IndVar, against loop invariant. If
357 /// entire (i.e. meaningful) loop body is dominated by this compare
358 /// instruction then loop body is executed only once. In such case eliminate 
359 /// loop structure surrounding this loop body. For example,
360 ///     for (int i = start; i < end; ++i) {
361 ///         if ( i == somevalue) {
362 ///           loop_body
363 ///         }
364 ///     }
365 /// can be transformed into
366 ///     if (somevalue >= start && somevalue < end) {
367 ///        i = somevalue;
368 ///        loop_body
369 ///     }
370 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
371
372   BasicBlock *Header = L->getHeader();
373
374   // First of all, check if SplitCondition dominates entire loop body
375   // or not.
376   
377   // If SplitCondition is not in loop header then this loop is not suitable
378   // for this transformation.
379   if (SD.SplitCondition->getParent() != Header)
380     return false;
381   
382   // If one of the Header block's successor is not an exit block then this
383   // loop is not a suitable candidate.
384   BasicBlock *ExitBlock = NULL;
385   for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
386     if (L->isLoopExit(*SI)) {
387       ExitBlock = *SI;
388       break;
389     }
390   }
391
392   if (!ExitBlock)
393     return false;
394
395   // If loop header includes loop variant instruction operands then
396   // this loop may not be eliminated.
397   if (!safeHeader(SD, Header)) 
398     return false;
399
400   // If Exit block includes loop variant instructions then this
401   // loop may not be eliminated.
402   if (!safeExitBlock(SD, ExitBlock)) 
403     return false;
404
405   // Update CFG.
406
407   // As a first step to break this loop, remove Latch to Header edge.
408   BasicBlock *Latch = L->getLoopLatch();
409   BasicBlock *LatchSucc = NULL;
410   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
411   if (!BR)
412     return false;
413   Header->removePredecessor(Latch);
414   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
415        SI != E; ++SI) {
416     if (Header != *SI)
417       LatchSucc = *SI;
418   }
419   BR->setUnconditionalDest(LatchSucc);
420
421   BasicBlock *Preheader = L->getLoopPreheader();
422   Instruction *Terminator = Header->getTerminator();
423   StartValue = IndVar->getIncomingValueForBlock(Preheader);
424
425   // Replace split condition in header.
426   // Transform 
427   //      SplitCondition : icmp eq i32 IndVar, SplitValue
428   // into
429   //      c1 = icmp uge i32 SplitValue, StartValue
430   //      c2 = icmp ult i32 vSplitValue, ExitValue
431   //      and i32 c1, c2 
432   bool SignedPredicate = ExitCondition->isSignedPredicate();
433   Instruction *C1 = new ICmpInst(SignedPredicate ? 
434                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
435                                  SD.SplitValue, StartValue, "lisplit", 
436                                  Terminator);
437   Instruction *C2 = new ICmpInst(SignedPredicate ? 
438                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
439                                  SD.SplitValue, ExitValue, "lisplit", 
440                                  Terminator);
441   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
442                                                       Terminator);
443   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
444   SD.SplitCondition->eraseFromParent();
445
446   // Now, clear latch block. Remove instructions that are responsible
447   // to increment induction variable. 
448   Instruction *LTerminator = Latch->getTerminator();
449   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
450        LB != LE; ) {
451     Instruction *I = LB;
452     ++LB;
453     if (isa<PHINode>(I) || I == LTerminator)
454       continue;
455
456     I->replaceAllUsesWith(UndefValue::get(I->getType()));
457     I->eraseFromParent();
458   }
459
460   LPM.deleteLoopFromQueue(L);
461
462   // Update Dominator Info.
463   // Only CFG change done is to remove Latch to Header edge. This
464   // does not change dominator tree because Latch did not dominate
465   // Header.
466   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
467     DominanceFrontier::iterator HeaderDF = DF->find(Header);
468     if (HeaderDF != DF->end()) 
469       DF->removeFromFrontier(HeaderDF, Header);
470
471     DominanceFrontier::iterator LatchDF = DF->find(Latch);
472     if (LatchDF != DF->end()) 
473       DF->removeFromFrontier(LatchDF, Header);
474   }
475   return true;
476 }
477
478 // If loop header includes loop variant instruction operands then
479 // this loop can not be eliminated. This is used by processOneIterationLoop().
480 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
481
482   Instruction *Terminator = Header->getTerminator();
483   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
484       BI != BE; ++BI) {
485     Instruction *I = BI;
486
487     // PHI Nodes are OK. FIXME : Handle last value assignments.
488     if (isa<PHINode>(I))
489       continue;
490
491     // SplitCondition itself is OK.
492     if (I == SD.SplitCondition)
493       continue;
494
495     // Induction variable is OK.
496     if (I == IndVar)
497       continue;
498
499     // Induction variable increment is OK.
500     if (I == IndVarIncrement)
501       continue;
502
503     // Terminator is also harmless.
504     if (I == Terminator)
505       continue;
506
507     // Otherwise we have a instruction that may not be safe.
508     return false;
509   }
510   
511   return true;
512 }
513
514 // If Exit block includes loop variant instructions then this
515 // loop may not be eliminated. This is used by processOneIterationLoop().
516 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
517
518   for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
519        BI != BE; ++BI) {
520     Instruction *I = BI;
521
522     // PHI Nodes are OK. FIXME : Handle last value assignments.
523     if (isa<PHINode>(I))
524       continue;
525
526     // Induction variable increment is OK.
527     if (IndVarIncrement && IndVarIncrement == I)
528       continue;
529
530     // Check if I is induction variable increment instruction.
531     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
532
533       Value *Op0 = I->getOperand(0);
534       Value *Op1 = I->getOperand(1);
535       PHINode *PN = NULL;
536       ConstantInt *CI = NULL;
537
538       if ((PN = dyn_cast<PHINode>(Op0))) {
539         if ((CI = dyn_cast<ConstantInt>(Op1)))
540           IndVarIncrement = I;
541       } else 
542         if ((PN = dyn_cast<PHINode>(Op1))) {
543           if ((CI = dyn_cast<ConstantInt>(Op0)))
544             IndVarIncrement = I;
545       }
546           
547       if (IndVarIncrement && PN == IndVar && CI->isOne())
548         continue;
549     }
550
551     // I is an Exit condition if next instruction is block terminator.
552     // Exit condition is OK if it compares loop invariant exit value,
553     // which is checked below.
554     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
555       if (EC == ExitCondition)
556         continue;
557     }
558
559     if (I == ExitBlock->getTerminator())
560       continue;
561
562     // Otherwise we have instruction that may not be safe.
563     return false;
564   }
565
566   // We could not find any reason to consider ExitBlock unsafe.
567   return true;
568 }
569
570 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
571 /// Size is growth is calculated based on amount of code duplicated in second
572 /// loop.
573 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
574
575   unsigned Cost = 0;
576   BasicBlock *SDBlock = SD.SplitCondition->getParent();
577   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
578        I != E; ++I) {
579     BasicBlock *BB = *I;
580     // If a block is not dominated by split condition block then
581     // it must be duplicated in both loops.
582     if (!DT->dominates(SDBlock, BB))
583       Cost += BB->size();
584   }
585
586   return Cost;
587 }
588
589 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
590
591   BasicBlock *Preheader = L->getLoopPreheader();
592
593   // True loop is original loop. False loop is cloned loop.
594
595   bool SignedPredicate = ExitCondition->isSignedPredicate();  
596   //[*] Calculate True loop's new Exit Value in loop preheader.
597   //      TLExitValue = min(SplitValue, ExitValue)
598   //[*] Calculate False loop's new Start Value in loop preheader.
599   //      FLStartValue = min(SplitValue, TrueLoop.StartValue)
600   Value *TLExitValue = NULL;
601   Value *FLStartValue = NULL;
602   if (isa<ConstantInt>(SD.SplitValue)) {
603     TLExitValue = SD.SplitValue;
604     FLStartValue = SD.SplitValue;
605   }
606   else {
607     Value *C1 = new ICmpInst(SignedPredicate ? 
608                             ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
609                             SD.SplitValue, ExitValue, "lsplit.ev",
610                             Preheader->getTerminator());
611     TLExitValue = new SelectInst(C1, SD.SplitValue, ExitValue, 
612                                  "lsplit.ev", Preheader->getTerminator());
613
614     Value *C2 = new ICmpInst(SignedPredicate ? 
615                              ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
616                              SD.SplitValue, StartValue, "lsplit.sv",
617                              Preheader->getTerminator());
618     FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
619                                   "lsplit.sv", Preheader->getTerminator());
620   }
621   //[*] Split Exit Edge.
622   //[*] Clone loop. Avoid true destination of split condition and 
623   //    the blocks dominated by true destination. 
624   //[*] True loops exit edge enters False loop.
625   //[*] Eliminate split condition's false branch from True loop.
626   //    Update true loop dom info.
627   //[*] Update True loop's exit value using NewExitValue.
628   //[*] Update False loop's start value using NewStartValue.
629   //[*] Fix lack of true branch in False loop CFG.
630   //    Update false loop dom info.
631   //[*] Update dom info in general.
632   return false;
633 }