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