0f55a9100c3ae57a7b1b32265ae1ea10ab15a99f
[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                     UseTrueBranchFirst(true), A_ExitValue(NULL), 
62                     B_StartValue(NULL) {}
63
64       // Induction variable's range is split at this value.
65       Value *SplitValue;
66       
67       // This compare instruction compares IndVar against SplitValue.
68       ICmpInst *SplitCondition;
69
70       // True if after loop index split, first loop will execute split condition's
71       // true branch.
72       bool UseTrueBranchFirst;
73
74       // Exit value for first loop after loop split.
75       Value *A_ExitValue;
76
77       // Start value for second loop after loop split.
78       Value *B_StartValue;
79
80       // Clear split info.
81       void clear() {
82         SplitValue = NULL;
83         SplitCondition = NULL;
84         UseTrueBranchFirst = true;
85         A_ExitValue = NULL;
86         B_StartValue = NULL;
87       }
88
89     };
90     
91   private:
92     /// Find condition inside a loop that is suitable candidate for index split.
93     void findSplitCondition();
94
95     /// Find loop's exit condition.
96     void findLoopConditionals();
97
98     /// Return induction variable associated with value V.
99     void findIndVar(Value *V, Loop *L);
100
101     /// processOneIterationLoop - Current loop L contains compare instruction
102     /// that compares induction variable, IndVar, agains loop invariant. If
103     /// entire (i.e. meaningful) loop body is dominated by this compare
104     /// instruction then loop body is executed only for one iteration. In
105     /// such case eliminate loop structure surrounding this loop body. For
106     bool processOneIterationLoop(SplitInfo &SD);
107     
108     /// If loop header includes loop variant instruction operands then
109     /// this loop may not be eliminated.
110     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
111
112     /// If Exiting block includes loop variant instructions then this
113     /// loop may not be eliminated.
114     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
115
116     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117     /// This routine is used to remove split condition's dead branch, dominated by
118     /// DeadBB. LiveBB dominates split conidition's other branch.
119     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
120
121     /// safeSplitCondition - Return true if it is possible to
122     /// split loop using given split condition.
123     bool safeSplitCondition(SplitInfo &SD);
124
125     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126     /// based on split value. 
127     void calculateLoopBounds(SplitInfo &SD);
128
129     /// updatePHINodes - CFG has been changed. 
130     /// Before 
131     ///   - ExitBB's single predecessor was Latch
132     ///   - Latch's second successor was Header
133     /// Now
134     ///   - ExitBB's single predecessor was Header
135     ///   - Latch's one and only successor was Header
136     ///
137     /// Update ExitBB PHINodes' to reflect this change.
138     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
139                         BasicBlock *Header,
140                         PHINode *IV, Instruction *IVIncrement);
141
142     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
143     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
144                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
145                            PHINode *IV, Instruction *IVAdd, Loop *LP);
146
147     /// splitLoop - Split current loop L in two loops using split information
148     /// SD. Update dominator information. Maintain LCSSA form.
149     bool splitLoop(SplitInfo &SD);
150
151     void initialize() {
152       IndVar = NULL; 
153       IndVarIncrement = NULL;
154       ExitCondition = NULL;
155       StartValue = NULL;
156       ExitValueNum = 0;
157       SplitData.clear();
158     }
159
160   private:
161
162     // Current Loop.
163     Loop *L;
164     LPPassManager *LPM;
165     LoopInfo *LI;
166     ScalarEvolution *SE;
167     DominatorTree *DT;
168     DominanceFrontier *DF;
169     SmallVector<SplitInfo, 4> SplitData;
170
171     // Induction variable whose range is being split by this transformation.
172     PHINode *IndVar;
173     Instruction *IndVarIncrement;
174       
175     // Loop exit condition.
176     ICmpInst *ExitCondition;
177
178     // Induction variable's initial value.
179     Value *StartValue;
180
181     // Induction variable's final loop exit value operand number in exit condition..
182     unsigned ExitValueNum;
183   };
184
185   char LoopIndexSplit::ID = 0;
186   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
187 }
188
189 LoopPass *llvm::createLoopIndexSplitPass() {
190   return new LoopIndexSplit();
191 }
192
193 // Index split Loop L. Return true if loop is split.
194 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
195   bool Changed = false;
196   L = IncomingLoop;
197   LPM = &LPM_Ref;
198
199   // FIXME - Nested loops make dominator info updates tricky. 
200   if (!L->getSubLoops().empty())
201     return false;
202
203   SE = &getAnalysis<ScalarEvolution>();
204   DT = &getAnalysis<DominatorTree>();
205   LI = &getAnalysis<LoopInfo>();
206   DF = &getAnalysis<DominanceFrontier>();
207
208   initialize();
209
210   findLoopConditionals();
211
212   if (!ExitCondition)
213     return false;
214
215   findSplitCondition();
216
217   if (SplitData.empty())
218     return false;
219
220   // First see if it is possible to eliminate loop itself or not.
221   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
222          E = SplitData.end(); SI != E;) {
223     SplitInfo &SD = *SI;
224     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
225       Changed = processOneIterationLoop(SD);
226       if (Changed) {
227         ++NumIndexSplit;
228         // If is loop is eliminated then nothing else to do here.
229         return Changed;
230       } else {
231         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
232         ++SI;
233         SplitData.erase(Delete_SI);
234       }
235     } else
236       ++SI;
237   }
238
239   if (SplitData.empty())
240     return false;
241
242   // Split most profitiable condition.
243   // FIXME : Implement cost analysis.
244   unsigned MostProfitableSDIndex = 0;
245   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
246
247   if (Changed)
248     ++NumIndexSplit;
249   
250   return Changed;
251 }
252
253 /// Return true if V is a induction variable or induction variable's
254 /// increment for loop L.
255 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
256   
257   Instruction *I = dyn_cast<Instruction>(V);
258   if (!I)
259     return;
260
261   // Check if I is a phi node from loop header or not.
262   if (PHINode *PN = dyn_cast<PHINode>(V)) {
263     if (PN->getParent() == L->getHeader()) {
264       IndVar = PN;
265       return;
266     }
267   }
268  
269   // Check if I is a add instruction whose one operand is
270   // phi node from loop header and second operand is constant.
271   if (I->getOpcode() != Instruction::Add)
272     return;
273   
274   Value *Op0 = I->getOperand(0);
275   Value *Op1 = I->getOperand(1);
276   
277   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
278     if (PN->getParent() == L->getHeader()
279         && isa<ConstantInt>(Op1)) {
280       IndVar = PN;
281       IndVarIncrement = I;
282       return;
283     }
284   }
285   
286   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
287     if (PN->getParent() == L->getHeader()
288         && isa<ConstantInt>(Op0)) {
289       IndVar = PN;
290       IndVarIncrement = I;
291       return;
292     }
293   }
294   
295   return;
296 }
297
298 // Find loop's exit condition and associated induction variable.
299 void LoopIndexSplit::findLoopConditionals() {
300
301   BasicBlock *ExitingBlock = NULL;
302
303   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
304        I != E; ++I) {
305     BasicBlock *BB = *I;
306     if (!L->isLoopExit(BB))
307       continue;
308     if (ExitingBlock)
309       return;
310     ExitingBlock = BB;
311   }
312
313   if (!ExitingBlock)
314     return;
315
316   // If exiting block is neither loop header nor loop latch then this loop is
317   // not suitable. 
318   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
319     return;
320
321   // If exit block's terminator is conditional branch inst then we have found
322   // exit condition.
323   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
324   if (!BR || BR->isUnconditional())
325     return;
326   
327   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
328   if (!CI)
329     return;
330
331   // FIXME
332   if (CI->getPredicate() == ICmpInst::ICMP_EQ
333       || CI->getPredicate() == ICmpInst::ICMP_NE)
334     return;
335
336   if (CI->getPredicate() == ICmpInst::ICMP_SGT
337       || CI->getPredicate() == ICmpInst::ICMP_UGT
338       || CI->getPredicate() == ICmpInst::ICMP_SGE
339       || CI->getPredicate() == ICmpInst::ICMP_UGE) {
340
341     BasicBlock *FirstSuccessor = BR->getSuccessor(0);
342     // splitLoop() is expecting LT/LE as exit condition predicate.
343     // Swap operands here if possible to meet this requirement.
344     if (!L->contains(FirstSuccessor)) 
345       CI->swapOperands();
346     else
347       return;
348   }
349
350   ExitCondition = CI;
351
352   // Exit condition's one operand is loop invariant exit value and second 
353   // operand is SCEVAddRecExpr based on induction variable.
354   Value *V0 = CI->getOperand(0);
355   Value *V1 = CI->getOperand(1);
356   
357   SCEVHandle SH0 = SE->getSCEV(V0);
358   SCEVHandle SH1 = SE->getSCEV(V1);
359   
360   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
361     ExitValueNum = 0;
362     findIndVar(V1, L);
363   }
364   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
365     ExitValueNum =  1;
366     findIndVar(V0, L);
367   }
368
369   if (!IndVar) 
370     ExitCondition = NULL;
371   else if (IndVar) {
372     BasicBlock *Preheader = L->getLoopPreheader();
373     StartValue = IndVar->getIncomingValueForBlock(Preheader);
374   }
375 }
376
377 /// Find condition inside a loop that is suitable candidate for index split.
378 void LoopIndexSplit::findSplitCondition() {
379
380   SplitInfo SD;
381   // Check all basic block's terminators.
382
383   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
384        I != E; ++I) {
385     BasicBlock *BB = *I;
386
387     // If this basic block does not terminate in a conditional branch
388     // then terminator is not a suitable split condition.
389     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
390     if (!BR)
391       continue;
392     
393     if (BR->isUnconditional())
394       continue;
395
396     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
397     if (!CI || CI == ExitCondition)
398       return;
399
400     if (CI->getPredicate() == ICmpInst::ICMP_NE)
401       return;
402
403     // If split condition predicate is GT or GE then first execute
404     // false branch of split condition.
405     if (CI->getPredicate() != ICmpInst::ICMP_ULT
406         && CI->getPredicate() != ICmpInst::ICMP_SLT
407         && CI->getPredicate() != ICmpInst::ICMP_ULE
408         && CI->getPredicate() != ICmpInst::ICMP_SLE)
409       SD.UseTrueBranchFirst = false;
410
411     // If one operand is loop invariant and second operand is SCEVAddRecExpr
412     // based on induction variable then CI is a candidate split condition.
413     Value *V0 = CI->getOperand(0);
414     Value *V1 = CI->getOperand(1);
415
416     SCEVHandle SH0 = SE->getSCEV(V0);
417     SCEVHandle SH1 = SE->getSCEV(V1);
418
419     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
420       SD.SplitValue = V0;
421       SD.SplitCondition = CI;
422       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
423         if (PN == IndVar)
424           SplitData.push_back(SD);
425       }
426       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
427         if (IndVarIncrement && IndVarIncrement == Insn)
428           SplitData.push_back(SD);
429       }
430     }
431     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
432       SD.SplitValue =  V1;
433       SD.SplitCondition = CI;
434       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
435         if (PN == IndVar)
436           SplitData.push_back(SD);
437       }
438       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
439         if (IndVarIncrement && IndVarIncrement == Insn)
440           SplitData.push_back(SD);
441       }
442     }
443   }
444 }
445
446 /// processOneIterationLoop - Current loop L contains compare instruction
447 /// that compares induction variable, IndVar, against loop invariant. If
448 /// entire (i.e. meaningful) loop body is dominated by this compare
449 /// instruction then loop body is executed only once. In such case eliminate 
450 /// loop structure surrounding this loop body. For example,
451 ///     for (int i = start; i < end; ++i) {
452 ///         if ( i == somevalue) {
453 ///           loop_body
454 ///         }
455 ///     }
456 /// can be transformed into
457 ///     if (somevalue >= start && somevalue < end) {
458 ///        i = somevalue;
459 ///        loop_body
460 ///     }
461 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
462
463   BasicBlock *Header = L->getHeader();
464
465   // First of all, check if SplitCondition dominates entire loop body
466   // or not.
467   
468   // If SplitCondition is not in loop header then this loop is not suitable
469   // for this transformation.
470   if (SD.SplitCondition->getParent() != Header)
471     return false;
472   
473   // If loop header includes loop variant instruction operands then
474   // this loop may not be eliminated.
475   if (!safeHeader(SD, Header)) 
476     return false;
477
478   // If Exiting block includes loop variant instructions then this
479   // loop may not be eliminated.
480   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
481     return false;
482
483   // Update CFG.
484
485   // Replace index variable with split value in loop body. Loop body is executed
486   // only when index variable is equal to split value.
487   IndVar->replaceAllUsesWith(SD.SplitValue);
488
489   // Remove Latch to Header edge.
490   BasicBlock *Latch = L->getLoopLatch();
491   BasicBlock *LatchSucc = NULL;
492   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
493   if (!BR)
494     return false;
495   Header->removePredecessor(Latch);
496   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
497        SI != E; ++SI) {
498     if (Header != *SI)
499       LatchSucc = *SI;
500   }
501   BR->setUnconditionalDest(LatchSucc);
502
503   Instruction *Terminator = Header->getTerminator();
504   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
505
506   // Replace split condition in header.
507   // Transform 
508   //      SplitCondition : icmp eq i32 IndVar, SplitValue
509   // into
510   //      c1 = icmp uge i32 SplitValue, StartValue
511   //      c2 = icmp ult i32 vSplitValue, ExitValue
512   //      and i32 c1, c2 
513   bool SignedPredicate = ExitCondition->isSignedPredicate();
514   Instruction *C1 = new ICmpInst(SignedPredicate ? 
515                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
516                                  SD.SplitValue, StartValue, "lisplit", 
517                                  Terminator);
518   Instruction *C2 = new ICmpInst(SignedPredicate ? 
519                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
520                                  SD.SplitValue, ExitValue, "lisplit", 
521                                  Terminator);
522   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
523                                                       Terminator);
524   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
525   SD.SplitCondition->eraseFromParent();
526
527   // Now, clear latch block. Remove instructions that are responsible
528   // to increment induction variable. 
529   Instruction *LTerminator = Latch->getTerminator();
530   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
531        LB != LE; ) {
532     Instruction *I = LB;
533     ++LB;
534     if (isa<PHINode>(I) || I == LTerminator)
535       continue;
536
537     if (I == IndVarIncrement) 
538       I->replaceAllUsesWith(ExitValue);
539     else
540       I->replaceAllUsesWith(UndefValue::get(I->getType()));
541     I->eraseFromParent();
542   }
543
544   LPM->deleteLoopFromQueue(L);
545
546   // Update Dominator Info.
547   // Only CFG change done is to remove Latch to Header edge. This
548   // does not change dominator tree because Latch did not dominate
549   // Header.
550   if (DF) {
551     DominanceFrontier::iterator HeaderDF = DF->find(Header);
552     if (HeaderDF != DF->end()) 
553       DF->removeFromFrontier(HeaderDF, Header);
554
555     DominanceFrontier::iterator LatchDF = DF->find(Latch);
556     if (LatchDF != DF->end()) 
557       DF->removeFromFrontier(LatchDF, Header);
558   }
559   return true;
560 }
561
562 // If loop header includes loop variant instruction operands then
563 // this loop can not be eliminated. This is used by processOneIterationLoop().
564 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
565
566   Instruction *Terminator = Header->getTerminator();
567   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
568       BI != BE; ++BI) {
569     Instruction *I = BI;
570
571     // PHI Nodes are OK.
572     if (isa<PHINode>(I))
573       continue;
574
575     // SplitCondition itself is OK.
576     if (I == SD.SplitCondition)
577       continue;
578
579     // Induction variable is OK.
580     if (I == IndVar)
581       continue;
582
583     // Induction variable increment is OK.
584     if (I == IndVarIncrement)
585       continue;
586
587     // Terminator is also harmless.
588     if (I == Terminator)
589       continue;
590
591     // Otherwise we have a instruction that may not be safe.
592     return false;
593   }
594   
595   return true;
596 }
597
598 // If Exiting block includes loop variant instructions then this
599 // loop may not be eliminated. This is used by processOneIterationLoop().
600 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
601                                        BasicBlock *ExitingBlock) {
602
603   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
604          BE = ExitingBlock->end(); BI != BE; ++BI) {
605     Instruction *I = BI;
606
607     // PHI Nodes are OK.
608     if (isa<PHINode>(I))
609       continue;
610
611     // Induction variable increment is OK.
612     if (IndVarIncrement && IndVarIncrement == I)
613       continue;
614
615     // Check if I is induction variable increment instruction.
616     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
617
618       Value *Op0 = I->getOperand(0);
619       Value *Op1 = I->getOperand(1);
620       PHINode *PN = NULL;
621       ConstantInt *CI = NULL;
622
623       if ((PN = dyn_cast<PHINode>(Op0))) {
624         if ((CI = dyn_cast<ConstantInt>(Op1)))
625           IndVarIncrement = I;
626       } else 
627         if ((PN = dyn_cast<PHINode>(Op1))) {
628           if ((CI = dyn_cast<ConstantInt>(Op0)))
629             IndVarIncrement = I;
630       }
631           
632       if (IndVarIncrement && PN == IndVar && CI->isOne())
633         continue;
634     }
635
636     // I is an Exit condition if next instruction is block terminator.
637     // Exit condition is OK if it compares loop invariant exit value,
638     // which is checked below.
639     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
640       if (EC == ExitCondition)
641         continue;
642     }
643
644     if (I == ExitingBlock->getTerminator())
645       continue;
646
647     // Otherwise we have instruction that may not be safe.
648     return false;
649   }
650
651   // We could not find any reason to consider ExitingBlock unsafe.
652   return true;
653 }
654
655 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
656 /// This routine is used to remove split condition's dead branch, dominated by
657 /// DeadBB. LiveBB dominates split conidition's other branch.
658 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
659                                   BasicBlock *LiveBB) {
660
661   // First update DeadBB's dominance frontier. 
662   SmallVector<BasicBlock *, 8> FrontierBBs;
663   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
664   if (DeadBBDF != DF->end()) {
665     SmallVector<BasicBlock *, 8> PredBlocks;
666     
667     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
668     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
669            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
670       BasicBlock *FrontierBB = *DeadBBSetI;
671       FrontierBBs.push_back(FrontierBB);
672
673       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
674       PredBlocks.clear();
675       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
676           PI != PE; ++PI) {
677         BasicBlock *P = *PI;
678         if (P == DeadBB || DT->dominates(DeadBB, P))
679           PredBlocks.push_back(P);
680       }
681
682       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
683           FBI != FBE; ++FBI) {
684         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
685           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
686                 PE = PredBlocks.end(); PI != PE; ++PI) {
687             BasicBlock *P = *PI;
688             PN->removeIncomingValue(P);
689           }
690         }
691         else
692           break;
693       }      
694     }
695   }
696   
697   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
698   SmallVector<BasicBlock *, 32> WorkList;
699   DomTreeNode *DN = DT->getNode(DeadBB);
700   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
701          E = df_end(DN); DI != E; ++DI) {
702     BasicBlock *BB = DI->getBlock();
703     WorkList.push_back(BB);
704     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
705   }
706
707   while (!WorkList.empty()) {
708     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
709     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
710         BBI != BBE; ++BBI) {
711       Instruction *I = BBI;
712       I->replaceAllUsesWith(UndefValue::get(I->getType()));
713       I->eraseFromParent();
714     }
715     LPM->deleteSimpleAnalysisValue(BB, LP);
716     DT->eraseNode(BB);
717     DF->removeBlock(BB);
718     LI->removeBlock(BB);
719     BB->eraseFromParent();
720   }
721
722   // Update Frontier BBs' dominator info.
723   while (!FrontierBBs.empty()) {
724     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
725     BasicBlock *NewDominator = FBB->getSinglePredecessor();
726     if (!NewDominator) {
727       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
728       NewDominator = *PI;
729       ++PI;
730       if (NewDominator != LiveBB) {
731         for(; PI != PE; ++PI) {
732           BasicBlock *P = *PI;
733           if (P == LiveBB) {
734             NewDominator = LiveBB;
735             break;
736           }
737           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
738         }
739       }
740     }
741     assert (NewDominator && "Unable to fix dominator info.");
742     DT->changeImmediateDominator(FBB, NewDominator);
743     DF->changeImmediateDominator(FBB, NewDominator, DT);
744   }
745
746 }
747
748 /// safeSplitCondition - Return true if it is possible to
749 /// split loop using given split condition.
750 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
751
752   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
753   
754   // Unable to handle triange loops at the moment.
755   // In triangle loop, split condition is in header and one of the
756   // the split destination is loop latch. If split condition is EQ
757   // then such loops are already handle in processOneIterationLoop().
758   BasicBlock *Latch = L->getLoopLatch();
759   BranchInst *SplitTerminator = 
760     cast<BranchInst>(SplitCondBlock->getTerminator());
761   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
762   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
763   if (L->getHeader() == SplitCondBlock 
764       && (Latch == Succ0 || Latch == Succ1))
765     return false;
766   
767   // If split condition branches heads do not have single predecessor, 
768   // SplitCondBlock, then is not possible to remove inactive branch.
769   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
770     return false;
771
772   // Finally this split condition is safe only if merge point for
773   // split condition branch is loop latch. This check along with previous
774   // check, to ensure that exit condition is in either loop latch or header,
775   // filters all loops with non-empty loop body between merge point
776   // and exit condition.
777   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
778   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
779   if (Succ0DF->second.count(Latch))
780     return true;
781
782   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
783   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
784   if (Succ1DF->second.count(Latch))
785     return true;
786   
787   return false;
788 }
789
790 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
791 /// based on split value. 
792 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
793
794   ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
795   const Type *Ty = SD.SplitValue->getType();
796   bool Sign = ExitCondition->isSignedPredicate();
797   BasicBlock *Preheader = L->getLoopPreheader();
798   Instruction *PHTerminator = Preheader->getTerminator();
799
800   // Initially use split value as upper loop bound for first loop and lower loop
801   // bound for second loop.
802   Value *AEV = SD.SplitValue;
803   Value *BSV = SD.SplitValue;
804
805   switch (ExitCondition->getPredicate()) {
806   case ICmpInst::ICMP_SGT:
807   case ICmpInst::ICMP_UGT:
808   case ICmpInst::ICMP_SGE:
809   case ICmpInst::ICMP_UGE:
810   default:
811     assert (0 && "Unexpected exit condition predicate");
812
813   case ICmpInst::ICMP_SLT:
814   case ICmpInst::ICMP_ULT:
815     {
816       switch (SP) {
817       case ICmpInst::ICMP_SLT:
818       case ICmpInst::ICMP_ULT:
819         //
820         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
821         //
822         // is transformed into
823         // AEV = BSV = SV
824         // for (i = LB; i < min(UB, AEV); ++i)
825         //    A;
826         // for (i = max(LB, BSV); i < UB; ++i);
827         //    B;
828         break;
829       case ICmpInst::ICMP_SLE:
830       case ICmpInst::ICMP_ULE:
831         {
832           //
833           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
834           //
835           // is transformed into
836           //
837           // AEV = SV + 1
838           // BSV = SV + 1
839           // for (i = LB; i < min(UB, AEV); ++i) 
840           //       A;
841           // for (i = max(LB, BSV); i < UB; ++i) 
842           //       B;
843           BSV = BinaryOperator::createAdd(SD.SplitValue,
844                                           ConstantInt::get(Ty, 1, Sign),
845                                           "lsplit.add", PHTerminator);
846           AEV = BSV;
847         }
848         break;
849       case ICmpInst::ICMP_SGE:
850       case ICmpInst::ICMP_UGE: 
851         //
852         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
853         // 
854         // is transformed into
855         // AEV = BSV = SV
856         // for (i = LB; i < min(UB, AEV); ++i)
857         //    B;
858         // for (i = max(BSV, LB); i < UB; ++i)
859         //    A;
860         break;
861       case ICmpInst::ICMP_SGT:
862       case ICmpInst::ICMP_UGT: 
863         {
864           //
865           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
866           //
867           // is transformed into
868           //
869           // BSV = AEV = SV + 1
870           // for (i = LB; i < min(UB, AEV); ++i) 
871           //       B;
872           // for (i = max(LB, BSV); i < UB; ++i) 
873           //       A;
874           BSV = BinaryOperator::createAdd(SD.SplitValue,
875                                           ConstantInt::get(Ty, 1, Sign),
876                                           "lsplit.add", PHTerminator);
877           AEV = BSV;
878         }
879         break;
880       default:
881         assert (0 && "Unexpected split condition predicate");
882         break;
883       } // end switch (SP)
884     }
885     break;
886   case ICmpInst::ICMP_SLE:
887   case ICmpInst::ICMP_ULE:
888     {
889       switch (SP) {
890       case ICmpInst::ICMP_SLT:
891       case ICmpInst::ICMP_ULT:
892         //
893         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
894         //
895         // is transformed into
896         // AEV = SV - 1;
897         // BSV = SV;
898         // for (i = LB; i <= min(UB, AEV); ++i) 
899         //       A;
900         // for (i = max(LB, BSV); i <= UB; ++i) 
901         //       B;
902         AEV = BinaryOperator::createSub(SD.SplitValue,
903                                         ConstantInt::get(Ty, 1, Sign),
904                                         "lsplit.sub", PHTerminator);
905         break;
906       case ICmpInst::ICMP_SLE:
907       case ICmpInst::ICMP_ULE:
908         //
909         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
910         //
911         // is transformed into
912         // AEV = SV;
913         // BSV = SV + 1;
914         // for (i = LB; i <= min(UB, AEV); ++i) 
915         //       A;
916         // for (i = max(LB, BSV); i <= UB; ++i) 
917         //       B;
918         BSV = BinaryOperator::createAdd(SD.SplitValue,
919                                         ConstantInt::get(Ty, 1, Sign),
920                                         "lsplit.add", PHTerminator);
921         break;
922       case ICmpInst::ICMP_SGT:
923       case ICmpInst::ICMP_UGT: 
924         //
925         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
926         //
927         // is transformed into
928         // AEV = SV;
929         // BSV = SV + 1;
930         // for (i = LB; i <= min(AEV, UB); ++i)
931         //      B;
932         // for (i = max(LB, BSV); i <= UB; ++i)
933         //      A;
934         BSV = BinaryOperator::createAdd(SD.SplitValue,
935                                         ConstantInt::get(Ty, 1, Sign),
936                                         "lsplit.add", PHTerminator);
937         break;
938       case ICmpInst::ICMP_SGE:
939       case ICmpInst::ICMP_UGE: 
940         // ** TODO **
941         //
942         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
943         //
944         // is transformed into
945         // AEV = SV - 1;
946         // BSV = SV;
947         // for (i = LB; i <= min(AEV, UB); ++i)
948         //      B;
949         // for (i = max(LB, BSV); i <= UB; ++i)
950         //      A;
951         AEV = BinaryOperator::createSub(SD.SplitValue,
952                                         ConstantInt::get(Ty, 1, Sign),
953                                         "lsplit.sub", PHTerminator);
954         break;
955       default:
956         assert (0 && "Unexpected split condition predicate");
957         break;
958       } // end switch (SP)
959     }
960     break;
961   }
962
963   // Calculate ALoop induction variable's new exiting value and
964   // BLoop induction variable's new starting value. Calculuate these
965   // values in original loop's preheader.
966   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
967   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
968   Value *C1 = new ICmpInst(Sign ?
969                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
970                            AEV,
971                            ExitCondition->getOperand(ExitValueNum), 
972                            "lsplit.ev", PHTerminator);
973   SD.A_ExitValue = new SelectInst(C1, AEV,
974                                   ExitCondition->getOperand(ExitValueNum), 
975                                   "lsplit.ev", PHTerminator);
976   
977   Value *C2 = new ICmpInst(Sign ?
978                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
979                            BSV, StartValue, "lsplit.sv",
980                            PHTerminator);
981   SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
982                                    "lsplit.sv", PHTerminator);
983 }
984
985 /// splitLoop - Split current loop L in two loops using split information
986 /// SD. Update dominator information. Maintain LCSSA form.
987 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
988
989   if (!safeSplitCondition(SD))
990     return false;
991
992   // After loop is cloned there are two loops.
993   //
994   // First loop, referred as ALoop, executes first part of loop's iteration
995   // space split.  Second loop, referred as BLoop, executes remaining
996   // part of loop's iteration space. 
997   //
998   // ALoop's exit edge enters BLoop's header through a forwarding block which 
999   // acts as a BLoop's preheader.
1000   BasicBlock *Preheader = L->getLoopPreheader();
1001
1002   // Calculate ALoop induction variable's new exiting value and
1003   // BLoop induction variable's new starting value.
1004   calculateLoopBounds(SD);
1005
1006   //[*] Clone loop.
1007   DenseMap<const Value *, Value *> ValueMap;
1008   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1009   Loop *ALoop = L;
1010   BasicBlock *B_Header = BLoop->getHeader();
1011
1012   //[*] ALoop's exiting edge BLoop's header.
1013   //    ALoop's original exit block becomes BLoop's exit block.
1014   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1015   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1016   BranchInst *A_ExitInsn =
1017     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1018   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1019   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1020   if (L->contains(B_ExitBlock)) {
1021     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1022     A_ExitInsn->setSuccessor(0, B_Header);
1023   } else
1024     A_ExitInsn->setSuccessor(1, B_Header);
1025
1026   //[*] Update ALoop's exit value using new exit value.
1027   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1028   
1029   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1030   //     original loop's preheader. Add incoming PHINode values from
1031   //     ALoop's exiting block. Update BLoop header's domiantor info.
1032
1033   // Collect inverse map of Header PHINodes.
1034   DenseMap<Value *, Value *> InverseMap;
1035   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1036          BE = L->getHeader()->end(); BI != BE; ++BI) {
1037     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1038       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1039       InverseMap[PNClone] = PN;
1040     } else
1041       break;
1042   }
1043
1044   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1045        BI != BE; ++BI) {
1046     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1047       // Remove incoming value from original preheader.
1048       PN->removeIncomingValue(Preheader);
1049
1050       // Add incoming value from A_ExitingBlock.
1051       if (PN == B_IndVar)
1052         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1053       else { 
1054         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1055         Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1056         PN->addIncoming(V2, A_ExitingBlock);
1057       }
1058     } else
1059       break;
1060   }
1061   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1062   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1063   
1064   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1065   //     block. Remove incoming PHINode values from ALoop's exiting block.
1066   //     Add new incoming values from BLoop's incoming exiting value.
1067   //     Update BLoop exit block's dominator info..
1068   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1069   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1070        BI != BE; ++BI) {
1071     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1072       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1073                                                             B_ExitingBlock);
1074       PN->removeIncomingValue(A_ExitingBlock);
1075     } else
1076       break;
1077   }
1078
1079   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1080   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1081
1082   //[*] Split ALoop's exit edge. This creates a new block which
1083   //    serves two purposes. First one is to hold PHINode defnitions
1084   //    to ensure that ALoop's LCSSA form. Second use it to act
1085   //    as a preheader for BLoop.
1086   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1087
1088   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1089   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1090   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1091       BI != BE; ++BI) {
1092     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1093       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1094       PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1095       newPHI->addIncoming(V1, A_ExitingBlock);
1096       A_ExitBlock->getInstList().push_front(newPHI);
1097       PN->removeIncomingValue(A_ExitBlock);
1098       PN->addIncoming(newPHI, A_ExitBlock);
1099     } else
1100       break;
1101   }
1102
1103   //[*] Eliminate split condition's inactive branch from ALoop.
1104   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1105   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1106   BasicBlock *A_InactiveBranch = NULL;
1107   BasicBlock *A_ActiveBranch = NULL;
1108   if (SD.UseTrueBranchFirst) {
1109     A_ActiveBranch = A_BR->getSuccessor(0);
1110     A_InactiveBranch = A_BR->getSuccessor(1);
1111   } else {
1112     A_ActiveBranch = A_BR->getSuccessor(1);
1113     A_InactiveBranch = A_BR->getSuccessor(0);
1114   }
1115   A_BR->setUnconditionalDest(A_ActiveBranch);
1116   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1117
1118   //[*] Eliminate split condition's inactive branch in from BLoop.
1119   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1120   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1121   BasicBlock *B_InactiveBranch = NULL;
1122   BasicBlock *B_ActiveBranch = NULL;
1123   if (SD.UseTrueBranchFirst) {
1124     B_ActiveBranch = B_BR->getSuccessor(1);
1125     B_InactiveBranch = B_BR->getSuccessor(0);
1126   } else {
1127     B_ActiveBranch = B_BR->getSuccessor(0);
1128     B_InactiveBranch = B_BR->getSuccessor(1);
1129   }
1130   B_BR->setUnconditionalDest(B_ActiveBranch);
1131   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1132
1133   BasicBlock *A_Header = L->getHeader();
1134   if (A_ExitingBlock == A_Header)
1135     return true;
1136
1137   //[*] Move exit condition into split condition block to avoid
1138   //    executing dead loop iteration.
1139   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1140   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1141   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1142
1143   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1144                     SD.SplitCondition, IndVar, IndVarIncrement, ALoop);
1145
1146   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1147                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1148
1149   return true;
1150 }
1151
1152 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1153 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1154                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1155                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1156
1157   BasicBlock *ExitingBB = EC->getParent();
1158   Instruction *CurrentBR = CondBB->getTerminator();
1159
1160   // Move exit condition into split condition block.
1161   EC->moveBefore(CurrentBR);
1162   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1163
1164   // Move exiting block's branch into split condition block. Update its branch
1165   // destination.
1166   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1167   ExitingBR->moveBefore(CurrentBR);
1168   if (ExitingBR->getSuccessor(0) == ExitBB)
1169     ExitingBR->setSuccessor(1, ActiveBB);
1170   else
1171     ExitingBR->setSuccessor(0, ActiveBB);
1172     
1173   // Remove split condition and current split condition branch.
1174   SC->eraseFromParent();
1175   CurrentBR->eraseFromParent();
1176
1177   // Connect exiting block to split condition block.
1178   new BranchInst(CondBB, ExitingBB);
1179
1180   // Update PHINodes
1181   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1182
1183   // Fix dominator info.
1184   // ExitBB is now dominated by CondBB
1185   DT->changeImmediateDominator(ExitBB, CondBB);
1186   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1187   
1188   // Basicblocks dominated by ActiveBB may have ExitingBB or
1189   // a basic block outside the loop in their DF list. If so,
1190   // replace it with CondBB.
1191   DomTreeNode *Node = DT->getNode(ActiveBB);
1192   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1193        DI != DE; ++DI) {
1194     BasicBlock *BB = DI->getBlock();
1195     DominanceFrontier::iterator BBDF = DF->find(BB);
1196     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1197     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1198     while (DomSetI != DomSetE) {
1199       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1200       ++DomSetI;
1201       BasicBlock *DFBB = *CurrentItr;
1202       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1203         BBDF->second.erase(DFBB);
1204         BBDF->second.insert(CondBB);
1205       }
1206     }
1207   }
1208 }
1209
1210 /// updatePHINodes - CFG has been changed. 
1211 /// Before 
1212 ///   - ExitBB's single predecessor was Latch
1213 ///   - Latch's second successor was Header
1214 /// Now
1215 ///   - ExitBB's single predecessor was Header
1216 ///   - Latch's one and only successor was Header
1217 ///
1218 /// Update ExitBB PHINodes' to reflect this change.
1219 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1220                                     BasicBlock *Header,
1221                                     PHINode *IV, Instruction *IVIncrement) {
1222
1223   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1224        BI != BE; ++BI) {
1225     PHINode *PN = dyn_cast<PHINode>(BI);
1226     if (!PN)
1227       break;
1228
1229     Value *V = PN->getIncomingValueForBlock(Latch);
1230     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1231       // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode 
1232       // (i.e. PN :)). 
1233       // The second use is in Header and it is new incoming value for PN.
1234       PHINode *U1 = NULL;
1235       PHINode *U2 = NULL;
1236       Value *NewV = NULL;
1237       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1238            UI != E; ++UI) {
1239         if (!U1)
1240           U1 = cast<PHINode>(*UI);
1241         else if (!U2)
1242           U2 = cast<PHINode>(*UI);
1243         else
1244           assert ( 0 && "Unexpected third use of this PHINode");
1245       }
1246       assert (U1 && U2 && "Unable to find two uses");
1247       
1248       if (U1->getParent() == Header) 
1249         NewV = U1;
1250       else
1251         NewV = U2;
1252       PN->addIncoming(NewV, Header);
1253
1254     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1255       // If this instruction is IVIncrement then IV is new incoming value 
1256       // from header otherwise this instruction must be incoming value from 
1257       // header because loop is in LCSSA form.
1258       if (PHI == IVIncrement)
1259         PN->addIncoming(IV, Header);
1260       else
1261         PN->addIncoming(V, Header);
1262     } else
1263       // Otherwise this is an incoming value from header because loop is in 
1264       // LCSSA form.
1265       PN->addIncoming(V, Header);
1266     
1267     // Remove incoming value from Latch.
1268     PN->removeIncomingValue(Latch);
1269   }
1270 }