a6bd9ff20a9ae965ea31d325ae45f39580d88955
[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 is distributed under the University of Illinois Open Source
6 // 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     void updateLoopBounds(ICmpInst *CI);
116     /// updateLoopIterationSpace - Current loop body is covered by an AND
117     /// instruction whose operands compares induction variables with loop
118     /// invariants. If possible, hoist this check outside the loop by
119     /// updating appropriate start and end values for induction variable.
120     bool updateLoopIterationSpace(SplitInfo &SD);
121
122     /// If loop header includes loop variant instruction operands then
123     /// this loop may not be eliminated.
124     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
125
126     /// If Exiting block includes loop variant instructions then this
127     /// loop may not be eliminated.
128     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
129
130     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131     /// This routine is used to remove split condition's dead branch, dominated by
132     /// DeadBB. LiveBB dominates split conidition's other branch.
133     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
134
135     /// safeSplitCondition - Return true if it is possible to
136     /// split loop using given split condition.
137     bool safeSplitCondition(SplitInfo &SD);
138
139     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140     /// based on split value. 
141     void calculateLoopBounds(SplitInfo &SD);
142
143     /// updatePHINodes - CFG has been changed. 
144     /// Before 
145     ///   - ExitBB's single predecessor was Latch
146     ///   - Latch's second successor was Header
147     /// Now
148     ///   - ExitBB's single predecessor was Header
149     ///   - Latch's one and only successor was Header
150     ///
151     /// Update ExitBB PHINodes' to reflect this change.
152     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
153                         BasicBlock *Header,
154                         PHINode *IV, Instruction *IVIncrement, Loop *LP);
155
156     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159                            PHINode *IV, Instruction *IVAdd, Loop *LP);
160
161     /// splitLoop - Split current loop L in two loops using split information
162     /// SD. Update dominator information. Maintain LCSSA form.
163     bool splitLoop(SplitInfo &SD);
164
165     void initialize() {
166       IndVar = NULL; 
167       IndVarIncrement = NULL;
168       ExitCondition = NULL;
169       StartValue = NULL;
170       ExitValueNum = 0;
171       SplitData.clear();
172     }
173
174   private:
175
176     // Current Loop.
177     Loop *L;
178     LPPassManager *LPM;
179     LoopInfo *LI;
180     ScalarEvolution *SE;
181     DominatorTree *DT;
182     DominanceFrontier *DF;
183     SmallVector<SplitInfo, 4> SplitData;
184
185     // Induction variable whose range is being split by this transformation.
186     PHINode *IndVar;
187     Instruction *IndVarIncrement;
188       
189     // Loop exit condition.
190     ICmpInst *ExitCondition;
191
192     // Induction variable's initial value.
193     Value *StartValue;
194
195     // Induction variable's final loop exit value operand number in exit condition..
196     unsigned ExitValueNum;
197   };
198
199   char LoopIndexSplit::ID = 0;
200   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
201 }
202
203 LoopPass *llvm::createLoopIndexSplitPass() {
204   return new LoopIndexSplit();
205 }
206
207 // Index split Loop L. Return true if loop is split.
208 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
209   bool Changed = false;
210   L = IncomingLoop;
211   LPM = &LPM_Ref;
212
213   // FIXME - Nested loops make dominator info updates tricky. 
214   if (!L->getSubLoops().empty())
215     return false;
216
217   SE = &getAnalysis<ScalarEvolution>();
218   DT = &getAnalysis<DominatorTree>();
219   LI = &getAnalysis<LoopInfo>();
220   DF = &getAnalysis<DominanceFrontier>();
221
222   initialize();
223
224   findLoopConditionals();
225
226   if (!ExitCondition)
227     return false;
228
229   findSplitCondition();
230
231   if (SplitData.empty())
232     return false;
233
234   // First see if it is possible to eliminate loop itself or not.
235   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
236        SI != SplitData.end();) {
237     SplitInfo &SD = *SI;
238     ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
239     if (SD.SplitCondition->getOpcode() == Instruction::And) {
240       Changed = updateLoopIterationSpace(SD);
241       if (Changed) {
242         ++NumIndexSplit;
243         // If is loop is eliminated then nothing else to do here.
244         return Changed;
245       } else {
246         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
247         SI = SplitData.erase(Delete_SI);
248       }
249     }
250     else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
251       Changed = processOneIterationLoop(SD);
252       if (Changed) {
253         ++NumIndexSplit;
254         // If is loop is eliminated then nothing else to do here.
255         return Changed;
256       } else {
257         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
258         SI = SplitData.erase(Delete_SI);
259       }
260     } else
261       ++SI;
262   }
263
264   if (SplitData.empty())
265     return false;
266
267   // Split most profitiable condition.
268   // FIXME : Implement cost analysis.
269   unsigned MostProfitableSDIndex = 0;
270   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
271
272   if (Changed)
273     ++NumIndexSplit;
274   
275   return Changed;
276 }
277
278 /// Return true if V is a induction variable or induction variable's
279 /// increment for loop L.
280 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
281   
282   Instruction *I = dyn_cast<Instruction>(V);
283   if (!I)
284     return;
285
286   // Check if I is a phi node from loop header or not.
287   if (PHINode *PN = dyn_cast<PHINode>(V)) {
288     if (PN->getParent() == L->getHeader()) {
289       IndVar = PN;
290       return;
291     }
292   }
293  
294   // Check if I is a add instruction whose one operand is
295   // phi node from loop header and second operand is constant.
296   if (I->getOpcode() != Instruction::Add)
297     return;
298   
299   Value *Op0 = I->getOperand(0);
300   Value *Op1 = I->getOperand(1);
301   
302   if (PHINode *PN = dyn_cast<PHINode>(Op0)) 
303     if (PN->getParent() == L->getHeader()) 
304       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) 
305         if (CI->isOne()) {
306           IndVar = PN;
307           IndVarIncrement = I;
308           return;
309         }
310
311   if (PHINode *PN = dyn_cast<PHINode>(Op1)) 
312     if (PN->getParent() == L->getHeader()) 
313       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) 
314         if (CI->isOne()) {
315           IndVar = PN;
316           IndVarIncrement = I;
317           return;
318         }
319   
320   return;
321 }
322
323 // Find loop's exit condition and associated induction variable.
324 void LoopIndexSplit::findLoopConditionals() {
325
326   BasicBlock *ExitingBlock = NULL;
327
328   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
329        I != E; ++I) {
330     BasicBlock *BB = *I;
331     if (!L->isLoopExit(BB))
332       continue;
333     if (ExitingBlock)
334       return;
335     ExitingBlock = BB;
336   }
337
338   if (!ExitingBlock)
339     return;
340
341   // If exiting block is neither loop header nor loop latch then this loop is
342   // not suitable. 
343   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
344     return;
345
346   // If exit block's terminator is conditional branch inst then we have found
347   // exit condition.
348   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
349   if (!BR || BR->isUnconditional())
350     return;
351   
352   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
353   if (!CI)
354     return;
355
356   // FIXME 
357   if (CI->getPredicate() == ICmpInst::ICMP_EQ
358       || CI->getPredicate() == ICmpInst::ICMP_NE)
359     return;
360
361   ExitCondition = CI;
362
363   // Exit condition's one operand is loop invariant exit value and second 
364   // operand is SCEVAddRecExpr based on induction variable.
365   Value *V0 = CI->getOperand(0);
366   Value *V1 = CI->getOperand(1);
367   
368   SCEVHandle SH0 = SE->getSCEV(V0);
369   SCEVHandle SH1 = SE->getSCEV(V1);
370   
371   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
372     ExitValueNum = 0;
373     findIndVar(V1, L);
374   }
375   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
376     ExitValueNum =  1;
377     findIndVar(V0, L);
378   }
379
380   if (!IndVar) 
381     ExitCondition = NULL;
382   else if (IndVar) {
383     BasicBlock *Preheader = L->getLoopPreheader();
384     StartValue = IndVar->getIncomingValueForBlock(Preheader);
385   }
386 }
387
388 /// Find condition inside a loop that is suitable candidate for index split.
389 void LoopIndexSplit::findSplitCondition() {
390
391   SplitInfo SD;
392   // Check all basic block's terminators.
393   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
394        I != E; ++I) {
395     SD.clear();
396     BasicBlock *BB = *I;
397
398     // If this basic block does not terminate in a conditional branch
399     // then terminator is not a suitable split condition.
400     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
401     if (!BR)
402       continue;
403     
404     if (BR->isUnconditional())
405       continue;
406
407     if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
408       if (AndI->getOpcode() == Instruction::And) {
409         ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
410         ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
411
412         if (!Op0 || !Op1)
413           continue;
414
415         if (!safeICmpInst(Op0, SD))
416           continue;
417         SD.clear();
418         if (!safeICmpInst(Op1, SD))
419           continue;
420         SD.clear();
421         SD.SplitCondition = AndI;
422         SplitData.push_back(SD);
423         continue;
424       }
425     }
426     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
427     if (!CI || CI == ExitCondition)
428       continue;
429
430     if (CI->getPredicate() == ICmpInst::ICMP_NE)
431       continue;
432
433     // If split condition predicate is GT or GE then first execute
434     // false branch of split condition.
435     if (CI->getPredicate() == ICmpInst::ICMP_UGT
436         || CI->getPredicate() == ICmpInst::ICMP_SGT
437         || CI->getPredicate() == ICmpInst::ICMP_UGE
438         || CI->getPredicate() == ICmpInst::ICMP_SGE)
439       SD.UseTrueBranchFirst = false;
440
441     // If one operand is loop invariant and second operand is SCEVAddRecExpr
442     // based on induction variable then CI is a candidate split condition.
443     if (safeICmpInst(CI, SD))
444       SplitData.push_back(SD);
445   }
446 }
447
448 // safeIcmpInst - CI is considered safe instruction if one of the operand
449 // is SCEVAddRecExpr based on induction variable and other operand is
450 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
451 // and return true;
452 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
453
454   Value *V0 = CI->getOperand(0);
455   Value *V1 = CI->getOperand(1);
456   
457   SCEVHandle SH0 = SE->getSCEV(V0);
458   SCEVHandle SH1 = SE->getSCEV(V1);
459   
460   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
461     SD.SplitValue = V0;
462     SD.SplitCondition = CI;
463     if (PHINode *PN = dyn_cast<PHINode>(V1)) {
464       if (PN == IndVar)
465         return true;
466     }
467     else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
468       if (IndVarIncrement && IndVarIncrement == Insn)
469         return true;
470     }
471   }
472   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
473     SD.SplitValue =  V1;
474     SD.SplitCondition = CI;
475     if (PHINode *PN = dyn_cast<PHINode>(V0)) {
476       if (PN == IndVar)
477         return true;
478     }
479     else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
480       if (IndVarIncrement && IndVarIncrement == Insn)
481         return true;
482     }
483   }
484
485   return false;
486 }
487
488 /// processOneIterationLoop - Current loop L contains compare instruction
489 /// that compares induction variable, IndVar, against loop invariant. If
490 /// entire (i.e. meaningful) loop body is dominated by this compare
491 /// instruction then loop body is executed only once. In such case eliminate 
492 /// loop structure surrounding this loop body. For example,
493 ///     for (int i = start; i < end; ++i) {
494 ///         if ( i == somevalue) {
495 ///           loop_body
496 ///         }
497 ///     }
498 /// can be transformed into
499 ///     if (somevalue >= start && somevalue < end) {
500 ///        i = somevalue;
501 ///        loop_body
502 ///     }
503 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
504
505   BasicBlock *Header = L->getHeader();
506
507   // First of all, check if SplitCondition dominates entire loop body
508   // or not.
509   
510   // If SplitCondition is not in loop header then this loop is not suitable
511   // for this transformation.
512   if (SD.SplitCondition->getParent() != Header)
513     return false;
514   
515   // If loop header includes loop variant instruction operands then
516   // this loop may not be eliminated.
517   if (!safeHeader(SD, Header)) 
518     return false;
519
520   // If Exiting block includes loop variant instructions then this
521   // loop may not be eliminated.
522   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
523     return false;
524
525   // Filter loops where split condition's false branch is not empty.
526   if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
527     return false;
528
529   // If split condition is not safe then do not process this loop.
530   // For example,
531   // for(int i = 0; i < N; i++) {
532   //    if ( i == XYZ) {
533   //      A;
534   //    else
535   //      B;
536   //    }
537   //   C;
538   //   D;
539   // }
540   if (!safeSplitCondition(SD))
541     return false;
542
543   BasicBlock *Latch = L->getLoopLatch();
544   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
545   if (!BR)
546     return false;
547
548   // Update CFG.
549
550   // Replace index variable with split value in loop body. Loop body is executed
551   // only when index variable is equal to split value.
552   IndVar->replaceAllUsesWith(SD.SplitValue);
553
554   // Remove Latch to Header edge.
555   BasicBlock *LatchSucc = NULL;
556   Header->removePredecessor(Latch);
557   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
558        SI != E; ++SI) {
559     if (Header != *SI)
560       LatchSucc = *SI;
561   }
562   BR->setUnconditionalDest(LatchSucc);
563
564   Instruction *Terminator = Header->getTerminator();
565   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
566
567   // Replace split condition in header.
568   // Transform 
569   //      SplitCondition : icmp eq i32 IndVar, SplitValue
570   // into
571   //      c1 = icmp uge i32 SplitValue, StartValue
572   //      c2 = icmp ult i32 SplitValue, ExitValue
573   //      and i32 c1, c2 
574   bool SignedPredicate = ExitCondition->isSignedPredicate();
575   Instruction *C1 = new ICmpInst(SignedPredicate ? 
576                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
577                                  SD.SplitValue, StartValue, "lisplit", 
578                                  Terminator);
579   Instruction *C2 = new ICmpInst(SignedPredicate ? 
580                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
581                                  SD.SplitValue, ExitValue, "lisplit", 
582                                  Terminator);
583   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
584                                                       Terminator);
585   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
586   SD.SplitCondition->eraseFromParent();
587
588   // Now, clear latch block. Remove instructions that are responsible
589   // to increment induction variable. 
590   Instruction *LTerminator = Latch->getTerminator();
591   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
592        LB != LE; ) {
593     Instruction *I = LB;
594     ++LB;
595     if (isa<PHINode>(I) || I == LTerminator)
596       continue;
597
598     if (I == IndVarIncrement) 
599       I->replaceAllUsesWith(ExitValue);
600     else
601       I->replaceAllUsesWith(UndefValue::get(I->getType()));
602     I->eraseFromParent();
603   }
604
605   LPM->deleteLoopFromQueue(L);
606
607   // Update Dominator Info.
608   // Only CFG change done is to remove Latch to Header edge. This
609   // does not change dominator tree because Latch did not dominate
610   // Header.
611   if (DF) {
612     DominanceFrontier::iterator HeaderDF = DF->find(Header);
613     if (HeaderDF != DF->end()) 
614       DF->removeFromFrontier(HeaderDF, Header);
615
616     DominanceFrontier::iterator LatchDF = DF->find(Latch);
617     if (LatchDF != DF->end()) 
618       DF->removeFromFrontier(LatchDF, Header);
619   }
620   return true;
621 }
622
623 // If loop header includes loop variant instruction operands then
624 // this loop can not be eliminated. This is used by processOneIterationLoop().
625 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
626
627   Instruction *Terminator = Header->getTerminator();
628   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
629       BI != BE; ++BI) {
630     Instruction *I = BI;
631
632     // PHI Nodes are OK.
633     if (isa<PHINode>(I))
634       continue;
635
636     // SplitCondition itself is OK.
637     if (I == SD.SplitCondition)
638       continue;
639
640     // Induction variable is OK.
641     if (I == IndVar)
642       continue;
643
644     // Induction variable increment is OK.
645     if (I == IndVarIncrement)
646       continue;
647
648     // Terminator is also harmless.
649     if (I == Terminator)
650       continue;
651
652     // Otherwise we have a instruction that may not be safe.
653     return false;
654   }
655   
656   return true;
657 }
658
659 // If Exiting block includes loop variant instructions then this
660 // loop may not be eliminated. This is used by processOneIterationLoop().
661 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
662                                        BasicBlock *ExitingBlock) {
663
664   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
665          BE = ExitingBlock->end(); BI != BE; ++BI) {
666     Instruction *I = BI;
667
668     // PHI Nodes are OK.
669     if (isa<PHINode>(I))
670       continue;
671
672     // Induction variable increment is OK.
673     if (IndVarIncrement && IndVarIncrement == I)
674       continue;
675
676     // Check if I is induction variable increment instruction.
677     if (I->getOpcode() == Instruction::Add) {
678
679       Value *Op0 = I->getOperand(0);
680       Value *Op1 = I->getOperand(1);
681       PHINode *PN = NULL;
682       ConstantInt *CI = NULL;
683
684       if ((PN = dyn_cast<PHINode>(Op0))) {
685         if ((CI = dyn_cast<ConstantInt>(Op1)))
686           if (CI->isOne()) {
687             if (!IndVarIncrement && PN == IndVar)
688               IndVarIncrement = I;
689             // else this is another loop induction variable
690             continue;
691           }
692       } else 
693         if ((PN = dyn_cast<PHINode>(Op1))) {
694           if ((CI = dyn_cast<ConstantInt>(Op0)))
695             if (CI->isOne()) {
696               if (!IndVarIncrement && PN == IndVar)
697                 IndVarIncrement = I;
698               // else this is another loop induction variable
699               continue;
700             }
701       }
702     } 
703
704     // I is an Exit condition if next instruction is block terminator.
705     // Exit condition is OK if it compares loop invariant exit value,
706     // which is checked below.
707     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
708       if (EC == ExitCondition)
709         continue;
710     }
711
712     if (I == ExitingBlock->getTerminator())
713       continue;
714
715     // Otherwise we have instruction that may not be safe.
716     return false;
717   }
718
719   // We could not find any reason to consider ExitingBlock unsafe.
720   return true;
721 }
722
723 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
724
725   Value *V0 = CI->getOperand(0);
726   Value *V1 = CI->getOperand(1);
727   Value *NV = NULL;
728
729   SCEVHandle SH0 = SE->getSCEV(V0);
730   
731   if (SH0->isLoopInvariant(L))
732     NV = V0;
733   else
734     NV = V1;
735
736   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
737       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
738       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
739       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)  {
740     ExitCondition->swapOperands();
741     if (ExitValueNum)
742       ExitValueNum = 0;
743     else
744       ExitValueNum = 1;
745   }
746
747   Value *NUB = NULL;
748   Value *NLB = NULL;
749   Value *UB = ExitCondition->getOperand(ExitValueNum);
750   const Type *Ty = NV->getType();
751   bool Sign = ExitCondition->isSignedPredicate();
752   BasicBlock *Preheader = L->getLoopPreheader();
753   Instruction *PHTerminator = Preheader->getTerminator();
754
755   assert (NV && "Unexpected value");
756
757   switch (CI->getPredicate()) {
758   case ICmpInst::ICMP_ULE:
759   case ICmpInst::ICMP_SLE:
760     // for (i = LB; i < UB; ++i)
761     //   if (i <= NV && ...)
762     //      LOOP_BODY
763     // 
764     // is transformed into
765     // NUB = min (NV+1, UB)
766     // for (i = LB; i < NUB ; ++i)
767     //   LOOP_BODY
768     //
769     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
770         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
771       Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
772                                            "lsplit.add", PHTerminator);
773       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
774                               A, UB,"lsplit,c", PHTerminator);
775       NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
776     }
777     
778     // for (i = LB; i <= UB; ++i)
779     //   if (i <= NV && ...)
780     //      LOOP_BODY
781     // 
782     // is transformed into
783     // NUB = min (NV, UB)
784     // for (i = LB; i <= NUB ; ++i)
785     //   LOOP_BODY
786     //
787     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
788              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
789       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
790                               NV, UB, "lsplit.c", PHTerminator);
791       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
792     }
793     break;
794   case ICmpInst::ICMP_ULT:
795   case ICmpInst::ICMP_SLT:
796     // for (i = LB; i < UB; ++i)
797     //   if (i < NV && ...)
798     //      LOOP_BODY
799     // 
800     // is transformed into
801     // NUB = min (NV, UB)
802     // for (i = LB; i < NUB ; ++i)
803     //   LOOP_BODY
804     //
805     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
806         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
807       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
808                               NV, UB, "lsplit.c", PHTerminator);
809       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
810     }
811
812     // for (i = LB; i <= UB; ++i)
813     //   if (i < NV && ...)
814     //      LOOP_BODY
815     // 
816     // is transformed into
817     // NUB = min (NV -1 , UB)
818     // for (i = LB; i <= NUB ; ++i)
819     //   LOOP_BODY
820     //
821     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
822              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
823       Value *S = BinaryOperator::createSub(NV, ConstantInt::get(Ty, 1, Sign),
824                                            "lsplit.add", PHTerminator);
825       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
826                               S, UB, "lsplit.c", PHTerminator);
827       NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
828     }
829     break;
830   case ICmpInst::ICMP_UGE:
831   case ICmpInst::ICMP_SGE:
832     // for (i = LB; i (< or <=) UB; ++i)
833     //   if (i >= NV && ...)
834     //      LOOP_BODY
835     // 
836     // is transformed into
837     // NLB = max (NV, LB)
838     // for (i = NLB; i (< or <=) UB ; ++i)
839     //   LOOP_BODY
840     //
841     {
842       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
843                               NV, StartValue, "lsplit.c", PHTerminator);
844       NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
845     }
846     break;
847   case ICmpInst::ICMP_UGT:
848   case ICmpInst::ICMP_SGT:
849     // for (i = LB; i (< or <=) UB; ++i)
850     //   if (i > NV && ...)
851     //      LOOP_BODY
852     // 
853     // is transformed into
854     // NLB = max (NV+1, LB)
855     // for (i = NLB; i (< or <=) UB ; ++i)
856     //   LOOP_BODY
857     //
858     {
859       Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
860                                            "lsplit.add", PHTerminator);
861       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
862                               A, StartValue, "lsplit.c", PHTerminator);
863       NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
864     }
865     break;
866   default:
867     assert ( 0 && "Unexpected split condition predicate");
868   }
869
870   if (NLB) {
871     unsigned i = IndVar->getBasicBlockIndex(Preheader);
872     IndVar->setIncomingValue(i, NLB);
873   }
874
875   if (NUB) {
876     ExitCondition->setOperand(ExitValueNum, NUB);
877   }
878 }
879 /// updateLoopIterationSpace - Current loop body is covered by an AND
880 /// instruction whose operands compares induction variables with loop
881 /// invariants. If possible, hoist this check outside the loop by
882 /// updating appropriate start and end values for induction variable.
883 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
884   BasicBlock *Header = L->getHeader();
885   BasicBlock *ExitingBlock = ExitCondition->getParent();
886   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
887
888   ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
889   ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
890
891   if (Op0->getPredicate() == ICmpInst::ICMP_EQ 
892       || Op0->getPredicate() == ICmpInst::ICMP_NE
893       || Op0->getPredicate() == ICmpInst::ICMP_EQ 
894       || Op0->getPredicate() == ICmpInst::ICMP_NE)
895     return false;
896
897   // Check if SplitCondition dominates entire loop body
898   // or not.
899   
900   // If SplitCondition is not in loop header then this loop is not suitable
901   // for this transformation.
902   if (SD.SplitCondition->getParent() != Header)
903     return false;
904   
905   // If loop header includes loop variant instruction operands then
906   // this loop may not be eliminated.
907   Instruction *Terminator = Header->getTerminator();
908   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
909       BI != BE; ++BI) {
910     Instruction *I = BI;
911
912     // PHI Nodes are OK.
913     if (isa<PHINode>(I))
914       continue;
915
916     // SplitCondition itself is OK.
917     if (I == SD.SplitCondition)
918       continue;
919     if (I == Op0 || I == Op1)
920       continue;
921
922     // Induction variable is OK.
923     if (I == IndVar)
924       continue;
925
926     // Induction variable increment is OK.
927     if (I == IndVarIncrement)
928       continue;
929
930     // Terminator is also harmless.
931     if (I == Terminator)
932       continue;
933
934     // Otherwise we have a instruction that may not be safe.
935     return false;
936   }
937
938   // If Exiting block includes loop variant instructions then this
939   // loop may not be eliminated.
940   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
941     return false;
942   
943   // Verify that loop exiting block has only two predecessor, where one predecessor
944   // is split condition block. The other predecessor will become exiting block's
945   // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
946   // more then two predecessors. This requires extra work in updating dominator
947   // information.
948   BasicBlock *ExitingBBPred = NULL;
949   for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
950        PI != PE; ++PI) {
951     BasicBlock *BB = *PI;
952     if (SplitCondBlock == BB) 
953       continue;
954     if (ExitingBBPred)
955       return false;
956     else
957       ExitingBBPred = BB;
958   }
959   
960   // Update loop bounds to absorb Op0 check.
961   updateLoopBounds(Op0);
962   // Update loop bounds to absorb Op1 check.
963   updateLoopBounds(Op1);
964
965   // Update CFG
966
967   // Unconditionally connect split block to its remaining successor. 
968   BranchInst *SplitTerminator = 
969     cast<BranchInst>(SplitCondBlock->getTerminator());
970   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
971   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
972   if (Succ0 == ExitCondition->getParent())
973     SplitTerminator->setUnconditionalDest(Succ1);
974   else
975     SplitTerminator->setUnconditionalDest(Succ0);
976
977   // Remove split condition.
978   SD.SplitCondition->eraseFromParent();
979   if (Op0->use_begin() == Op0->use_end())
980     Op0->eraseFromParent();
981   if (Op1->use_begin() == Op1->use_end())
982     Op1->eraseFromParent();
983       
984   BranchInst *ExitInsn =
985     dyn_cast<BranchInst>(ExitingBlock->getTerminator());
986   assert (ExitInsn && "Unable to find suitable loop exit branch");
987   BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
988   if (L->contains(ExitBlock))
989     ExitBlock = ExitInsn->getSuccessor(0);
990
991   // Update domiantor info. Now, ExitingBlock has only one predecessor, 
992   // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
993   DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
994   
995   // If ExitingBlock is a member of loop BB's DF list then replace it with
996   // loop header and exit block.
997   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
998        I != E; ++I) {
999     BasicBlock *BB = *I;
1000     if (BB == Header || BB == ExitingBlock)
1001       continue;
1002     DominanceFrontier::iterator BBDF = DF->find(BB);
1003     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1004     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1005     while (DomSetI != DomSetE) {
1006       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1007       ++DomSetI;
1008       BasicBlock *DFBB = *CurrentItr;
1009       if (DFBB == ExitingBlock) {
1010         BBDF->second.erase(DFBB);
1011         BBDF->second.insert(Header);
1012         if (Header != ExitingBlock)
1013           BBDF->second.insert(ExitBlock);
1014       }
1015     }
1016   }
1017
1018   return true;
1019 }
1020
1021
1022 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1023 /// This routine is used to remove split condition's dead branch, dominated by
1024 /// DeadBB. LiveBB dominates split conidition's other branch.
1025 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
1026                                   BasicBlock *LiveBB) {
1027
1028   // First update DeadBB's dominance frontier. 
1029   SmallVector<BasicBlock *, 8> FrontierBBs;
1030   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1031   if (DeadBBDF != DF->end()) {
1032     SmallVector<BasicBlock *, 8> PredBlocks;
1033     
1034     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1035     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1036            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1037       BasicBlock *FrontierBB = *DeadBBSetI;
1038       FrontierBBs.push_back(FrontierBB);
1039
1040       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1041       PredBlocks.clear();
1042       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1043           PI != PE; ++PI) {
1044         BasicBlock *P = *PI;
1045         if (P == DeadBB || DT->dominates(DeadBB, P))
1046           PredBlocks.push_back(P);
1047       }
1048
1049       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1050           FBI != FBE; ++FBI) {
1051         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1052           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1053                 PE = PredBlocks.end(); PI != PE; ++PI) {
1054             BasicBlock *P = *PI;
1055             PN->removeIncomingValue(P);
1056           }
1057         }
1058         else
1059           break;
1060       }      
1061     }
1062   }
1063   
1064   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1065   SmallVector<BasicBlock *, 32> WorkList;
1066   DomTreeNode *DN = DT->getNode(DeadBB);
1067   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1068          E = df_end(DN); DI != E; ++DI) {
1069     BasicBlock *BB = DI->getBlock();
1070     WorkList.push_back(BB);
1071     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1072   }
1073
1074   while (!WorkList.empty()) {
1075     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1076     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
1077         BBI != BBE; ) {
1078       Instruction *I = BBI;
1079       ++BBI;
1080       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1081       I->eraseFromParent();
1082     }
1083     LPM->deleteSimpleAnalysisValue(BB, LP);
1084     DT->eraseNode(BB);
1085     DF->removeBlock(BB);
1086     LI->removeBlock(BB);
1087     BB->eraseFromParent();
1088   }
1089
1090   // Update Frontier BBs' dominator info.
1091   while (!FrontierBBs.empty()) {
1092     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1093     BasicBlock *NewDominator = FBB->getSinglePredecessor();
1094     if (!NewDominator) {
1095       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1096       NewDominator = *PI;
1097       ++PI;
1098       if (NewDominator != LiveBB) {
1099         for(; PI != PE; ++PI) {
1100           BasicBlock *P = *PI;
1101           if (P == LiveBB) {
1102             NewDominator = LiveBB;
1103             break;
1104           }
1105           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1106         }
1107       }
1108     }
1109     assert (NewDominator && "Unable to fix dominator info.");
1110     DT->changeImmediateDominator(FBB, NewDominator);
1111     DF->changeImmediateDominator(FBB, NewDominator, DT);
1112   }
1113
1114 }
1115
1116 /// safeSplitCondition - Return true if it is possible to
1117 /// split loop using given split condition.
1118 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1119
1120   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1121   BasicBlock *Latch = L->getLoopLatch();  
1122   BranchInst *SplitTerminator = 
1123     cast<BranchInst>(SplitCondBlock->getTerminator());
1124   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1125   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1126
1127   // If split block does not dominate the latch then this is not a diamond.
1128   // Such loop may not benefit from index split.
1129   if (!DT->dominates(SplitCondBlock, Latch))
1130     return false;
1131
1132   // Finally this split condition is safe only if merge point for
1133   // split condition branch is loop latch. This check along with previous
1134   // check, to ensure that exit condition is in either loop latch or header,
1135   // filters all loops with non-empty loop body between merge point
1136   // and exit condition.
1137   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1138   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1139   if (Succ0DF->second.count(Latch))
1140     return true;
1141
1142   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1143   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1144   if (Succ1DF->second.count(Latch))
1145     return true;
1146   
1147   return false;
1148 }
1149
1150 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1151 /// based on split value. 
1152 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1153
1154   ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1155   ICmpInst::Predicate SP = SC->getPredicate();
1156   const Type *Ty = SD.SplitValue->getType();
1157   bool Sign = ExitCondition->isSignedPredicate();
1158   BasicBlock *Preheader = L->getLoopPreheader();
1159   Instruction *PHTerminator = Preheader->getTerminator();
1160
1161   // Initially use split value as upper loop bound for first loop and lower loop
1162   // bound for second loop.
1163   Value *AEV = SD.SplitValue;
1164   Value *BSV = SD.SplitValue;
1165
1166   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1167       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1168       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1169       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1170     ExitCondition->swapOperands();
1171     if (ExitValueNum)
1172       ExitValueNum = 0;
1173     else
1174       ExitValueNum = 1;
1175   }
1176
1177   switch (ExitCondition->getPredicate()) {
1178   case ICmpInst::ICMP_SGT:
1179   case ICmpInst::ICMP_UGT:
1180   case ICmpInst::ICMP_SGE:
1181   case ICmpInst::ICMP_UGE:
1182   default:
1183     assert (0 && "Unexpected exit condition predicate");
1184
1185   case ICmpInst::ICMP_SLT:
1186   case ICmpInst::ICMP_ULT:
1187     {
1188       switch (SP) {
1189       case ICmpInst::ICMP_SLT:
1190       case ICmpInst::ICMP_ULT:
1191         //
1192         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1193         //
1194         // is transformed into
1195         // AEV = BSV = SV
1196         // for (i = LB; i < min(UB, AEV); ++i)
1197         //    A;
1198         // for (i = max(LB, BSV); i < UB; ++i);
1199         //    B;
1200         break;
1201       case ICmpInst::ICMP_SLE:
1202       case ICmpInst::ICMP_ULE:
1203         {
1204           //
1205           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1206           //
1207           // is transformed into
1208           //
1209           // AEV = SV + 1
1210           // BSV = SV + 1
1211           // for (i = LB; i < min(UB, AEV); ++i) 
1212           //       A;
1213           // for (i = max(LB, BSV); i < UB; ++i) 
1214           //       B;
1215           BSV = BinaryOperator::createAdd(SD.SplitValue,
1216                                           ConstantInt::get(Ty, 1, Sign),
1217                                           "lsplit.add", PHTerminator);
1218           AEV = BSV;
1219         }
1220         break;
1221       case ICmpInst::ICMP_SGE:
1222       case ICmpInst::ICMP_UGE: 
1223         //
1224         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1225         // 
1226         // is transformed into
1227         // AEV = BSV = SV
1228         // for (i = LB; i < min(UB, AEV); ++i)
1229         //    B;
1230         // for (i = max(BSV, LB); i < UB; ++i)
1231         //    A;
1232         break;
1233       case ICmpInst::ICMP_SGT:
1234       case ICmpInst::ICMP_UGT: 
1235         {
1236           //
1237           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1238           //
1239           // is transformed into
1240           //
1241           // BSV = AEV = SV + 1
1242           // for (i = LB; i < min(UB, AEV); ++i) 
1243           //       B;
1244           // for (i = max(LB, BSV); i < UB; ++i) 
1245           //       A;
1246           BSV = BinaryOperator::createAdd(SD.SplitValue,
1247                                           ConstantInt::get(Ty, 1, Sign),
1248                                           "lsplit.add", PHTerminator);
1249           AEV = BSV;
1250         }
1251         break;
1252       default:
1253         assert (0 && "Unexpected split condition predicate");
1254         break;
1255       } // end switch (SP)
1256     }
1257     break;
1258   case ICmpInst::ICMP_SLE:
1259   case ICmpInst::ICMP_ULE:
1260     {
1261       switch (SP) {
1262       case ICmpInst::ICMP_SLT:
1263       case ICmpInst::ICMP_ULT:
1264         //
1265         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1266         //
1267         // is transformed into
1268         // AEV = SV - 1;
1269         // BSV = SV;
1270         // for (i = LB; i <= min(UB, AEV); ++i) 
1271         //       A;
1272         // for (i = max(LB, BSV); i <= UB; ++i) 
1273         //       B;
1274         AEV = BinaryOperator::createSub(SD.SplitValue,
1275                                         ConstantInt::get(Ty, 1, Sign),
1276                                         "lsplit.sub", PHTerminator);
1277         break;
1278       case ICmpInst::ICMP_SLE:
1279       case ICmpInst::ICMP_ULE:
1280         //
1281         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1282         //
1283         // is transformed into
1284         // AEV = SV;
1285         // BSV = SV + 1;
1286         // for (i = LB; i <= min(UB, AEV); ++i) 
1287         //       A;
1288         // for (i = max(LB, BSV); i <= UB; ++i) 
1289         //       B;
1290         BSV = BinaryOperator::createAdd(SD.SplitValue,
1291                                         ConstantInt::get(Ty, 1, Sign),
1292                                         "lsplit.add", PHTerminator);
1293         break;
1294       case ICmpInst::ICMP_SGT:
1295       case ICmpInst::ICMP_UGT: 
1296         //
1297         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1298         //
1299         // is transformed into
1300         // AEV = SV;
1301         // BSV = SV + 1;
1302         // for (i = LB; i <= min(AEV, UB); ++i)
1303         //      B;
1304         // for (i = max(LB, BSV); i <= UB; ++i)
1305         //      A;
1306         BSV = BinaryOperator::createAdd(SD.SplitValue,
1307                                         ConstantInt::get(Ty, 1, Sign),
1308                                         "lsplit.add", PHTerminator);
1309         break;
1310       case ICmpInst::ICMP_SGE:
1311       case ICmpInst::ICMP_UGE: 
1312         // ** TODO **
1313         //
1314         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1315         //
1316         // is transformed into
1317         // AEV = SV - 1;
1318         // BSV = SV;
1319         // for (i = LB; i <= min(AEV, UB); ++i)
1320         //      B;
1321         // for (i = max(LB, BSV); i <= UB; ++i)
1322         //      A;
1323         AEV = BinaryOperator::createSub(SD.SplitValue,
1324                                         ConstantInt::get(Ty, 1, Sign),
1325                                         "lsplit.sub", PHTerminator);
1326         break;
1327       default:
1328         assert (0 && "Unexpected split condition predicate");
1329         break;
1330       } // end switch (SP)
1331     }
1332     break;
1333   }
1334
1335   // Calculate ALoop induction variable's new exiting value and
1336   // BLoop induction variable's new starting value. Calculuate these
1337   // values in original loop's preheader.
1338   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1339   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
1340   Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1341
1342   // If ExitValue operand is also defined in Loop header then
1343   // insert new ExitValue after this operand definition.
1344   if (Instruction *EVN = 
1345       dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1346     if (!isa<PHINode>(EVN))
1347       if (InsertPt->getParent() == EVN->getParent()) {
1348         BasicBlock::iterator LHBI = L->getHeader()->begin();
1349         BasicBlock::iterator LHBE = L->getHeader()->end();  
1350         for(;LHBI != LHBE; ++LHBI) {
1351           Instruction *I = LHBI;
1352           if (I == EVN) 
1353             break;
1354         }
1355         InsertPt = ++LHBI;
1356       }
1357   }
1358   Value *C1 = new ICmpInst(Sign ?
1359                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1360                            AEV,
1361                            ExitCondition->getOperand(ExitValueNum), 
1362                            "lsplit.ev", InsertPt);
1363
1364   SD.A_ExitValue = SelectInst::Create(C1, AEV,
1365                                       ExitCondition->getOperand(ExitValueNum), 
1366                                       "lsplit.ev", InsertPt);
1367
1368   Value *C2 = new ICmpInst(Sign ?
1369                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1370                            BSV, StartValue, "lsplit.sv",
1371                            PHTerminator);
1372   SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1373                                        "lsplit.sv", PHTerminator);
1374 }
1375
1376 /// splitLoop - Split current loop L in two loops using split information
1377 /// SD. Update dominator information. Maintain LCSSA form.
1378 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1379
1380   if (!safeSplitCondition(SD))
1381     return false;
1382
1383   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1384   
1385   // Unable to handle triange loops at the moment.
1386   // In triangle loop, split condition is in header and one of the
1387   // the split destination is loop latch. If split condition is EQ
1388   // then such loops are already handle in processOneIterationLoop().
1389   BasicBlock *Latch = L->getLoopLatch();
1390   BranchInst *SplitTerminator = 
1391     cast<BranchInst>(SplitCondBlock->getTerminator());
1392   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1393   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1394   if (L->getHeader() == SplitCondBlock 
1395       && (Latch == Succ0 || Latch == Succ1))
1396     return false;
1397
1398   // If split condition branches heads do not have single predecessor, 
1399   // SplitCondBlock, then is not possible to remove inactive branch.
1400   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1401     return false;
1402
1403   // If Exiting block includes loop variant instructions then this
1404   // loop may not be split safely.
1405   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
1406     return false;
1407
1408   // After loop is cloned there are two loops.
1409   //
1410   // First loop, referred as ALoop, executes first part of loop's iteration
1411   // space split.  Second loop, referred as BLoop, executes remaining
1412   // part of loop's iteration space. 
1413   //
1414   // ALoop's exit edge enters BLoop's header through a forwarding block which 
1415   // acts as a BLoop's preheader.
1416   BasicBlock *Preheader = L->getLoopPreheader();
1417
1418   // Calculate ALoop induction variable's new exiting value and
1419   // BLoop induction variable's new starting value.
1420   calculateLoopBounds(SD);
1421
1422   //[*] Clone loop.
1423   DenseMap<const Value *, Value *> ValueMap;
1424   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1425   Loop *ALoop = L;
1426   BasicBlock *B_Header = BLoop->getHeader();
1427
1428   //[*] ALoop's exiting edge BLoop's header.
1429   //    ALoop's original exit block becomes BLoop's exit block.
1430   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1431   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1432   BranchInst *A_ExitInsn =
1433     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1434   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1435   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1436   if (L->contains(B_ExitBlock)) {
1437     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1438     A_ExitInsn->setSuccessor(0, B_Header);
1439   } else
1440     A_ExitInsn->setSuccessor(1, B_Header);
1441
1442   //[*] Update ALoop's exit value using new exit value.
1443   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1444   
1445   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1446   //     original loop's preheader. Add incoming PHINode values from
1447   //     ALoop's exiting block. Update BLoop header's domiantor info.
1448
1449   // Collect inverse map of Header PHINodes.
1450   DenseMap<Value *, Value *> InverseMap;
1451   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1452          BE = L->getHeader()->end(); BI != BE; ++BI) {
1453     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1454       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1455       InverseMap[PNClone] = PN;
1456     } else
1457       break;
1458   }
1459
1460   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1461        BI != BE; ++BI) {
1462     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1463       // Remove incoming value from original preheader.
1464       PN->removeIncomingValue(Preheader);
1465
1466       // Add incoming value from A_ExitingBlock.
1467       if (PN == B_IndVar)
1468         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1469       else { 
1470         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1471         Value *V2 = NULL;
1472         // If loop header is also loop exiting block then
1473         // OrigPN is incoming value for B loop header.
1474         if (A_ExitingBlock == L->getHeader())
1475           V2 = OrigPN;
1476         else
1477           V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1478         PN->addIncoming(V2, A_ExitingBlock);
1479       }
1480     } else
1481       break;
1482   }
1483   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1484   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1485   
1486   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1487   //     block. Remove incoming PHINode values from ALoop's exiting block.
1488   //     Add new incoming values from BLoop's incoming exiting value.
1489   //     Update BLoop exit block's dominator info..
1490   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1491   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1492        BI != BE; ++BI) {
1493     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1494       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1495                                                             B_ExitingBlock);
1496       PN->removeIncomingValue(A_ExitingBlock);
1497     } else
1498       break;
1499   }
1500
1501   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1502   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1503
1504   //[*] Split ALoop's exit edge. This creates a new block which
1505   //    serves two purposes. First one is to hold PHINode defnitions
1506   //    to ensure that ALoop's LCSSA form. Second use it to act
1507   //    as a preheader for BLoop.
1508   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1509
1510   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1511   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1512   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1513       BI != BE; ++BI) {
1514     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1515       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1516       PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1517       newPHI->addIncoming(V1, A_ExitingBlock);
1518       A_ExitBlock->getInstList().push_front(newPHI);
1519       PN->removeIncomingValue(A_ExitBlock);
1520       PN->addIncoming(newPHI, A_ExitBlock);
1521     } else
1522       break;
1523   }
1524
1525   //[*] Eliminate split condition's inactive branch from ALoop.
1526   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1527   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1528   BasicBlock *A_InactiveBranch = NULL;
1529   BasicBlock *A_ActiveBranch = NULL;
1530   if (SD.UseTrueBranchFirst) {
1531     A_ActiveBranch = A_BR->getSuccessor(0);
1532     A_InactiveBranch = A_BR->getSuccessor(1);
1533   } else {
1534     A_ActiveBranch = A_BR->getSuccessor(1);
1535     A_InactiveBranch = A_BR->getSuccessor(0);
1536   }
1537   A_BR->setUnconditionalDest(A_ActiveBranch);
1538   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1539
1540   //[*] Eliminate split condition's inactive branch in from BLoop.
1541   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1542   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1543   BasicBlock *B_InactiveBranch = NULL;
1544   BasicBlock *B_ActiveBranch = NULL;
1545   if (SD.UseTrueBranchFirst) {
1546     B_ActiveBranch = B_BR->getSuccessor(1);
1547     B_InactiveBranch = B_BR->getSuccessor(0);
1548   } else {
1549     B_ActiveBranch = B_BR->getSuccessor(0);
1550     B_InactiveBranch = B_BR->getSuccessor(1);
1551   }
1552   B_BR->setUnconditionalDest(B_ActiveBranch);
1553   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1554
1555   BasicBlock *A_Header = L->getHeader();
1556   if (A_ExitingBlock == A_Header)
1557     return true;
1558
1559   //[*] Move exit condition into split condition block to avoid
1560   //    executing dead loop iteration.
1561   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1562   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1563   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1564
1565   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1566                     cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement, 
1567                     ALoop);
1568
1569   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1570                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1571
1572   return true;
1573 }
1574
1575 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1576 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1577                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1578                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1579
1580   BasicBlock *ExitingBB = EC->getParent();
1581   Instruction *CurrentBR = CondBB->getTerminator();
1582
1583   // Move exit condition into split condition block.
1584   EC->moveBefore(CurrentBR);
1585   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1586
1587   // Move exiting block's branch into split condition block. Update its branch
1588   // destination.
1589   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1590   ExitingBR->moveBefore(CurrentBR);
1591   BasicBlock *OrigDestBB = NULL;
1592   if (ExitingBR->getSuccessor(0) == ExitBB) {
1593     OrigDestBB = ExitingBR->getSuccessor(1);
1594     ExitingBR->setSuccessor(1, ActiveBB);
1595   }
1596   else {
1597     OrigDestBB = ExitingBR->getSuccessor(0);
1598     ExitingBR->setSuccessor(0, ActiveBB);
1599   }
1600     
1601   // Remove split condition and current split condition branch.
1602   SC->eraseFromParent();
1603   CurrentBR->eraseFromParent();
1604
1605   // Connect exiting block to original destination.
1606   BranchInst::Create(OrigDestBB, ExitingBB);
1607
1608   // Update PHINodes
1609   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1610
1611   // Fix dominator info.
1612   // ExitBB is now dominated by CondBB
1613   DT->changeImmediateDominator(ExitBB, CondBB);
1614   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1615   
1616   // Basicblocks dominated by ActiveBB may have ExitingBB or
1617   // a basic block outside the loop in their DF list. If so,
1618   // replace it with CondBB.
1619   DomTreeNode *Node = DT->getNode(ActiveBB);
1620   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1621        DI != DE; ++DI) {
1622     BasicBlock *BB = DI->getBlock();
1623     DominanceFrontier::iterator BBDF = DF->find(BB);
1624     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1625     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1626     while (DomSetI != DomSetE) {
1627       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1628       ++DomSetI;
1629       BasicBlock *DFBB = *CurrentItr;
1630       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1631         BBDF->second.erase(DFBB);
1632         BBDF->second.insert(CondBB);
1633       }
1634     }
1635   }
1636 }
1637
1638 /// updatePHINodes - CFG has been changed. 
1639 /// Before 
1640 ///   - ExitBB's single predecessor was Latch
1641 ///   - Latch's second successor was Header
1642 /// Now
1643 ///   - ExitBB's single predecessor is Header
1644 ///   - Latch's one and only successor is Header
1645 ///
1646 /// Update ExitBB PHINodes' to reflect this change.
1647 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1648                                     BasicBlock *Header,
1649                                     PHINode *IV, Instruction *IVIncrement,
1650                                     Loop *LP) {
1651
1652   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1653        BI != BE; ) {
1654     PHINode *PN = dyn_cast<PHINode>(BI);
1655     ++BI;
1656     if (!PN)
1657       break;
1658
1659     Value *V = PN->getIncomingValueForBlock(Latch);
1660     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1661       // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1662       // in Header which is new incoming value for PN.
1663       Value *NewV = NULL;
1664       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1665            UI != E; ++UI) 
1666         if (PHINode *U = dyn_cast<PHINode>(*UI)) 
1667           if (LP->contains(U->getParent())) {
1668             NewV = U;
1669             break;
1670           }
1671
1672       // Add incoming value from header only if PN has any use inside the loop.
1673       if (NewV)
1674         PN->addIncoming(NewV, Header);
1675
1676     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1677       // If this instruction is IVIncrement then IV is new incoming value 
1678       // from header otherwise this instruction must be incoming value from 
1679       // header because loop is in LCSSA form.
1680       if (PHI == IVIncrement)
1681         PN->addIncoming(IV, Header);
1682       else
1683         PN->addIncoming(V, Header);
1684     } else
1685       // Otherwise this is an incoming value from header because loop is in 
1686       // LCSSA form.
1687       PN->addIncoming(V, Header);
1688     
1689     // Remove incoming value from Latch.
1690     PN->removeIncomingValue(Latch);
1691   }
1692 }