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