4a5c1c8cc0b3125a3ac5539d2db1589180068468
[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/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"
25
26 using namespace llvm;
27
28 STATISTIC(NumIndexSplit, "Number of loops index split");
29
30 namespace {
31
32   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34   public:
35     static char ID; // Pass ID, replacement for typeid
36     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38     // Index split Loop L. Return true if loop is split.
39     bool runOnLoop(Loop *L, LPPassManager &LPM);
40
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>();
54     }
55
56   private:
57
58     class SplitInfo {
59     public:
60       SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
61
62       // Induction variable's range is split at this value.
63       Value *SplitValue;
64       
65       // This compare instruction compares IndVar against SplitValue.
66       ICmpInst *SplitCondition;
67
68       // Clear split info.
69       void clear() {
70         SplitValue = NULL;
71         SplitCondition = NULL;
72       }
73
74     };
75     
76   private:
77     /// Find condition inside a loop that is suitable candidate for index split.
78     void findSplitCondition();
79
80     /// Find loop's exit condition.
81     void findLoopConditionals();
82
83     /// Return induction variable associated with value V.
84     void findIndVar(Value *V, Loop *L);
85
86     /// processOneIterationLoop - Current loop L contains compare instruction
87     /// that compares induction variable, IndVar, agains loop invariant. If
88     /// entire (i.e. meaningful) loop body is dominated by this compare
89     /// instruction then loop body is executed only for one iteration. In
90     /// such case eliminate loop structure surrounding this loop body. For
91     bool processOneIterationLoop(SplitInfo &SD);
92     
93     /// If loop header includes loop variant instruction operands then
94     /// this loop may not be eliminated.
95     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
96
97     /// If Exit block includes loop variant instructions then this
98     /// loop may not be eliminated.
99     bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
100
101     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
102     /// This routine is used to remove split condition's dead branch, dominated by
103     /// DeadBB. LiveBB dominates split conidition's other branch.
104     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
105
106     /// Find cost of spliting loop L.
107     unsigned findSplitCost(Loop *L, SplitInfo &SD);
108     bool splitLoop(SplitInfo &SD);
109
110     void initialize() {
111       IndVar = NULL; 
112       IndVarIncrement = NULL;
113       ExitCondition = NULL;
114       StartValue = NULL;
115       ExitValueNum = 0;
116       SplitData.clear();
117     }
118
119   private:
120
121     // Current Loop.
122     Loop *L;
123     LPPassManager *LPM;
124     LoopInfo *LI;
125     ScalarEvolution *SE;
126     DominatorTree *DT;
127     DominanceFrontier *DF;
128     SmallVector<SplitInfo, 4> SplitData;
129
130     // Induction variable whose range is being split by this transformation.
131     PHINode *IndVar;
132     Instruction *IndVarIncrement;
133       
134     // Loop exit condition.
135     ICmpInst *ExitCondition;
136
137     // Induction variable's initial value.
138     Value *StartValue;
139
140     // Induction variable's final loop exit value operand number in exit condition..
141     unsigned ExitValueNum;
142   };
143
144   char LoopIndexSplit::ID = 0;
145   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
146 }
147
148 LoopPass *llvm::createLoopIndexSplitPass() {
149   return new LoopIndexSplit();
150 }
151
152 // Index split Loop L. Return true if loop is split.
153 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
154   bool Changed = false;
155   L = IncomingLoop;
156   LPM = &LPM_Ref;
157
158   // FIXME - Nested loops make dominator info updates tricky. 
159   if (!L->getSubLoops().empty())
160     return false;
161
162   SE = &getAnalysis<ScalarEvolution>();
163   DT = &getAnalysis<DominatorTree>();
164   LI = &getAnalysis<LoopInfo>();
165   DF = &getAnalysis<DominanceFrontier>();
166
167   initialize();
168
169   findLoopConditionals();
170
171   if (!ExitCondition)
172     return false;
173
174   findSplitCondition();
175
176   if (SplitData.empty())
177     return false;
178
179   // First see if it is possible to eliminate loop itself or not.
180   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
181          E = SplitData.end(); SI != E;) {
182     SplitInfo &SD = *SI;
183     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
184       Changed = processOneIterationLoop(SD);
185       if (Changed) {
186         ++NumIndexSplit;
187         // If is loop is eliminated then nothing else to do here.
188         return Changed;
189       } else {
190         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
191         ++SI;
192         SplitData.erase(Delete_SI);
193       }
194     } else
195       ++SI;
196   }
197
198   unsigned MaxCost = 99;
199   unsigned Index = 0;
200   unsigned MostProfitableSDIndex = 0;
201   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
202          E = SplitData.end(); SI != E; ++SI, ++Index) {
203     SplitInfo SD = *SI;
204
205     // ICM_EQs are already handled above.
206     assert (SD.SplitCondition->getPredicate() != ICmpInst::ICMP_EQ &&
207             "Unexpected split condition predicate");
208     
209     unsigned Cost = findSplitCost(L, SD);
210     if (Cost < MaxCost)
211       MostProfitableSDIndex = Index;
212   }
213
214   // Split most profitiable condition.
215   if (!SplitData.empty())
216     Changed = splitLoop(SplitData[MostProfitableSDIndex]);
217
218   if (Changed)
219     ++NumIndexSplit;
220   
221   return Changed;
222 }
223
224 /// Return true if V is a induction variable or induction variable's
225 /// increment for loop L.
226 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
227   
228   Instruction *I = dyn_cast<Instruction>(V);
229   if (!I)
230     return;
231
232   // Check if I is a phi node from loop header or not.
233   if (PHINode *PN = dyn_cast<PHINode>(V)) {
234     if (PN->getParent() == L->getHeader()) {
235       IndVar = PN;
236       return;
237     }
238   }
239  
240   // Check if I is a add instruction whose one operand is
241   // phi node from loop header and second operand is constant.
242   if (I->getOpcode() != Instruction::Add)
243     return;
244   
245   Value *Op0 = I->getOperand(0);
246   Value *Op1 = I->getOperand(1);
247   
248   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
249     if (PN->getParent() == L->getHeader()
250         && isa<ConstantInt>(Op1)) {
251       IndVar = PN;
252       IndVarIncrement = I;
253       return;
254     }
255   }
256   
257   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
258     if (PN->getParent() == L->getHeader()
259         && isa<ConstantInt>(Op0)) {
260       IndVar = PN;
261       IndVarIncrement = I;
262       return;
263     }
264   }
265   
266   return;
267 }
268
269 // Find loop's exit condition and associated induction variable.
270 void LoopIndexSplit::findLoopConditionals() {
271
272   BasicBlock *ExitBlock = NULL;
273
274   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
275        I != E; ++I) {
276     BasicBlock *BB = *I;
277     if (!L->isLoopExit(BB))
278       continue;
279     if (ExitBlock)
280       return;
281     ExitBlock = BB;
282   }
283
284   if (!ExitBlock)
285     return;
286   
287   // If exit block's terminator is conditional branch inst then we have found
288   // exit condition.
289   BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
290   if (!BR || BR->isUnconditional())
291     return;
292   
293   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
294   if (!CI)
295     return;
296   
297   ExitCondition = CI;
298
299   // Exit condition's one operand is loop invariant exit value and second 
300   // operand is SCEVAddRecExpr based on induction variable.
301   Value *V0 = CI->getOperand(0);
302   Value *V1 = CI->getOperand(1);
303   
304   SCEVHandle SH0 = SE->getSCEV(V0);
305   SCEVHandle SH1 = SE->getSCEV(V1);
306   
307   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
308     ExitValueNum = 0;
309     findIndVar(V1, L);
310   }
311   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
312     ExitValueNum =  1;
313     findIndVar(V0, L);
314   }
315
316   if (!IndVar) 
317     ExitCondition = NULL;
318   else if (IndVar) {
319     BasicBlock *Preheader = L->getLoopPreheader();
320     StartValue = IndVar->getIncomingValueForBlock(Preheader);
321   }
322 }
323
324 /// Find condition inside a loop that is suitable candidate for index split.
325 void LoopIndexSplit::findSplitCondition() {
326
327   SplitInfo SD;
328   // Check all basic block's terminators.
329
330   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
331        I != E; ++I) {
332     BasicBlock *BB = *I;
333
334     // If this basic block does not terminate in a conditional branch
335     // then terminator is not a suitable split condition.
336     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
337     if (!BR)
338       continue;
339     
340     if (BR->isUnconditional())
341       continue;
342
343     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
344     if (!CI || CI == ExitCondition)
345       return;
346
347     // If one operand is loop invariant and second operand is SCEVAddRecExpr
348     // based on induction variable then CI is a candidate split condition.
349     Value *V0 = CI->getOperand(0);
350     Value *V1 = CI->getOperand(1);
351
352     SCEVHandle SH0 = SE->getSCEV(V0);
353     SCEVHandle SH1 = SE->getSCEV(V1);
354
355     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
356       SD.SplitValue = V0;
357       SD.SplitCondition = CI;
358       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
359         if (PN == IndVar)
360           SplitData.push_back(SD);
361       }
362       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
363         if (IndVarIncrement && IndVarIncrement == Insn)
364           SplitData.push_back(SD);
365       }
366     }
367     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
368       SD.SplitValue =  V1;
369       SD.SplitCondition = CI;
370       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
371         if (PN == IndVar)
372           SplitData.push_back(SD);
373       }
374       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
375         if (IndVarIncrement && IndVarIncrement == Insn)
376           SplitData.push_back(SD);
377       }
378     }
379   }
380 }
381
382 /// processOneIterationLoop - Current loop L contains compare instruction
383 /// that compares induction variable, IndVar, against loop invariant. If
384 /// entire (i.e. meaningful) loop body is dominated by this compare
385 /// instruction then loop body is executed only once. In such case eliminate 
386 /// loop structure surrounding this loop body. For example,
387 ///     for (int i = start; i < end; ++i) {
388 ///         if ( i == somevalue) {
389 ///           loop_body
390 ///         }
391 ///     }
392 /// can be transformed into
393 ///     if (somevalue >= start && somevalue < end) {
394 ///        i = somevalue;
395 ///        loop_body
396 ///     }
397 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
398
399   BasicBlock *Header = L->getHeader();
400
401   // First of all, check if SplitCondition dominates entire loop body
402   // or not.
403   
404   // If SplitCondition is not in loop header then this loop is not suitable
405   // for this transformation.
406   if (SD.SplitCondition->getParent() != Header)
407     return false;
408   
409   // If loop header includes loop variant instruction operands then
410   // this loop may not be eliminated.
411   if (!safeHeader(SD, Header)) 
412     return false;
413
414   // If Exit block includes loop variant instructions then this
415   // loop may not be eliminated.
416   if (!safeExitBlock(SD, ExitCondition->getParent())) 
417     return false;
418
419   // Update CFG.
420
421   // As a first step to break this loop, remove Latch to Header edge.
422   BasicBlock *Latch = L->getLoopLatch();
423   BasicBlock *LatchSucc = NULL;
424   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
425   if (!BR)
426     return false;
427   Header->removePredecessor(Latch);
428   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
429        SI != E; ++SI) {
430     if (Header != *SI)
431       LatchSucc = *SI;
432   }
433   BR->setUnconditionalDest(LatchSucc);
434
435   Instruction *Terminator = Header->getTerminator();
436   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
437
438   // Replace split condition in header.
439   // Transform 
440   //      SplitCondition : icmp eq i32 IndVar, SplitValue
441   // into
442   //      c1 = icmp uge i32 SplitValue, StartValue
443   //      c2 = icmp ult i32 vSplitValue, ExitValue
444   //      and i32 c1, c2 
445   bool SignedPredicate = ExitCondition->isSignedPredicate();
446   Instruction *C1 = new ICmpInst(SignedPredicate ? 
447                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
448                                  SD.SplitValue, StartValue, "lisplit", 
449                                  Terminator);
450   Instruction *C2 = new ICmpInst(SignedPredicate ? 
451                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
452                                  SD.SplitValue, ExitValue, "lisplit", 
453                                  Terminator);
454   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
455                                                       Terminator);
456   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
457   SD.SplitCondition->eraseFromParent();
458
459   // Now, clear latch block. Remove instructions that are responsible
460   // to increment induction variable. 
461   Instruction *LTerminator = Latch->getTerminator();
462   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
463        LB != LE; ) {
464     Instruction *I = LB;
465     ++LB;
466     if (isa<PHINode>(I) || I == LTerminator)
467       continue;
468
469     if (I == IndVarIncrement) 
470       I->replaceAllUsesWith(ExitValue);
471     else
472       I->replaceAllUsesWith(UndefValue::get(I->getType()));
473     I->eraseFromParent();
474   }
475
476   LPM->deleteLoopFromQueue(L);
477
478   // Update Dominator Info.
479   // Only CFG change done is to remove Latch to Header edge. This
480   // does not change dominator tree because Latch did not dominate
481   // Header.
482   if (DF) {
483     DominanceFrontier::iterator HeaderDF = DF->find(Header);
484     if (HeaderDF != DF->end()) 
485       DF->removeFromFrontier(HeaderDF, Header);
486
487     DominanceFrontier::iterator LatchDF = DF->find(Latch);
488     if (LatchDF != DF->end()) 
489       DF->removeFromFrontier(LatchDF, Header);
490   }
491   return true;
492 }
493
494 // If loop header includes loop variant instruction operands then
495 // this loop can not be eliminated. This is used by processOneIterationLoop().
496 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
497
498   Instruction *Terminator = Header->getTerminator();
499   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
500       BI != BE; ++BI) {
501     Instruction *I = BI;
502
503     // PHI Nodes are OK.
504     if (isa<PHINode>(I))
505       continue;
506
507     // SplitCondition itself is OK.
508     if (I == SD.SplitCondition)
509       continue;
510
511     // Induction variable is OK.
512     if (I == IndVar)
513       continue;
514
515     // Induction variable increment is OK.
516     if (I == IndVarIncrement)
517       continue;
518
519     // Terminator is also harmless.
520     if (I == Terminator)
521       continue;
522
523     // Otherwise we have a instruction that may not be safe.
524     return false;
525   }
526   
527   return true;
528 }
529
530 // If Exit block includes loop variant instructions then this
531 // loop may not be eliminated. This is used by processOneIterationLoop().
532 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
533
534   for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
535        BI != BE; ++BI) {
536     Instruction *I = BI;
537
538     // PHI Nodes are OK.
539     if (isa<PHINode>(I))
540       continue;
541
542     // Induction variable increment is OK.
543     if (IndVarIncrement && IndVarIncrement == I)
544       continue;
545
546     // Check if I is induction variable increment instruction.
547     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
548
549       Value *Op0 = I->getOperand(0);
550       Value *Op1 = I->getOperand(1);
551       PHINode *PN = NULL;
552       ConstantInt *CI = NULL;
553
554       if ((PN = dyn_cast<PHINode>(Op0))) {
555         if ((CI = dyn_cast<ConstantInt>(Op1)))
556           IndVarIncrement = I;
557       } else 
558         if ((PN = dyn_cast<PHINode>(Op1))) {
559           if ((CI = dyn_cast<ConstantInt>(Op0)))
560             IndVarIncrement = I;
561       }
562           
563       if (IndVarIncrement && PN == IndVar && CI->isOne())
564         continue;
565     }
566
567     // I is an Exit condition if next instruction is block terminator.
568     // Exit condition is OK if it compares loop invariant exit value,
569     // which is checked below.
570     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
571       if (EC == ExitCondition)
572         continue;
573     }
574
575     if (I == ExitBlock->getTerminator())
576       continue;
577
578     // Otherwise we have instruction that may not be safe.
579     return false;
580   }
581
582   // We could not find any reason to consider ExitBlock unsafe.
583   return true;
584 }
585
586 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
587 /// Size is growth is calculated based on amount of code duplicated in second
588 /// loop.
589 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
590
591   unsigned Cost = 0;
592   BasicBlock *SDBlock = SD.SplitCondition->getParent();
593   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
594        I != E; ++I) {
595     BasicBlock *BB = *I;
596     // If a block is not dominated by split condition block then
597     // it must be duplicated in both loops.
598     if (!DT->dominates(SDBlock, BB))
599       Cost += BB->size();
600   }
601
602   return Cost;
603 }
604
605 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
606 /// This routine is used to remove split condition's dead branch, dominated by
607 /// DeadBB. LiveBB dominates split conidition's other branch.
608 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
609                                   BasicBlock *LiveBB) {
610
611   // First update DeadBB's dominance frontier. 
612   SmallVector<BasicBlock *, 8> FrontierBBs;
613   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
614   if (DeadBBDF != DF->end()) {
615     SmallVector<BasicBlock *, 8> PredBlocks;
616     
617     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
618     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
619            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
620       BasicBlock *FrontierBB = *DeadBBSetI;
621       FrontierBBs.push_back(FrontierBB);
622
623       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
624       PredBlocks.clear();
625       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
626           PI != PE; ++PI) {
627         BasicBlock *P = *PI;
628         if (P == DeadBB || DT->dominates(DeadBB, P))
629           PredBlocks.push_back(P);
630       }
631
632       BasicBlock *NewDominator = NULL;
633       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
634           FBI != FBE; ++FBI) {
635         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
636           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
637                 PE = PredBlocks.end(); PI != PE; ++PI) {
638             BasicBlock *P = *PI;
639             PN->removeIncomingValue(P);
640           }
641           // If we have not identified new dominator then see if we can identify
642           // one based on remaining incoming PHINode values.
643           if (NewDominator == NULL && PN->getNumIncomingValues() == 1)
644             NewDominator = PN->getIncomingBlock(0);
645         }
646         else
647           break;
648       }      
649     }
650   }
651   
652   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
653   SmallVector<BasicBlock *, 32> WorkList;
654   DomTreeNode *DN = DT->getNode(DeadBB);
655   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
656          E = df_end(DN); DI != E; ++DI) {
657     BasicBlock *BB = DI->getBlock();
658     WorkList.push_back(BB);
659     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
660   }
661
662   while (!WorkList.empty()) {
663     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
664     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
665         BBI != BBE; ++BBI) {
666       Instruction *I = BBI;
667       I->replaceAllUsesWith(UndefValue::get(I->getType()));
668       I->eraseFromParent();
669     }
670     LPM->deleteSimpleAnalysisValue(BB, LP);
671     DT->eraseNode(BB);
672     DF->removeBlock(BB);
673     LI->removeBlock(BB);
674     BB->eraseFromParent();
675   }
676
677   // Update Frontier BBs' dominator info.
678   while (!FrontierBBs.empty()) {
679     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
680     BasicBlock *NewDominator = FBB->getSinglePredecessor();
681     if (!NewDominator) {
682       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
683       NewDominator = *PI;
684       ++PI;
685       if (NewDominator != LiveBB) {
686         for(; PI != PE; ++PI) {
687           BasicBlock *P = *PI;
688           if (P == LiveBB) {
689             NewDominator = LiveBB;
690             break;
691           }
692           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
693         }
694       }
695     }
696     assert (NewDominator && "Unable to fix dominator info.");
697     DT->changeImmediateDominator(FBB, NewDominator);
698     DF->changeImmediateDominator(FBB, NewDominator, DT);
699   }
700
701 }
702
703 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
704
705   BasicBlock *Preheader = L->getLoopPreheader();
706   BasicBlock *SplitBlock = SD.SplitCondition->getParent();
707   BasicBlock *Latch = L->getLoopLatch();
708   BasicBlock *Header = L->getHeader();
709   BranchInst *SplitTerminator = cast<BranchInst>(SplitBlock->getTerminator());
710
711   // FIXME - Unable to handle triange loops at the moment.
712   // In triangle loop, split condition is in header and one of the
713   // the split destination is loop latch. If split condition is EQ
714   // then such loops are already handle in processOneIterationLoop().
715   if (Header == SplitBlock 
716       && (Latch == SplitTerminator->getSuccessor(0) 
717           || Latch == SplitTerminator->getSuccessor(1)))
718     return false;
719
720   // If one of the split condition branch is post dominating other then loop 
721   // index split is not appropriate.
722   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
723   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
724   if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
725     return false;
726
727   // If one of the split condition branch is a predecessor of the other
728   // split condition branch head then do not split loop on this condition.
729   for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0); PI != PE; ++PI)
730     if (Succ1 == *PI)
731       return false;
732   for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1); PI != PE; ++PI)
733     if (Succ0 == *PI)
734       return false;
735
736   // True loop is original loop. False loop is cloned loop.
737
738   bool SignedPredicate = ExitCondition->isSignedPredicate();  
739   //[*] Calculate True loop's new Exit Value in loop preheader.
740   //      TLExitValue = min(SplitValue, ExitValue)
741   //[*] Calculate False loop's new Start Value in loop preheader.
742   //      FLStartValue = min(SplitValue, TrueLoop.StartValue)
743   Value *TLExitValue = NULL;
744   Value *FLStartValue = NULL;
745   if (isa<ConstantInt>(SD.SplitValue)) {
746     TLExitValue = SD.SplitValue;
747     FLStartValue = SD.SplitValue;
748   }
749   else {
750     Value *C1 = new ICmpInst(SignedPredicate ? 
751                             ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
752                             SD.SplitValue, 
753                              ExitCondition->getOperand(ExitValueNum), 
754                              "lsplit.ev",
755                             Preheader->getTerminator());
756     TLExitValue = new SelectInst(C1, SD.SplitValue, 
757                                  ExitCondition->getOperand(ExitValueNum), 
758                                  "lsplit.ev", Preheader->getTerminator());
759
760     Value *C2 = new ICmpInst(SignedPredicate ? 
761                              ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
762                              SD.SplitValue, StartValue, "lsplit.sv",
763                              Preheader->getTerminator());
764     FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
765                                   "lsplit.sv", Preheader->getTerminator());
766   }
767
768   //[*] Clone loop. Avoid true destination of split condition and 
769   //    the blocks dominated by true destination. 
770   DenseMap<const Value *, Value *> ValueMap;
771   Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
772   BasicBlock *FalseHeader = FalseLoop->getHeader();
773
774   //[*] True loop's exit edge enters False loop.
775   PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
776   BasicBlock *ExitBlock = ExitCondition->getParent();
777   BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
778   assert (ExitInsn && "Unable to find suitable loop exit branch");
779   BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
780
781   if (L->contains(ExitDest)) {
782     ExitDest = ExitInsn->getSuccessor(0);
783     ExitInsn->setSuccessor(0, FalseHeader);
784   } else
785     ExitInsn->setSuccessor(1, FalseHeader);
786
787   // Collect inverse map of Header PHINodes.
788   DenseMap<Value *, Value *> InverseMap;
789   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
790          BE = L->getHeader()->end(); BI != BE; ++BI) {
791     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
792       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
793       InverseMap[PNClone] = PN;
794     } else
795       break;
796   }
797
798   // Update False loop's header
799   for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
800        BI != BE; ++BI) {
801     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
802       PN->removeIncomingValue(Preheader);
803       if (PN == IndVarClone)
804         PN->addIncoming(FLStartValue, ExitBlock);
805       else { 
806         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
807         Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
808         PN->addIncoming(V2, ExitBlock);
809       }
810     } else
811       break;
812   }
813
814   // Update ExitDest. Now it's predecessor is False loop's exit block.
815   BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
816   for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
817        BI != BE; ++BI) {
818     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
819       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
820       PN->removeIncomingValue(ExitBlock);
821     } else
822       break;
823   }
824
825   if (DT) {
826     DT->changeImmediateDominator(FalseHeader, ExitBlock);
827     DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
828   }
829
830   assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
831
832   //[*] Split Exit Edge. 
833   SplitEdge(ExitBlock, FalseHeader, this);
834
835   //[*] Eliminate split condition's false branch from True loop.
836   BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
837   BasicBlock *FBB = BR->getSuccessor(1);
838   BR->setUnconditionalDest(BR->getSuccessor(0));
839   removeBlocks(FBB, L, BR->getSuccessor(0));
840
841   //[*] Update True loop's exit value using new exit value.
842   ExitCondition->setOperand(ExitValueNum, TLExitValue);
843
844   //[*] Eliminate split condition's  true branch in False loop CFG.
845   BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
846   BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
847   BasicBlock *TBB = FBR->getSuccessor(0);
848   FBR->setUnconditionalDest(FBR->getSuccessor(1));
849   removeBlocks(TBB, FalseLoop, cast<BasicBlock>(FBR->getSuccessor(0)));
850
851   return true;
852 }
853