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