blob: 6a2c7587f6e02f1e99b8c65206716a071533a7d9 [file] [log] [blame]
Devang Patelfee76bd2007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelfee76bd2007-08-07 00:25:56 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelfee76bd2007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel787a7132007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000024#include "llvm/ADT/Statistic.h"
25
26using namespace llvm;
27
28STATISTIC(NumIndexSplit, "Number of loops index split");
29
30namespace {
31
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34 public:
35 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000036 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000037
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);
Devang Patel423c8b22007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patel71554b82007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel4259fe32007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Patel4a69da92007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patelc9d123d2007-08-09 01:39:01 +000063
Devang Patel71554b82007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patel4f12c5f2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patel71554b82007-08-08 21:02:17 +000069
Devang Patel4259fe32007-08-24 06:17:19 +000070 // True if after loop index split, first loop will execute split condition's
71 // true branch.
72 bool UseTrueBranchFirst;
Devang Patel4a69da92007-08-25 00:56:38 +000073
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
Devang Patel9021c702007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel9021c702007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel4259fe32007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Patel4a69da92007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000087 }
Devang Patelc9d123d2007-08-09 01:39:01 +000088
Devang Patel71554b82007-08-08 21:02:17 +000089 };
Devang Patelbacf5192007-08-10 00:33:50 +000090
Devang Patel71554b82007-08-08 21:02:17 +000091 private:
Devang Pateld35ed2c2007-09-11 00:42:56 +000092
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
Devang Patelfee76bd2007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patelbacf5192007-08-10 00:33:50 +0000102 /// 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
Devang Patelfee76bd2007-08-07 00:25:56 +0000108 /// 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
Devang Patel423c8b22007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patel00622952008-09-17 17:53:47 +0000114
115 /// isOneIterationLoop - Return true if split condition is EQ and
116 /// the IV is not used outside the loop.
117 bool isOneIterationLoop(ICmpInst *CI);
Devang Patel5279d062007-09-17 20:39:48 +0000118
119 void updateLoopBounds(ICmpInst *CI);
120 /// updateLoopIterationSpace - Current loop body is covered by an AND
121 /// instruction whose operands compares induction variables with loop
122 /// invariants. If possible, hoist this check outside the loop by
123 /// updating appropriate start and end values for induction variable.
124 bool updateLoopIterationSpace(SplitInfo &SD);
125
Devang Patel9704fcf2007-08-08 22:25:28 +0000126 /// If loop header includes loop variant instruction operands then
127 /// this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000128 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000129
Devang Patel1cc2ec82007-08-20 23:51:18 +0000130 /// If Exiting block includes loop variant instructions then this
Devang Patel9704fcf2007-08-08 22:25:28 +0000131 /// loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000132 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000133
Devang Patela6a86632007-08-14 18:35:57 +0000134 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
135 /// This routine is used to remove split condition's dead branch, dominated by
136 /// DeadBB. LiveBB dominates split conidition's other branch.
137 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel98147a32007-08-12 07:02:51 +0000138
Devang Pateldc523952007-08-22 18:27:01 +0000139 /// safeSplitCondition - Return true if it is possible to
140 /// split loop using given split condition.
141 bool safeSplitCondition(SplitInfo &SD);
142
Devang Patel4a69da92007-08-25 00:56:38 +0000143 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
144 /// based on split value.
145 void calculateLoopBounds(SplitInfo &SD);
146
Devang Pateld79faee2007-08-25 02:39:24 +0000147 /// updatePHINodes - CFG has been changed.
148 /// Before
149 /// - ExitBB's single predecessor was Latch
150 /// - Latch's second successor was Header
151 /// Now
152 /// - ExitBB's single predecessor was Header
153 /// - Latch's one and only successor was Header
154 ///
155 /// Update ExitBB PHINodes' to reflect this change.
156 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
157 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000158 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000159
160 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
161 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
162 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
163 PHINode *IV, Instruction *IVAdd, Loop *LP);
164
Devang Pateldc523952007-08-22 18:27:01 +0000165 /// splitLoop - Split current loop L in two loops using split information
166 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patel71554b82007-08-08 21:02:17 +0000167 bool splitLoop(SplitInfo &SD);
Devang Patelfee76bd2007-08-07 00:25:56 +0000168
Devang Patelbacf5192007-08-10 00:33:50 +0000169 void initialize() {
170 IndVar = NULL;
171 IndVarIncrement = NULL;
172 ExitCondition = NULL;
Devang Patel98147a32007-08-12 07:02:51 +0000173 StartValue = NULL;
174 ExitValueNum = 0;
175 SplitData.clear();
Devang Patelbacf5192007-08-10 00:33:50 +0000176 }
177
Devang Patelfee76bd2007-08-07 00:25:56 +0000178 private:
179
180 // Current Loop.
181 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000182 LPPassManager *LPM;
183 LoopInfo *LI;
Devang Patelfee76bd2007-08-07 00:25:56 +0000184 ScalarEvolution *SE;
Devang Patel9704fcf2007-08-08 22:25:28 +0000185 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000186 DominanceFrontier *DF;
Devang Patel71554b82007-08-08 21:02:17 +0000187 SmallVector<SplitInfo, 4> SplitData;
Devang Patelbacf5192007-08-10 00:33:50 +0000188
189 // Induction variable whose range is being split by this transformation.
190 PHINode *IndVar;
191 Instruction *IndVarIncrement;
192
193 // Loop exit condition.
194 ICmpInst *ExitCondition;
195
196 // Induction variable's initial value.
197 Value *StartValue;
198
Devang Patel98147a32007-08-12 07:02:51 +0000199 // Induction variable's final loop exit value operand number in exit condition..
200 unsigned ExitValueNum;
Devang Patelfee76bd2007-08-07 00:25:56 +0000201 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000202}
203
Dan Gohman844731a2008-05-13 00:00:25 +0000204char LoopIndexSplit::ID = 0;
205static RegisterPass<LoopIndexSplit>
206X("loop-index-split", "Index Split Loops");
207
Devang Patelfee76bd2007-08-07 00:25:56 +0000208LoopPass *llvm::createLoopIndexSplitPass() {
209 return new LoopIndexSplit();
210}
211
212// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000213bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000214 bool Changed = false;
215 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000216 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000217
Devang Patel3fe4f212007-08-15 02:14:55 +0000218 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000219 if (!L->getSubLoops().empty())
220 return false;
221
Devang Patelfee76bd2007-08-07 00:25:56 +0000222 SE = &getAnalysis<ScalarEvolution>();
Devang Patel9704fcf2007-08-08 22:25:28 +0000223 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000224 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000225 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000226
Devang Patelbacf5192007-08-10 00:33:50 +0000227 initialize();
228
229 findLoopConditionals();
230
231 if (!ExitCondition)
232 return false;
233
Devang Patelfee76bd2007-08-07 00:25:56 +0000234 findSplitCondition();
235
Devang Patel71554b82007-08-08 21:02:17 +0000236 if (SplitData.empty())
Devang Patelfee76bd2007-08-07 00:25:56 +0000237 return false;
238
Devang Patel71554b82007-08-08 21:02:17 +0000239 // First see if it is possible to eliminate loop itself or not.
David Greenea022e3f2008-04-02 18:24:46 +0000240 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
241 SI != SplitData.end();) {
Devang Patel71554b82007-08-08 21:02:17 +0000242 SplitInfo &SD = *SI;
Devang Patel4f12c5f2007-09-11 00:12:56 +0000243 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
Devang Patel5279d062007-09-17 20:39:48 +0000244 if (SD.SplitCondition->getOpcode() == Instruction::And) {
245 Changed = updateLoopIterationSpace(SD);
246 if (Changed) {
247 ++NumIndexSplit;
248 // If is loop is eliminated then nothing else to do here.
249 return Changed;
250 } else {
251 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000252 SI = SplitData.erase(Delete_SI);
Devang Patel5279d062007-09-17 20:39:48 +0000253 }
254 }
Devang Patel00622952008-09-17 17:53:47 +0000255 else if (isOneIterationLoop(CI)) {
Devang Patel423c8b22007-08-10 18:07:13 +0000256 Changed = processOneIterationLoop(SD);
Devang Patel71554b82007-08-08 21:02:17 +0000257 if (Changed) {
258 ++NumIndexSplit;
259 // If is loop is eliminated then nothing else to do here.
260 return Changed;
Devang Pateld651f652007-08-20 20:24:15 +0000261 } else {
262 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000263 SI = SplitData.erase(Delete_SI);
Devang Patel71554b82007-08-08 21:02:17 +0000264 }
Devang Pateld651f652007-08-20 20:24:15 +0000265 } else
266 ++SI;
Devang Patel71554b82007-08-08 21:02:17 +0000267 }
268
Devang Patel4259fe32007-08-24 06:17:19 +0000269 if (SplitData.empty())
270 return false;
271
Devang Patel9704fcf2007-08-08 22:25:28 +0000272 // Split most profitiable condition.
Devang Patel7237d112007-08-24 05:21:13 +0000273 // FIXME : Implement cost analysis.
274 unsigned MostProfitableSDIndex = 0;
275 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel9704fcf2007-08-08 22:25:28 +0000276
Devang Patelfee76bd2007-08-07 00:25:56 +0000277 if (Changed)
278 ++NumIndexSplit;
Devang Patel71554b82007-08-08 21:02:17 +0000279
Devang Patelfee76bd2007-08-07 00:25:56 +0000280 return Changed;
281}
282
Devang Patel00622952008-09-17 17:53:47 +0000283/// isOneIterationLoop - Return true if split condition is EQ and
284/// the IV is not used outside the loop.
285bool LoopIndexSplit::isOneIterationLoop(ICmpInst *CI) {
286 if (!CI)
287 return false;
288 if (CI->getPredicate() != ICmpInst::ICMP_EQ)
289 return false;
290
291 Value *Incr = IndVar->getIncomingValueForBlock(L->getLoopLatch());
292 for (Value::use_iterator UI = Incr->use_begin(), E = Incr->use_end();
293 UI != E; ++UI)
294 if (!L->contains(cast<Instruction>(*UI)->getParent()))
295 return false;
296
297 return true;
298}
Devang Patelc9d123d2007-08-09 01:39:01 +0000299/// Return true if V is a induction variable or induction variable's
300/// increment for loop L.
Devang Patelbacf5192007-08-10 00:33:50 +0000301void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000302
303 Instruction *I = dyn_cast<Instruction>(V);
304 if (!I)
Devang Patelbacf5192007-08-10 00:33:50 +0000305 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000306
307 // Check if I is a phi node from loop header or not.
308 if (PHINode *PN = dyn_cast<PHINode>(V)) {
309 if (PN->getParent() == L->getHeader()) {
Devang Patelbacf5192007-08-10 00:33:50 +0000310 IndVar = PN;
311 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000312 }
313 }
314
315 // Check if I is a add instruction whose one operand is
316 // phi node from loop header and second operand is constant.
317 if (I->getOpcode() != Instruction::Add)
Devang Patelbacf5192007-08-10 00:33:50 +0000318 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000319
320 Value *Op0 = I->getOperand(0);
321 Value *Op1 = I->getOperand(1);
322
Devang Patelc840da12008-01-29 02:20:41 +0000323 if (PHINode *PN = dyn_cast<PHINode>(Op0))
324 if (PN->getParent() == L->getHeader())
325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
326 if (CI->isOne()) {
327 IndVar = PN;
328 IndVarIncrement = I;
329 return;
330 }
331
332 if (PHINode *PN = dyn_cast<PHINode>(Op1))
333 if (PN->getParent() == L->getHeader())
334 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
335 if (CI->isOne()) {
336 IndVar = PN;
337 IndVarIncrement = I;
338 return;
339 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000340
Devang Patelbacf5192007-08-10 00:33:50 +0000341 return;
342}
343
344// Find loop's exit condition and associated induction variable.
345void LoopIndexSplit::findLoopConditionals() {
346
Devang Patel1cc2ec82007-08-20 23:51:18 +0000347 BasicBlock *ExitingBlock = NULL;
Devang Patelbacf5192007-08-10 00:33:50 +0000348
349 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
350 I != E; ++I) {
351 BasicBlock *BB = *I;
352 if (!L->isLoopExit(BB))
353 continue;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000354 if (ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000355 return;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000356 ExitingBlock = BB;
Devang Patelbacf5192007-08-10 00:33:50 +0000357 }
358
Devang Patel1cc2ec82007-08-20 23:51:18 +0000359 if (!ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000360 return;
Devang Patelb88e4202007-08-24 05:36:56 +0000361
362 // If exiting block is neither loop header nor loop latch then this loop is
363 // not suitable.
364 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
365 return;
366
Devang Patelbacf5192007-08-10 00:33:50 +0000367 // If exit block's terminator is conditional branch inst then we have found
368 // exit condition.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000369 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patelbacf5192007-08-10 00:33:50 +0000370 if (!BR || BR->isUnconditional())
371 return;
372
373 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
374 if (!CI)
375 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000376
Bill Wendlingc6849102007-09-14 01:13:55 +0000377 // FIXME
Devang Patelbabbe272007-09-19 00:28:47 +0000378 if (CI->getPredicate() == ICmpInst::ICMP_EQ
Bill Wendlingc6849102007-09-14 01:13:55 +0000379 || CI->getPredicate() == ICmpInst::ICMP_NE)
380 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000381
Devang Patelbacf5192007-08-10 00:33:50 +0000382 ExitCondition = CI;
383
384 // Exit condition's one operand is loop invariant exit value and second
385 // operand is SCEVAddRecExpr based on induction variable.
386 Value *V0 = CI->getOperand(0);
387 Value *V1 = CI->getOperand(1);
388
389 SCEVHandle SH0 = SE->getSCEV(V0);
390 SCEVHandle SH1 = SE->getSCEV(V1);
391
392 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel98147a32007-08-12 07:02:51 +0000393 ExitValueNum = 0;
Devang Patelbacf5192007-08-10 00:33:50 +0000394 findIndVar(V1, L);
395 }
396 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel98147a32007-08-12 07:02:51 +0000397 ExitValueNum = 1;
Devang Patelbacf5192007-08-10 00:33:50 +0000398 findIndVar(V0, L);
399 }
400
Devang Patel98147a32007-08-12 07:02:51 +0000401 if (!IndVar)
Devang Patelbacf5192007-08-10 00:33:50 +0000402 ExitCondition = NULL;
403 else if (IndVar) {
404 BasicBlock *Preheader = L->getLoopPreheader();
405 StartValue = IndVar->getIncomingValueForBlock(Preheader);
406 }
Devang Patela5e27f82008-07-09 00:12:01 +0000407
408 // If start value is more then exit value where induction variable
409 // increments by 1 then we are potentially dealing with an infinite loop.
410 // Do not index split this loop.
411 if (ExitCondition) {
412 ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
413 ConstantInt *EV =
414 dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
415 if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
416 ExitCondition = NULL;
417 else if (EV && EV->isZero())
418 ExitCondition = NULL;
419 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000420}
421
Devang Patelfee76bd2007-08-07 00:25:56 +0000422/// Find condition inside a loop that is suitable candidate for index split.
423void LoopIndexSplit::findSplitCondition() {
424
Devang Patel71554b82007-08-08 21:02:17 +0000425 SplitInfo SD;
Devang Patelc9d123d2007-08-09 01:39:01 +0000426 // Check all basic block's terminators.
Devang Patelc9d123d2007-08-09 01:39:01 +0000427 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
428 I != E; ++I) {
Devang Patel964be452007-09-11 00:23:56 +0000429 SD.clear();
Devang Patelc9d123d2007-08-09 01:39:01 +0000430 BasicBlock *BB = *I;
Devang Patelfee76bd2007-08-07 00:25:56 +0000431
Devang Patelc9d123d2007-08-09 01:39:01 +0000432 // If this basic block does not terminate in a conditional branch
433 // then terminator is not a suitable split condition.
434 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
435 if (!BR)
436 continue;
437
438 if (BR->isUnconditional())
Devang Patelfee76bd2007-08-07 00:25:56 +0000439 continue;
440
Devang Patel5279d062007-09-17 20:39:48 +0000441 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
442 if (AndI->getOpcode() == Instruction::And) {
443 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
444 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
445
446 if (!Op0 || !Op1)
447 continue;
448
449 if (!safeICmpInst(Op0, SD))
450 continue;
451 SD.clear();
452 if (!safeICmpInst(Op1, SD))
453 continue;
454 SD.clear();
455 SD.SplitCondition = AndI;
456 SplitData.push_back(SD);
457 continue;
458 }
459 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000460 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patelbacf5192007-08-10 00:33:50 +0000461 if (!CI || CI == ExitCondition)
Devang Patelba32a5f2007-09-10 23:57:58 +0000462 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000463
Devang Patelc830aee2007-08-24 06:02:25 +0000464 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patelba32a5f2007-09-10 23:57:58 +0000465 continue;
Devang Patelc830aee2007-08-24 06:02:25 +0000466
Devang Patel4259fe32007-08-24 06:17:19 +0000467 // If split condition predicate is GT or GE then first execute
468 // false branch of split condition.
Devang Patelc3957d12007-09-11 01:10:45 +0000469 if (CI->getPredicate() == ICmpInst::ICMP_UGT
470 || CI->getPredicate() == ICmpInst::ICMP_SGT
471 || CI->getPredicate() == ICmpInst::ICMP_UGE
472 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel4259fe32007-08-24 06:17:19 +0000473 SD.UseTrueBranchFirst = false;
474
Devang Patelc9d123d2007-08-09 01:39:01 +0000475 // If one operand is loop invariant and second operand is SCEVAddRecExpr
476 // based on induction variable then CI is a candidate split condition.
Devang Pateld35ed2c2007-09-11 00:42:56 +0000477 if (safeICmpInst(CI, SD))
478 SplitData.push_back(SD);
479 }
480}
Devang Patelc9d123d2007-08-09 01:39:01 +0000481
Devang Pateld35ed2c2007-09-11 00:42:56 +0000482// safeIcmpInst - CI is considered safe instruction if one of the operand
483// is SCEVAddRecExpr based on induction variable and other operand is
484// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
485// and return true;
486bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000487
Devang Pateld35ed2c2007-09-11 00:42:56 +0000488 Value *V0 = CI->getOperand(0);
489 Value *V1 = CI->getOperand(1);
490
491 SCEVHandle SH0 = SE->getSCEV(V0);
492 SCEVHandle SH1 = SE->getSCEV(V1);
493
494 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
495 SD.SplitValue = V0;
496 SD.SplitCondition = CI;
497 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
498 if (PN == IndVar)
499 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000500 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000501 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
502 if (IndVarIncrement && IndVarIncrement == Insn)
503 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000504 }
505 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000506 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
507 SD.SplitValue = V1;
508 SD.SplitCondition = CI;
509 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
510 if (PN == IndVar)
511 return true;
512 }
513 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
514 if (IndVarIncrement && IndVarIncrement == Insn)
515 return true;
516 }
517 }
518
519 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000520}
521
522/// processOneIterationLoop - Current loop L contains compare instruction
523/// that compares induction variable, IndVar, against loop invariant. If
524/// entire (i.e. meaningful) loop body is dominated by this compare
525/// instruction then loop body is executed only once. In such case eliminate
526/// loop structure surrounding this loop body. For example,
527/// for (int i = start; i < end; ++i) {
528/// if ( i == somevalue) {
529/// loop_body
530/// }
531/// }
532/// can be transformed into
533/// if (somevalue >= start && somevalue < end) {
534/// i = somevalue;
535/// loop_body
536/// }
Devang Patel423c8b22007-08-10 18:07:13 +0000537bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000538
539 BasicBlock *Header = L->getHeader();
540
541 // First of all, check if SplitCondition dominates entire loop body
542 // or not.
543
544 // If SplitCondition is not in loop header then this loop is not suitable
545 // for this transformation.
Devang Patel71554b82007-08-08 21:02:17 +0000546 if (SD.SplitCondition->getParent() != Header)
Devang Patelfee76bd2007-08-07 00:25:56 +0000547 return false;
548
Devang Patelfee76bd2007-08-07 00:25:56 +0000549 // If loop header includes loop variant instruction operands then
550 // this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000551 if (!safeHeader(SD, Header))
Devang Patelfee76bd2007-08-07 00:25:56 +0000552 return false;
553
Devang Patel1cc2ec82007-08-20 23:51:18 +0000554 // If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000555 // loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000556 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelfee76bd2007-08-07 00:25:56 +0000557 return false;
558
Devang Patel968eee22007-09-19 00:15:16 +0000559 // Filter loops where split condition's false branch is not empty.
560 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
561 return false;
562
Devang Patel8893ca62007-09-17 21:01:05 +0000563 // If split condition is not safe then do not process this loop.
564 // For example,
565 // for(int i = 0; i < N; i++) {
566 // if ( i == XYZ) {
567 // A;
568 // else
569 // B;
570 // }
571 // C;
572 // D;
573 // }
574 if (!safeSplitCondition(SD))
575 return false;
576
Devang Patel84ef08b2007-09-19 00:11:01 +0000577 BasicBlock *Latch = L->getLoopLatch();
578 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
579 if (!BR)
580 return false;
581
Devang Patel6a2bfda2007-08-08 01:51:27 +0000582 // Update CFG.
583
Devang Patelebc5fea2007-08-20 20:49:01 +0000584 // Replace index variable with split value in loop body. Loop body is executed
585 // only when index variable is equal to split value.
586 IndVar->replaceAllUsesWith(SD.SplitValue);
587
Devang Patelfc19fbd2008-10-10 22:02:57 +0000588 Instruction *LTerminator = Latch->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000589 Instruction *Terminator = Header->getTerminator();
Devang Patelada054a2007-08-14 01:30:57 +0000590 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelfee76bd2007-08-07 00:25:56 +0000591
Devang Patelfee76bd2007-08-07 00:25:56 +0000592 // Replace split condition in header.
593 // Transform
594 // SplitCondition : icmp eq i32 IndVar, SplitValue
595 // into
596 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000597 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000598 // and i32 c1, c2
Devang Patelbacf5192007-08-10 00:33:50 +0000599 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelfc19fbd2008-10-10 22:02:57 +0000600 CmpInst::Predicate C2Predicate = ExitCondition->getPredicate();
601 if (LTerminator->getOperand(0) != Header)
602 C2Predicate = CmpInst::getInversePredicate(C2Predicate);
Devang Patelfee76bd2007-08-07 00:25:56 +0000603 Instruction *C1 = new ICmpInst(SignedPredicate ?
604 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel71554b82007-08-08 21:02:17 +0000605 SD.SplitValue, StartValue, "lisplit",
606 Terminator);
Devang Patelfc19fbd2008-10-10 22:02:57 +0000607 Instruction *C2 = new ICmpInst(C2Predicate,
Devang Patelada054a2007-08-14 01:30:57 +0000608 SD.SplitValue, ExitValue, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000609 Terminator);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000610 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000611 Terminator);
612 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
613 SD.SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000614
Devang Patelfc19fbd2008-10-10 22:02:57 +0000615 // Remove Latch to Header edge.
616 BasicBlock *LatchSucc = NULL;
617 Header->removePredecessor(Latch);
618 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
619 SI != E; ++SI) {
620 if (Header != *SI)
621 LatchSucc = *SI;
622 }
623 BR->setUnconditionalDest(LatchSucc);
624
Devang Patelfee76bd2007-08-07 00:25:56 +0000625 // Now, clear latch block. Remove instructions that are responsible
626 // to increment induction variable.
Devang Patelfee76bd2007-08-07 00:25:56 +0000627 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
628 LB != LE; ) {
629 Instruction *I = LB;
630 ++LB;
631 if (isa<PHINode>(I) || I == LTerminator)
632 continue;
633
Devang Patel52abbf52008-05-19 22:23:55 +0000634 if (I == IndVarIncrement) {
635 // Replace induction variable increment if it is not used outside
636 // the loop.
637 bool UsedOutsideLoop = false;
638 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
639 UI != E; ++UI) {
640 if (Instruction *Use = dyn_cast<Instruction>(UI))
641 if (!L->contains(Use->getParent())) {
642 UsedOutsideLoop = true;
643 break;
644 }
645 }
646 if (!UsedOutsideLoop) {
647 I->replaceAllUsesWith(ExitValue);
648 I->eraseFromParent();
649 }
650 }
651 else {
Devang Patelada054a2007-08-14 01:30:57 +0000652 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel52abbf52008-05-19 22:23:55 +0000653 I->eraseFromParent();
654 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000655 }
656
Devang Patel423c8b22007-08-10 18:07:13 +0000657 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000658
659 // Update Dominator Info.
660 // Only CFG change done is to remove Latch to Header edge. This
661 // does not change dominator tree because Latch did not dominate
662 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000663 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000664 DominanceFrontier::iterator HeaderDF = DF->find(Header);
665 if (HeaderDF != DF->end())
666 DF->removeFromFrontier(HeaderDF, Header);
667
668 DominanceFrontier::iterator LatchDF = DF->find(Latch);
669 if (LatchDF != DF->end())
670 DF->removeFromFrontier(LatchDF, Header);
671 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000672 return true;
673}
674
675// If loop header includes loop variant instruction operands then
676// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patel71554b82007-08-08 21:02:17 +0000677bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000678
679 Instruction *Terminator = Header->getTerminator();
680 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
681 BI != BE; ++BI) {
682 Instruction *I = BI;
683
Devang Patelada054a2007-08-14 01:30:57 +0000684 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000685 if (isa<PHINode>(I))
686 continue;
687
688 // SplitCondition itself is OK.
Devang Patel71554b82007-08-08 21:02:17 +0000689 if (I == SD.SplitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000690 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000691
Devang Patelc9d123d2007-08-09 01:39:01 +0000692 // Induction variable is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000693 if (I == IndVar)
Devang Patelc9d123d2007-08-09 01:39:01 +0000694 continue;
695
696 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000697 if (I == IndVarIncrement)
Devang Patelc9d123d2007-08-09 01:39:01 +0000698 continue;
699
Devang Patelfee76bd2007-08-07 00:25:56 +0000700 // Terminator is also harmless.
701 if (I == Terminator)
702 continue;
703
704 // Otherwise we have a instruction that may not be safe.
705 return false;
706 }
707
708 return true;
709}
710
Devang Patel1cc2ec82007-08-20 23:51:18 +0000711// If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000712// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel1cc2ec82007-08-20 23:51:18 +0000713bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
714 BasicBlock *ExitingBlock) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000715
Devang Patel1cc2ec82007-08-20 23:51:18 +0000716 for (BasicBlock::iterator BI = ExitingBlock->begin(),
717 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000718 Instruction *I = BI;
719
Devang Patelada054a2007-08-14 01:30:57 +0000720 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000721 if (isa<PHINode>(I))
722 continue;
723
Devang Patelc9d123d2007-08-09 01:39:01 +0000724 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000725 if (IndVarIncrement && IndVarIncrement == I)
Devang Patelc9d123d2007-08-09 01:39:01 +0000726 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000727
Devang Patelc9d123d2007-08-09 01:39:01 +0000728 // Check if I is induction variable increment instruction.
Devang Patela6dff2f2007-09-25 18:24:48 +0000729 if (I->getOpcode() == Instruction::Add) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000730
731 Value *Op0 = I->getOperand(0);
732 Value *Op1 = I->getOperand(1);
Devang Patelfee76bd2007-08-07 00:25:56 +0000733 PHINode *PN = NULL;
734 ConstantInt *CI = NULL;
735
736 if ((PN = dyn_cast<PHINode>(Op0))) {
737 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000738 if (CI->isOne()) {
739 if (!IndVarIncrement && PN == IndVar)
740 IndVarIncrement = I;
741 // else this is another loop induction variable
742 continue;
743 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000744 } else
745 if ((PN = dyn_cast<PHINode>(Op1))) {
746 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000747 if (CI->isOne()) {
748 if (!IndVarIncrement && PN == IndVar)
749 IndVarIncrement = I;
750 // else this is another loop induction variable
751 continue;
752 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000753 }
Devang Patela6dff2f2007-09-25 18:24:48 +0000754 }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000755
Devang Patelfee76bd2007-08-07 00:25:56 +0000756 // I is an Exit condition if next instruction is block terminator.
757 // Exit condition is OK if it compares loop invariant exit value,
758 // which is checked below.
Devang Patel002fe252007-08-07 23:17:52 +0000759 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbacf5192007-08-10 00:33:50 +0000760 if (EC == ExitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000761 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000762 }
763
Devang Patel1cc2ec82007-08-20 23:51:18 +0000764 if (I == ExitingBlock->getTerminator())
Devang Patelbacf5192007-08-10 00:33:50 +0000765 continue;
766
Devang Patelfee76bd2007-08-07 00:25:56 +0000767 // Otherwise we have instruction that may not be safe.
768 return false;
769 }
770
Devang Patel1cc2ec82007-08-20 23:51:18 +0000771 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelfee76bd2007-08-07 00:25:56 +0000772 return true;
773}
774
Devang Patel5279d062007-09-17 20:39:48 +0000775void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
776
777 Value *V0 = CI->getOperand(0);
778 Value *V1 = CI->getOperand(1);
779 Value *NV = NULL;
780
781 SCEVHandle SH0 = SE->getSCEV(V0);
782
783 if (SH0->isLoopInvariant(L))
784 NV = V0;
785 else
786 NV = V1;
787
Devang Patel453a8442007-09-25 17:31:19 +0000788 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
789 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
790 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
791 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
792 ExitCondition->swapOperands();
793 if (ExitValueNum)
794 ExitValueNum = 0;
795 else
796 ExitValueNum = 1;
797 }
798
799 Value *NUB = NULL;
800 Value *NLB = NULL;
801 Value *UB = ExitCondition->getOperand(ExitValueNum);
802 const Type *Ty = NV->getType();
803 bool Sign = ExitCondition->isSignedPredicate();
804 BasicBlock *Preheader = L->getLoopPreheader();
805 Instruction *PHTerminator = Preheader->getTerminator();
806
807 assert (NV && "Unexpected value");
808
Devang Patel5279d062007-09-17 20:39:48 +0000809 switch (CI->getPredicate()) {
810 case ICmpInst::ICMP_ULE:
811 case ICmpInst::ICMP_SLE:
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 //
Devang Patel453a8442007-09-25 17:31:19 +0000821 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
822 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000823 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000824 "lsplit.add", PHTerminator);
825 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
826 A, UB,"lsplit,c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000827 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000828 }
829
Devang Patel5279d062007-09-17 20:39:48 +0000830 // for (i = LB; i <= UB; ++i)
831 // if (i <= NV && ...)
832 // LOOP_BODY
833 //
834 // is transformed into
835 // NUB = min (NV, UB)
836 // for (i = LB; i <= NUB ; ++i)
837 // LOOP_BODY
838 //
Devang Patel453a8442007-09-25 17:31:19 +0000839 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
840 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
841 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
842 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000843 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000844 }
Devang Patel5279d062007-09-17 20:39:48 +0000845 break;
846 case ICmpInst::ICMP_ULT:
847 case ICmpInst::ICMP_SLT:
848 // for (i = LB; i < UB; ++i)
849 // if (i < NV && ...)
850 // LOOP_BODY
851 //
852 // is transformed into
853 // NUB = min (NV, UB)
854 // for (i = LB; i < NUB ; ++i)
855 // LOOP_BODY
856 //
Devang Patel453a8442007-09-25 17:31:19 +0000857 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
858 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
859 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
860 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000861 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000862 }
Devang Patel5279d062007-09-17 20:39:48 +0000863
864 // for (i = LB; i <= UB; ++i)
865 // if (i < NV && ...)
866 // LOOP_BODY
867 //
868 // is transformed into
869 // NUB = min (NV -1 , UB)
870 // for (i = LB; i <= NUB ; ++i)
871 // LOOP_BODY
872 //
Devang Patel453a8442007-09-25 17:31:19 +0000873 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
874 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000875 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000876 "lsplit.add", PHTerminator);
877 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
878 S, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000879 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000880 }
Devang Patel5279d062007-09-17 20:39:48 +0000881 break;
882 case ICmpInst::ICMP_UGE:
883 case ICmpInst::ICMP_SGE:
884 // for (i = LB; i (< or <=) UB; ++i)
885 // if (i >= NV && ...)
886 // LOOP_BODY
887 //
888 // is transformed into
889 // NLB = max (NV, LB)
890 // for (i = NLB; i (< or <=) UB ; ++i)
891 // LOOP_BODY
892 //
Devang Patel453a8442007-09-25 17:31:19 +0000893 {
894 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
895 NV, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000896 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000897 }
Devang Patel5279d062007-09-17 20:39:48 +0000898 break;
899 case ICmpInst::ICMP_UGT:
900 case ICmpInst::ICMP_SGT:
901 // for (i = LB; i (< or <=) UB; ++i)
902 // if (i > NV && ...)
903 // LOOP_BODY
904 //
905 // is transformed into
906 // NLB = max (NV+1, LB)
907 // for (i = NLB; i (< or <=) UB ; ++i)
908 // LOOP_BODY
909 //
Devang Patel453a8442007-09-25 17:31:19 +0000910 {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000911 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000912 "lsplit.add", PHTerminator);
913 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
914 A, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000915 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000916 }
Devang Patel5279d062007-09-17 20:39:48 +0000917 break;
918 default:
919 assert ( 0 && "Unexpected split condition predicate");
920 }
Devang Patel453a8442007-09-25 17:31:19 +0000921
922 if (NLB) {
923 unsigned i = IndVar->getBasicBlockIndex(Preheader);
924 IndVar->setIncomingValue(i, NLB);
925 }
926
927 if (NUB) {
928 ExitCondition->setOperand(ExitValueNum, NUB);
929 }
Devang Patel5279d062007-09-17 20:39:48 +0000930}
931/// updateLoopIterationSpace - Current loop body is covered by an AND
932/// instruction whose operands compares induction variables with loop
933/// invariants. If possible, hoist this check outside the loop by
934/// updating appropriate start and end values for induction variable.
935bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
936 BasicBlock *Header = L->getHeader();
Devang Patel453a8442007-09-25 17:31:19 +0000937 BasicBlock *ExitingBlock = ExitCondition->getParent();
938 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
939
Devang Patel5279d062007-09-17 20:39:48 +0000940 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
941 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
942
943 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
944 || Op0->getPredicate() == ICmpInst::ICMP_NE
Devang Pateld44b7c12008-10-06 23:22:54 +0000945 || Op1->getPredicate() == ICmpInst::ICMP_EQ
946 || Op1->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5279d062007-09-17 20:39:48 +0000947 return false;
948
949 // Check if SplitCondition dominates entire loop body
950 // or not.
951
952 // If SplitCondition is not in loop header then this loop is not suitable
953 // for this transformation.
954 if (SD.SplitCondition->getParent() != Header)
955 return false;
956
957 // If loop header includes loop variant instruction operands then
958 // this loop may not be eliminated.
959 Instruction *Terminator = Header->getTerminator();
960 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
961 BI != BE; ++BI) {
962 Instruction *I = BI;
963
964 // PHI Nodes are OK.
965 if (isa<PHINode>(I))
966 continue;
967
968 // SplitCondition itself is OK.
969 if (I == SD.SplitCondition)
970 continue;
971 if (I == Op0 || I == Op1)
972 continue;
973
974 // Induction variable is OK.
975 if (I == IndVar)
976 continue;
977
978 // Induction variable increment is OK.
979 if (I == IndVarIncrement)
980 continue;
981
982 // Terminator is also harmless.
983 if (I == Terminator)
984 continue;
985
986 // Otherwise we have a instruction that may not be safe.
987 return false;
988 }
989
990 // If Exiting block includes loop variant instructions then this
991 // loop may not be eliminated.
992 if (!safeExitingBlock(SD, ExitCondition->getParent()))
993 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000994
995 // Verify that loop exiting block has only two predecessor, where one predecessor
996 // is split condition block. The other predecessor will become exiting block's
997 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
998 // more then two predecessors. This requires extra work in updating dominator
999 // information.
1000 BasicBlock *ExitingBBPred = NULL;
1001 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
1002 PI != PE; ++PI) {
1003 BasicBlock *BB = *PI;
1004 if (SplitCondBlock == BB)
1005 continue;
1006 if (ExitingBBPred)
1007 return false;
1008 else
1009 ExitingBBPred = BB;
1010 }
1011
1012 // Update loop bounds to absorb Op0 check.
Devang Patel5279d062007-09-17 20:39:48 +00001013 updateLoopBounds(Op0);
Devang Patel453a8442007-09-25 17:31:19 +00001014 // Update loop bounds to absorb Op1 check.
Devang Patel5279d062007-09-17 20:39:48 +00001015 updateLoopBounds(Op1);
Devang Patel453a8442007-09-25 17:31:19 +00001016
Devang Patel5279d062007-09-17 20:39:48 +00001017 // Update CFG
Devang Patel453a8442007-09-25 17:31:19 +00001018
1019 // Unconditionally connect split block to its remaining successor.
1020 BranchInst *SplitTerminator =
1021 cast<BranchInst>(SplitCondBlock->getTerminator());
1022 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1023 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1024 if (Succ0 == ExitCondition->getParent())
1025 SplitTerminator->setUnconditionalDest(Succ1);
1026 else
1027 SplitTerminator->setUnconditionalDest(Succ0);
1028
1029 // Remove split condition.
1030 SD.SplitCondition->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +00001031 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +00001032 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +00001033 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +00001034 Op1->eraseFromParent();
1035
1036 BranchInst *ExitInsn =
1037 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1038 assert (ExitInsn && "Unable to find suitable loop exit branch");
1039 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1040 if (L->contains(ExitBlock))
1041 ExitBlock = ExitInsn->getSuccessor(0);
1042
1043 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1044 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1045 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1046
1047 // If ExitingBlock is a member of loop BB's DF list then replace it with
1048 // loop header and exit block.
1049 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1050 I != E; ++I) {
1051 BasicBlock *BB = *I;
1052 if (BB == Header || BB == ExitingBlock)
1053 continue;
1054 DominanceFrontier::iterator BBDF = DF->find(BB);
1055 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1056 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1057 while (DomSetI != DomSetE) {
1058 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1059 ++DomSetI;
1060 BasicBlock *DFBB = *CurrentItr;
1061 if (DFBB == ExitingBlock) {
1062 BBDF->second.erase(DFBB);
1063 BBDF->second.insert(Header);
1064 if (Header != ExitingBlock)
1065 BBDF->second.insert(ExitBlock);
1066 }
1067 }
1068 }
1069
Devang Patel1c013502007-09-25 17:43:08 +00001070 return true;
Devang Patel5279d062007-09-17 20:39:48 +00001071}
1072
1073
Devang Patela6a86632007-08-14 18:35:57 +00001074/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1075/// This routine is used to remove split condition's dead branch, dominated by
1076/// DeadBB. LiveBB dominates split conidition's other branch.
1077void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1078 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +00001079
Devang Patel5b8ec612007-08-15 03:31:47 +00001080 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +00001081 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +00001082 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1083 if (DeadBBDF != DF->end()) {
1084 SmallVector<BasicBlock *, 8> PredBlocks;
1085
1086 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1087 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1088 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1089 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +00001090 FrontierBBs.push_back(FrontierBB);
1091
Devang Patel5b8ec612007-08-15 03:31:47 +00001092 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1093 PredBlocks.clear();
1094 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1095 PI != PE; ++PI) {
1096 BasicBlock *P = *PI;
1097 if (P == DeadBB || DT->dominates(DeadBB, P))
1098 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001099 }
Devang Patel96bf5242007-08-17 21:59:16 +00001100
Devang Patel5b8ec612007-08-15 03:31:47 +00001101 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1102 FBI != FBE; ++FBI) {
1103 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1104 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1105 PE = PredBlocks.end(); PI != PE; ++PI) {
1106 BasicBlock *P = *PI;
1107 PN->removeIncomingValue(P);
1108 }
1109 }
1110 else
1111 break;
Devang Patel96bf5242007-08-17 21:59:16 +00001112 }
Devang Patel98147a32007-08-12 07:02:51 +00001113 }
Devang Patel98147a32007-08-12 07:02:51 +00001114 }
Devang Patel5b8ec612007-08-15 03:31:47 +00001115
1116 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1117 SmallVector<BasicBlock *, 32> WorkList;
1118 DomTreeNode *DN = DT->getNode(DeadBB);
1119 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1120 E = df_end(DN); DI != E; ++DI) {
1121 BasicBlock *BB = DI->getBlock();
1122 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +00001123 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +00001124 }
1125
1126 while (!WorkList.empty()) {
1127 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1128 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +00001129 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +00001130 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +00001131 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +00001132 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1133 I->eraseFromParent();
1134 }
1135 LPM->deleteSimpleAnalysisValue(BB, LP);
1136 DT->eraseNode(BB);
1137 DF->removeBlock(BB);
1138 LI->removeBlock(BB);
1139 BB->eraseFromParent();
1140 }
Devang Patel96bf5242007-08-17 21:59:16 +00001141
1142 // Update Frontier BBs' dominator info.
1143 while (!FrontierBBs.empty()) {
1144 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1145 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1146 if (!NewDominator) {
1147 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1148 NewDominator = *PI;
1149 ++PI;
1150 if (NewDominator != LiveBB) {
1151 for(; PI != PE; ++PI) {
1152 BasicBlock *P = *PI;
1153 if (P == LiveBB) {
1154 NewDominator = LiveBB;
1155 break;
1156 }
1157 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1158 }
1159 }
1160 }
1161 assert (NewDominator && "Unable to fix dominator info.");
1162 DT->changeImmediateDominator(FBB, NewDominator);
1163 DF->changeImmediateDominator(FBB, NewDominator, DT);
1164 }
1165
Devang Patel98147a32007-08-12 07:02:51 +00001166}
1167
Devang Pateldc523952007-08-22 18:27:01 +00001168/// safeSplitCondition - Return true if it is possible to
1169/// split loop using given split condition.
1170bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patel23a19f82007-08-10 00:53:35 +00001171
Devang Pateldc523952007-08-22 18:27:01 +00001172 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel8893ca62007-09-17 21:01:05 +00001173 BasicBlock *Latch = L->getLoopLatch();
Devang Pateldc523952007-08-22 18:27:01 +00001174 BranchInst *SplitTerminator =
1175 cast<BranchInst>(SplitCondBlock->getTerminator());
1176 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1177 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel20d260a2007-08-18 00:00:32 +00001178
Bill Wendling643310d2008-05-02 00:43:20 +00001179 // If split block does not dominate the latch then this is not a diamond.
1180 // Such loop may not benefit from index split.
1181 if (!DT->dominates(SplitCondBlock, Latch))
1182 return false;
1183
Devang Patelb88e4202007-08-24 05:36:56 +00001184 // Finally this split condition is safe only if merge point for
1185 // split condition branch is loop latch. This check along with previous
1186 // check, to ensure that exit condition is in either loop latch or header,
1187 // filters all loops with non-empty loop body between merge point
1188 // and exit condition.
1189 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1190 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1191 if (Succ0DF->second.count(Latch))
1192 return true;
1193
1194 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1195 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1196 if (Succ1DF->second.count(Latch))
1197 return true;
1198
1199 return false;
Devang Pateldc523952007-08-22 18:27:01 +00001200}
1201
Devang Patel4a69da92007-08-25 00:56:38 +00001202/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1203/// based on split value.
1204void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1205
Devang Patel4f12c5f2007-09-11 00:12:56 +00001206 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1207 ICmpInst::Predicate SP = SC->getPredicate();
Devang Patel4a69da92007-08-25 00:56:38 +00001208 const Type *Ty = SD.SplitValue->getType();
1209 bool Sign = ExitCondition->isSignedPredicate();
1210 BasicBlock *Preheader = L->getLoopPreheader();
1211 Instruction *PHTerminator = Preheader->getTerminator();
1212
1213 // Initially use split value as upper loop bound for first loop and lower loop
1214 // bound for second loop.
1215 Value *AEV = SD.SplitValue;
1216 Value *BSV = SD.SplitValue;
1217
Devang Patelbabbe272007-09-19 00:28:47 +00001218 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1219 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1220 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel02c48362008-02-13 19:48:48 +00001221 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
Devang Patelbabbe272007-09-19 00:28:47 +00001222 ExitCondition->swapOperands();
Devang Patel02c48362008-02-13 19:48:48 +00001223 if (ExitValueNum)
1224 ExitValueNum = 0;
1225 else
1226 ExitValueNum = 1;
1227 }
Devang Patelbabbe272007-09-19 00:28:47 +00001228
Devang Patel4a69da92007-08-25 00:56:38 +00001229 switch (ExitCondition->getPredicate()) {
1230 case ICmpInst::ICMP_SGT:
1231 case ICmpInst::ICMP_UGT:
1232 case ICmpInst::ICMP_SGE:
1233 case ICmpInst::ICMP_UGE:
1234 default:
1235 assert (0 && "Unexpected exit condition predicate");
1236
1237 case ICmpInst::ICMP_SLT:
1238 case ICmpInst::ICMP_ULT:
1239 {
1240 switch (SP) {
1241 case ICmpInst::ICMP_SLT:
1242 case ICmpInst::ICMP_ULT:
1243 //
1244 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1245 //
1246 // is transformed into
1247 // AEV = BSV = SV
1248 // for (i = LB; i < min(UB, AEV); ++i)
1249 // A;
1250 // for (i = max(LB, BSV); i < UB; ++i);
1251 // B;
1252 break;
1253 case ICmpInst::ICMP_SLE:
1254 case ICmpInst::ICMP_ULE:
1255 {
1256 //
1257 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1258 //
1259 // is transformed into
1260 //
1261 // AEV = SV + 1
1262 // BSV = SV + 1
1263 // for (i = LB; i < min(UB, AEV); ++i)
1264 // A;
1265 // for (i = max(LB, BSV); i < UB; ++i)
1266 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001267 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001268 ConstantInt::get(Ty, 1, Sign),
1269 "lsplit.add", PHTerminator);
1270 AEV = BSV;
1271 }
1272 break;
1273 case ICmpInst::ICMP_SGE:
1274 case ICmpInst::ICMP_UGE:
1275 //
1276 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1277 //
1278 // is transformed into
1279 // AEV = BSV = SV
1280 // for (i = LB; i < min(UB, AEV); ++i)
1281 // B;
1282 // for (i = max(BSV, LB); i < UB; ++i)
1283 // A;
1284 break;
1285 case ICmpInst::ICMP_SGT:
1286 case ICmpInst::ICMP_UGT:
1287 {
1288 //
1289 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1290 //
1291 // is transformed into
1292 //
1293 // BSV = AEV = SV + 1
1294 // for (i = LB; i < min(UB, AEV); ++i)
1295 // B;
1296 // for (i = max(LB, BSV); i < UB; ++i)
1297 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001298 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001299 ConstantInt::get(Ty, 1, Sign),
1300 "lsplit.add", PHTerminator);
1301 AEV = BSV;
1302 }
1303 break;
1304 default:
1305 assert (0 && "Unexpected split condition predicate");
1306 break;
1307 } // end switch (SP)
1308 }
1309 break;
1310 case ICmpInst::ICMP_SLE:
1311 case ICmpInst::ICMP_ULE:
1312 {
1313 switch (SP) {
1314 case ICmpInst::ICMP_SLT:
1315 case ICmpInst::ICMP_ULT:
1316 //
1317 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1318 //
1319 // is transformed into
1320 // AEV = SV - 1;
1321 // BSV = SV;
1322 // for (i = LB; i <= min(UB, AEV); ++i)
1323 // A;
1324 // for (i = max(LB, BSV); i <= UB; ++i)
1325 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001326 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001327 ConstantInt::get(Ty, 1, Sign),
1328 "lsplit.sub", PHTerminator);
1329 break;
1330 case ICmpInst::ICMP_SLE:
1331 case ICmpInst::ICMP_ULE:
1332 //
1333 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1334 //
1335 // is transformed into
1336 // AEV = SV;
1337 // BSV = SV + 1;
1338 // for (i = LB; i <= min(UB, AEV); ++i)
1339 // A;
1340 // for (i = max(LB, BSV); i <= UB; ++i)
1341 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001342 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001343 ConstantInt::get(Ty, 1, Sign),
1344 "lsplit.add", PHTerminator);
1345 break;
1346 case ICmpInst::ICMP_SGT:
1347 case ICmpInst::ICMP_UGT:
1348 //
1349 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1350 //
1351 // is transformed into
1352 // AEV = SV;
1353 // BSV = SV + 1;
1354 // for (i = LB; i <= min(AEV, UB); ++i)
1355 // B;
1356 // for (i = max(LB, BSV); i <= UB; ++i)
1357 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001358 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001359 ConstantInt::get(Ty, 1, Sign),
1360 "lsplit.add", PHTerminator);
1361 break;
1362 case ICmpInst::ICMP_SGE:
1363 case ICmpInst::ICMP_UGE:
1364 // ** TODO **
1365 //
1366 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1367 //
1368 // is transformed into
1369 // AEV = SV - 1;
1370 // BSV = SV;
1371 // for (i = LB; i <= min(AEV, UB); ++i)
1372 // B;
1373 // for (i = max(LB, BSV); i <= UB; ++i)
1374 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001375 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001376 ConstantInt::get(Ty, 1, Sign),
1377 "lsplit.sub", PHTerminator);
1378 break;
1379 default:
1380 assert (0 && "Unexpected split condition predicate");
1381 break;
1382 } // end switch (SP)
1383 }
1384 break;
1385 }
1386
1387 // Calculate ALoop induction variable's new exiting value and
1388 // BLoop induction variable's new starting value. Calculuate these
1389 // values in original loop's preheader.
1390 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1391 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel3f65f022007-09-21 21:18:19 +00001392 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Patel5ffdc562007-12-03 19:17:21 +00001393
1394 // If ExitValue operand is also defined in Loop header then
1395 // insert new ExitValue after this operand definition.
1396 if (Instruction *EVN =
1397 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1398 if (!isa<PHINode>(EVN))
1399 if (InsertPt->getParent() == EVN->getParent()) {
1400 BasicBlock::iterator LHBI = L->getHeader()->begin();
1401 BasicBlock::iterator LHBE = L->getHeader()->end();
1402 for(;LHBI != LHBE; ++LHBI) {
1403 Instruction *I = LHBI;
1404 if (I == EVN)
1405 break;
1406 }
1407 InsertPt = ++LHBI;
1408 }
1409 }
Devang Patel4a69da92007-08-25 00:56:38 +00001410 Value *C1 = new ICmpInst(Sign ?
1411 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1412 AEV,
1413 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001414 "lsplit.ev", InsertPt);
1415
Gabor Greif051a9502008-04-06 20:25:17 +00001416 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1417 ExitCondition->getOperand(ExitValueNum),
1418 "lsplit.ev", InsertPt);
Devang Patel3f65f022007-09-21 21:18:19 +00001419
Devang Patel4a69da92007-08-25 00:56:38 +00001420 Value *C2 = new ICmpInst(Sign ?
1421 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1422 BSV, StartValue, "lsplit.sv",
1423 PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +00001424 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1425 "lsplit.sv", PHTerminator);
Devang Patel4a69da92007-08-25 00:56:38 +00001426}
1427
Devang Pateldc523952007-08-22 18:27:01 +00001428/// splitLoop - Split current loop L in two loops using split information
1429/// SD. Update dominator information. Maintain LCSSA form.
1430bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1431
1432 if (!safeSplitCondition(SD))
1433 return false;
1434
Devang Patel4fe0fe82008-09-18 23:45:14 +00001435 // If split condition EQ is not handled.
1436 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(SD.SplitCondition)) {
1437 if (ICMP->getPredicate() == ICmpInst::ICMP_EQ)
1438 return false;
1439 }
1440
Devang Patel8893ca62007-09-17 21:01:05 +00001441 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1442
Dan Gohman2864ce62008-06-24 18:00:21 +00001443 // Unable to handle triangle loops at the moment.
Devang Patel8893ca62007-09-17 21:01:05 +00001444 // In triangle loop, split condition is in header and one of the
1445 // the split destination is loop latch. If split condition is EQ
1446 // then such loops are already handle in processOneIterationLoop().
1447 BasicBlock *Latch = L->getLoopLatch();
1448 BranchInst *SplitTerminator =
1449 cast<BranchInst>(SplitCondBlock->getTerminator());
1450 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1451 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1452 if (L->getHeader() == SplitCondBlock
1453 && (Latch == Succ0 || Latch == Succ1))
1454 return false;
1455
1456 // If split condition branches heads do not have single predecessor,
1457 // SplitCondBlock, then is not possible to remove inactive branch.
1458 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1459 return false;
1460
Devang Patel82ada542008-02-08 22:49:13 +00001461 // If Exiting block includes loop variant instructions then this
1462 // loop may not be split safely.
1463 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1464 return false;
1465
Devang Patela8644e32007-08-22 19:33:29 +00001466 // After loop is cloned there are two loops.
1467 //
1468 // First loop, referred as ALoop, executes first part of loop's iteration
1469 // space split. Second loop, referred as BLoop, executes remaining
1470 // part of loop's iteration space.
1471 //
1472 // ALoop's exit edge enters BLoop's header through a forwarding block which
1473 // acts as a BLoop's preheader.
Devang Patel4a69da92007-08-25 00:56:38 +00001474 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateldc523952007-08-22 18:27:01 +00001475
Devang Patel4a69da92007-08-25 00:56:38 +00001476 // Calculate ALoop induction variable's new exiting value and
1477 // BLoop induction variable's new starting value.
1478 calculateLoopBounds(SD);
Devang Patel423c8b22007-08-10 18:07:13 +00001479
Devang Patela8644e32007-08-22 19:33:29 +00001480 //[*] Clone loop.
Devang Patel98147a32007-08-12 07:02:51 +00001481 DenseMap<const Value *, Value *> ValueMap;
Devang Patela8644e32007-08-22 19:33:29 +00001482 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Pateld79faee2007-08-25 02:39:24 +00001483 Loop *ALoop = L;
Devang Patela8644e32007-08-22 19:33:29 +00001484 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel98147a32007-08-12 07:02:51 +00001485
Devang Patela8644e32007-08-22 19:33:29 +00001486 //[*] ALoop's exiting edge BLoop's header.
1487 // ALoop's original exit block becomes BLoop's exit block.
1488 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1489 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1490 BranchInst *A_ExitInsn =
1491 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1492 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1493 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1494 if (L->contains(B_ExitBlock)) {
1495 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1496 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patelada054a2007-08-14 01:30:57 +00001497 } else
Devang Patela8644e32007-08-22 19:33:29 +00001498 A_ExitInsn->setSuccessor(1, B_Header);
1499
1500 //[*] Update ALoop's exit value using new exit value.
Devang Patel4a69da92007-08-25 00:56:38 +00001501 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001502
Devang Patela8644e32007-08-22 19:33:29 +00001503 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1504 // original loop's preheader. Add incoming PHINode values from
1505 // ALoop's exiting block. Update BLoop header's domiantor info.
1506
Devang Patelada054a2007-08-14 01:30:57 +00001507 // Collect inverse map of Header PHINodes.
1508 DenseMap<Value *, Value *> InverseMap;
1509 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1510 BE = L->getHeader()->end(); BI != BE; ++BI) {
1511 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1512 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1513 InverseMap[PNClone] = PN;
1514 } else
1515 break;
1516 }
Devang Patel4a69da92007-08-25 00:56:38 +00001517
Devang Patela8644e32007-08-22 19:33:29 +00001518 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel98147a32007-08-12 07:02:51 +00001519 BI != BE; ++BI) {
1520 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001521 // Remove incoming value from original preheader.
1522 PN->removeIncomingValue(Preheader);
1523
1524 // Add incoming value from A_ExitingBlock.
1525 if (PN == B_IndVar)
Devang Patel4a69da92007-08-25 00:56:38 +00001526 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001527 else {
1528 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patel9b03daa2008-02-14 23:18:47 +00001529 Value *V2 = NULL;
1530 // If loop header is also loop exiting block then
1531 // OrigPN is incoming value for B loop header.
1532 if (A_ExitingBlock == L->getHeader())
1533 V2 = OrigPN;
1534 else
1535 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
Devang Patela8644e32007-08-22 19:33:29 +00001536 PN->addIncoming(V2, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001537 }
1538 } else
Devang Patel98147a32007-08-12 07:02:51 +00001539 break;
1540 }
Devang Patela8644e32007-08-22 19:33:29 +00001541 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1542 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001543
Devang Patela8644e32007-08-22 19:33:29 +00001544 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1545 // block. Remove incoming PHINode values from ALoop's exiting block.
1546 // Add new incoming values from BLoop's incoming exiting value.
1547 // Update BLoop exit block's dominator info..
1548 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1549 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patelada054a2007-08-14 01:30:57 +00001550 BI != BE; ++BI) {
1551 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001552 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1553 B_ExitingBlock);
1554 PN->removeIncomingValue(A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001555 } else
1556 break;
1557 }
Devang Patel98147a32007-08-12 07:02:51 +00001558
Devang Patela8644e32007-08-22 19:33:29 +00001559 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1560 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001561
Devang Patela8644e32007-08-22 19:33:29 +00001562 //[*] Split ALoop's exit edge. This creates a new block which
1563 // serves two purposes. First one is to hold PHINode defnitions
1564 // to ensure that ALoop's LCSSA form. Second use it to act
1565 // as a preheader for BLoop.
1566 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel423c8b22007-08-10 18:07:13 +00001567
Devang Patela8644e32007-08-22 19:33:29 +00001568 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1569 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1570 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel60cbab42007-08-21 19:47:46 +00001571 BI != BE; ++BI) {
1572 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001573 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001574 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
Devang Patela8644e32007-08-22 19:33:29 +00001575 newPHI->addIncoming(V1, A_ExitingBlock);
1576 A_ExitBlock->getInstList().push_front(newPHI);
1577 PN->removeIncomingValue(A_ExitBlock);
1578 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001579 } else
1580 break;
1581 }
1582
Devang Patela8644e32007-08-22 19:33:29 +00001583 //[*] Eliminate split condition's inactive branch from ALoop.
1584 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1585 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001586 BasicBlock *A_InactiveBranch = NULL;
1587 BasicBlock *A_ActiveBranch = NULL;
1588 if (SD.UseTrueBranchFirst) {
1589 A_ActiveBranch = A_BR->getSuccessor(0);
1590 A_InactiveBranch = A_BR->getSuccessor(1);
1591 } else {
1592 A_ActiveBranch = A_BR->getSuccessor(1);
1593 A_InactiveBranch = A_BR->getSuccessor(0);
1594 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001595 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001596 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1597
1598 //[*] Eliminate split condition's inactive branch in from BLoop.
1599 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1600 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001601 BasicBlock *B_InactiveBranch = NULL;
1602 BasicBlock *B_ActiveBranch = NULL;
1603 if (SD.UseTrueBranchFirst) {
1604 B_ActiveBranch = B_BR->getSuccessor(1);
1605 B_InactiveBranch = B_BR->getSuccessor(0);
1606 } else {
1607 B_ActiveBranch = B_BR->getSuccessor(0);
1608 B_InactiveBranch = B_BR->getSuccessor(1);
1609 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001610 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001611 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1612
Devang Pateld79faee2007-08-25 02:39:24 +00001613 BasicBlock *A_Header = L->getHeader();
1614 if (A_ExitingBlock == A_Header)
1615 return true;
1616
1617 //[*] Move exit condition into split condition block to avoid
1618 // executing dead loop iteration.
1619 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1620 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1621 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1622
1623 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel4f12c5f2007-09-11 00:12:56 +00001624 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1625 ALoop);
Devang Pateld79faee2007-08-25 02:39:24 +00001626
1627 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1628 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1629
Devang Patel98147a32007-08-12 07:02:51 +00001630 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +00001631}
Devang Pateld79faee2007-08-25 02:39:24 +00001632
1633// moveExitCondition - Move exit condition EC into split condition block CondBB.
1634void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1635 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1636 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1637
1638 BasicBlock *ExitingBB = EC->getParent();
1639 Instruction *CurrentBR = CondBB->getTerminator();
1640
1641 // Move exit condition into split condition block.
1642 EC->moveBefore(CurrentBR);
1643 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1644
1645 // Move exiting block's branch into split condition block. Update its branch
1646 // destination.
1647 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1648 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +00001649 BasicBlock *OrigDestBB = NULL;
1650 if (ExitingBR->getSuccessor(0) == ExitBB) {
1651 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +00001652 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001653 }
1654 else {
1655 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +00001656 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001657 }
Devang Pateld79faee2007-08-25 02:39:24 +00001658
1659 // Remove split condition and current split condition branch.
1660 SC->eraseFromParent();
1661 CurrentBR->eraseFromParent();
1662
Devang Patel23067df2008-02-13 22:06:36 +00001663 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +00001664 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +00001665
1666 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +00001667 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +00001668
1669 // Fix dominator info.
1670 // ExitBB is now dominated by CondBB
1671 DT->changeImmediateDominator(ExitBB, CondBB);
1672 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1673
1674 // Basicblocks dominated by ActiveBB may have ExitingBB or
1675 // a basic block outside the loop in their DF list. If so,
1676 // replace it with CondBB.
1677 DomTreeNode *Node = DT->getNode(ActiveBB);
1678 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1679 DI != DE; ++DI) {
1680 BasicBlock *BB = DI->getBlock();
1681 DominanceFrontier::iterator BBDF = DF->find(BB);
1682 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1683 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1684 while (DomSetI != DomSetE) {
1685 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1686 ++DomSetI;
1687 BasicBlock *DFBB = *CurrentItr;
1688 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1689 BBDF->second.erase(DFBB);
1690 BBDF->second.insert(CondBB);
1691 }
1692 }
1693 }
1694}
1695
1696/// updatePHINodes - CFG has been changed.
1697/// Before
1698/// - ExitBB's single predecessor was Latch
1699/// - Latch's second successor was Header
1700/// Now
Devang Patel82ada542008-02-08 22:49:13 +00001701/// - ExitBB's single predecessor is Header
1702/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +00001703///
1704/// Update ExitBB PHINodes' to reflect this change.
1705void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1706 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +00001707 PHINode *IV, Instruction *IVIncrement,
1708 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +00001709
1710 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001711 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +00001712 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001713 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +00001714 if (!PN)
1715 break;
1716
1717 Value *V = PN->getIncomingValueForBlock(Latch);
1718 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +00001719 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1720 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +00001721 Value *NewV = NULL;
1722 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +00001723 UI != E; ++UI)
1724 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +00001725 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +00001726 NewV = U;
1727 break;
1728 }
1729
Devang Patel60a12902008-03-24 20:16:14 +00001730 // Add incoming value from header only if PN has any use inside the loop.
1731 if (NewV)
1732 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +00001733
1734 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1735 // If this instruction is IVIncrement then IV is new incoming value
1736 // from header otherwise this instruction must be incoming value from
1737 // header because loop is in LCSSA form.
1738 if (PHI == IVIncrement)
1739 PN->addIncoming(IV, Header);
1740 else
1741 PN->addIncoming(V, Header);
1742 } else
1743 // Otherwise this is an incoming value from header because loop is in
1744 // LCSSA form.
1745 PN->addIncoming(V, Header);
1746
1747 // Remove incoming value from Latch.
1748 PN->removeIncomingValue(Latch);
1749 }
1750}