blob: 110919c1bdff1629e8b82fd1b160a2b173e82997 [file] [log] [blame]
Devang Patelbc5fe632007-08-07 00:25:56 +00001//===- 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
Devang Patelbc5fe632007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
Devang Patel3719d4f2007-08-07 23:17:52 +000017#include "llvm/Function.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000018#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel95fd7172007-08-08 21:39:47 +000020#include "llvm/Analysis/Dominators.h"
Devang Patel901f67e2007-08-10 18:07:13 +000021#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000023#include "llvm/Support/Compiler.h"
24#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
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
40
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
Devang Patel901f67e2007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelbc5fe632007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel0aaeb172007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patel95fd7172007-08-08 21:39:47 +000051 AU.addPreserved<DominatorTree>();
52 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000053 }
54
55 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000056
57 class SplitInfo {
58 public:
Devang Patel61571ca2007-08-10 00:33:50 +000059 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000060
Devang Patelc8dadbf2007-08-08 21:02:17 +000061 // Induction variable's range is split at this value.
62 Value *SplitValue;
63
Devang Patelc8dadbf2007-08-08 21:02:17 +000064 // This compare instruction compares IndVar against SplitValue.
65 ICmpInst *SplitCondition;
66
Devang Patel31696332007-08-08 21:18:27 +000067 // Clear split info.
68 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000069 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000070 SplitCondition = NULL;
Devang Patel31696332007-08-08 21:18:27 +000071 }
Devang Patel2545f7b2007-08-09 01:39:01 +000072
Devang Patelc8dadbf2007-08-08 21:02:17 +000073 };
Devang Patel61571ca2007-08-10 00:33:50 +000074
Devang Patelc8dadbf2007-08-08 21:02:17 +000075 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000076 /// Find condition inside a loop that is suitable candidate for index split.
77 void findSplitCondition();
78
Devang Patel61571ca2007-08-10 00:33:50 +000079 /// Find loop's exit condition.
80 void findLoopConditionals();
81
82 /// Return induction variable associated with value V.
83 void findIndVar(Value *V, Loop *L);
84
Devang Patelbc5fe632007-08-07 00:25:56 +000085 /// processOneIterationLoop - Current loop L contains compare instruction
86 /// that compares induction variable, IndVar, agains loop invariant. If
87 /// entire (i.e. meaningful) loop body is dominated by this compare
88 /// instruction then loop body is executed only for one iteration. In
89 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +000090 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +000091
Devang Patel0aaeb172007-08-08 22:25:28 +000092 /// If loop header includes loop variant instruction operands then
93 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000094 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000095
Devang Patel0aaeb172007-08-08 22:25:28 +000096 /// If Exit block includes loop variant instructions then this
97 /// loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000098 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000099
Devang Patel0aaeb172007-08-08 22:25:28 +0000100 /// Find cost of spliting loop L.
101 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000102 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000103
Devang Patel61571ca2007-08-10 00:33:50 +0000104 void initialize() {
105 IndVar = NULL;
106 IndVarIncrement = NULL;
107 ExitCondition = NULL;
108 StartValue = ExitValue = NULL;
109 }
110
Devang Patelbc5fe632007-08-07 00:25:56 +0000111 private:
112
113 // Current Loop.
114 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000115 LPPassManager *LPM;
116 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000117 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000118 DominatorTree *DT;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000119 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000120
121 // Induction variable whose range is being split by this transformation.
122 PHINode *IndVar;
123 Instruction *IndVarIncrement;
124
125 // Loop exit condition.
126 ICmpInst *ExitCondition;
127
128 // Induction variable's initial value.
129 Value *StartValue;
130
131 // Induction variable's final loop exit value.
132 Value *ExitValue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000133 };
134
135 char LoopIndexSplit::ID = 0;
136 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
137}
138
139LoopPass *llvm::createLoopIndexSplitPass() {
140 return new LoopIndexSplit();
141}
142
143// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000144bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000145 bool Changed = false;
146 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000147 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000148
Devang Patelbc5fe632007-08-07 00:25:56 +0000149 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000150 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000151 LI = &getAnalysis<LoopInfo>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000152
Devang Patel61571ca2007-08-10 00:33:50 +0000153 initialize();
154
155 findLoopConditionals();
156
157 if (!ExitCondition)
158 return false;
159
Devang Patelbc5fe632007-08-07 00:25:56 +0000160 findSplitCondition();
161
Devang Patelc8dadbf2007-08-08 21:02:17 +0000162 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000163 return false;
164
Devang Patelc8dadbf2007-08-08 21:02:17 +0000165 // First see if it is possible to eliminate loop itself or not.
166 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
167 E = SplitData.end(); SI != E; ++SI) {
168 SplitInfo &SD = *SI;
169 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000170 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000171 if (Changed) {
172 ++NumIndexSplit;
173 // If is loop is eliminated then nothing else to do here.
174 return Changed;
175 }
176 }
177 }
178
Devang Patel0aaeb172007-08-08 22:25:28 +0000179 unsigned MaxCost = 99;
180 unsigned Index = 0;
181 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000182 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000183 E = SplitData.end(); SI != E; ++SI, ++Index) {
184 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000185
186 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000187 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000188 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000189
190 unsigned Cost = findSplitCost(L, SD);
191 if (Cost < MaxCost)
192 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000193 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000194
Devang Patel0aaeb172007-08-08 22:25:28 +0000195 // Split most profitiable condition.
196 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
197
Devang Patelbc5fe632007-08-07 00:25:56 +0000198 if (Changed)
199 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000200
Devang Patelbc5fe632007-08-07 00:25:56 +0000201 return Changed;
202}
203
Devang Patel2545f7b2007-08-09 01:39:01 +0000204/// Return true if V is a induction variable or induction variable's
205/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000206void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000207
208 Instruction *I = dyn_cast<Instruction>(V);
209 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000210 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000211
212 // Check if I is a phi node from loop header or not.
213 if (PHINode *PN = dyn_cast<PHINode>(V)) {
214 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000215 IndVar = PN;
216 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000217 }
218 }
219
220 // Check if I is a add instruction whose one operand is
221 // phi node from loop header and second operand is constant.
222 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000223 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000224
225 Value *Op0 = I->getOperand(0);
226 Value *Op1 = I->getOperand(1);
227
228 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
229 if (PN->getParent() == L->getHeader()
230 && isa<ConstantInt>(Op1)) {
231 IndVar = PN;
232 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000233 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000234 }
235 }
236
237 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
238 if (PN->getParent() == L->getHeader()
239 && isa<ConstantInt>(Op0)) {
240 IndVar = PN;
241 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000242 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000243 }
244 }
245
Devang Patel61571ca2007-08-10 00:33:50 +0000246 return;
247}
248
249// Find loop's exit condition and associated induction variable.
250void LoopIndexSplit::findLoopConditionals() {
251
252 BasicBlock *ExitBlock = NULL;
253
254 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
255 I != E; ++I) {
256 BasicBlock *BB = *I;
257 if (!L->isLoopExit(BB))
258 continue;
259 if (ExitBlock)
260 return;
261 ExitBlock = BB;
262 }
263
264 if (!ExitBlock)
265 return;
266
267 // If exit block's terminator is conditional branch inst then we have found
268 // exit condition.
269 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
270 if (!BR || BR->isUnconditional())
271 return;
272
273 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
274 if (!CI)
275 return;
276
277 ExitCondition = CI;
278
279 // Exit condition's one operand is loop invariant exit value and second
280 // operand is SCEVAddRecExpr based on induction variable.
281 Value *V0 = CI->getOperand(0);
282 Value *V1 = CI->getOperand(1);
283
284 SCEVHandle SH0 = SE->getSCEV(V0);
285 SCEVHandle SH1 = SE->getSCEV(V1);
286
287 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
288 ExitValue = V0;
289 findIndVar(V1, L);
290 }
291 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
292 ExitValue = V1;
293 findIndVar(V0, L);
294 }
295
296 if (!ExitValue || !IndVar)
297 ExitCondition = NULL;
298 else if (IndVar) {
299 BasicBlock *Preheader = L->getLoopPreheader();
300 StartValue = IndVar->getIncomingValueForBlock(Preheader);
301 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000302}
303
Devang Patelbc5fe632007-08-07 00:25:56 +0000304/// Find condition inside a loop that is suitable candidate for index split.
305void LoopIndexSplit::findSplitCondition() {
306
Devang Patelc8dadbf2007-08-08 21:02:17 +0000307 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000308 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000309
Devang Patel2545f7b2007-08-09 01:39:01 +0000310 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
311 I != E; ++I) {
312 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000313
Devang Patel2545f7b2007-08-09 01:39:01 +0000314 // If this basic block does not terminate in a conditional branch
315 // then terminator is not a suitable split condition.
316 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
317 if (!BR)
318 continue;
319
320 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000321 continue;
322
Devang Patel2545f7b2007-08-09 01:39:01 +0000323 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000324 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000325 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000326
Devang Patel2545f7b2007-08-09 01:39:01 +0000327 // If one operand is loop invariant and second operand is SCEVAddRecExpr
328 // based on induction variable then CI is a candidate split condition.
329 Value *V0 = CI->getOperand(0);
330 Value *V1 = CI->getOperand(1);
331
332 SCEVHandle SH0 = SE->getSCEV(V0);
333 SCEVHandle SH1 = SE->getSCEV(V1);
334
335 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
336 SD.SplitValue = V0;
337 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000338 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
339 if (PN == IndVar)
340 SplitData.push_back(SD);
341 }
342 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
343 if (IndVarIncrement && IndVarIncrement == Insn)
344 SplitData.push_back(SD);
345 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000346 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000347 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
348 SD.SplitValue = V1;
349 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000350 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
351 if (PN == IndVar)
352 SplitData.push_back(SD);
353 }
354 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
355 if (IndVarIncrement && IndVarIncrement == Insn)
356 SplitData.push_back(SD);
357 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000358 }
359 }
360}
361
362/// processOneIterationLoop - Current loop L contains compare instruction
363/// that compares induction variable, IndVar, against loop invariant. If
364/// entire (i.e. meaningful) loop body is dominated by this compare
365/// instruction then loop body is executed only once. In such case eliminate
366/// loop structure surrounding this loop body. For example,
367/// for (int i = start; i < end; ++i) {
368/// if ( i == somevalue) {
369/// loop_body
370/// }
371/// }
372/// can be transformed into
373/// if (somevalue >= start && somevalue < end) {
374/// i = somevalue;
375/// loop_body
376/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000377bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000378
379 BasicBlock *Header = L->getHeader();
380
381 // First of all, check if SplitCondition dominates entire loop body
382 // or not.
383
384 // If SplitCondition is not in loop header then this loop is not suitable
385 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000386 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000387 return false;
388
Devang Patelbc5fe632007-08-07 00:25:56 +0000389 // If loop header includes loop variant instruction operands then
390 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000391 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000392 return false;
393
394 // If Exit block includes loop variant instructions then this
395 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000396 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000397 return false;
398
Devang Patel2bcb5012007-08-08 01:51:27 +0000399 // Update CFG.
400
401 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000402 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000403 BasicBlock *LatchSucc = NULL;
404 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
405 if (!BR)
406 return false;
407 Header->removePredecessor(Latch);
408 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
409 SI != E; ++SI) {
410 if (Header != *SI)
411 LatchSucc = *SI;
412 }
413 BR->setUnconditionalDest(LatchSucc);
414
Devang Patelbc5fe632007-08-07 00:25:56 +0000415 BasicBlock *Preheader = L->getLoopPreheader();
416 Instruction *Terminator = Header->getTerminator();
Devang Patel61571ca2007-08-10 00:33:50 +0000417 StartValue = IndVar->getIncomingValueForBlock(Preheader);
Devang Patelbc5fe632007-08-07 00:25:56 +0000418
Devang Patelbc5fe632007-08-07 00:25:56 +0000419 // Replace split condition in header.
420 // Transform
421 // SplitCondition : icmp eq i32 IndVar, SplitValue
422 // into
423 // c1 = icmp uge i32 SplitValue, StartValue
424 // c2 = icmp ult i32 vSplitValue, ExitValue
425 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000426 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000427 Instruction *C1 = new ICmpInst(SignedPredicate ?
428 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000429 SD.SplitValue, StartValue, "lisplit",
430 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000431 Instruction *C2 = new ICmpInst(SignedPredicate ?
432 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel61571ca2007-08-10 00:33:50 +0000433 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000434 Terminator);
435 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
436 Terminator);
437 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
438 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000439
Devang Patelbc5fe632007-08-07 00:25:56 +0000440 // Now, clear latch block. Remove instructions that are responsible
441 // to increment induction variable.
442 Instruction *LTerminator = Latch->getTerminator();
443 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
444 LB != LE; ) {
445 Instruction *I = LB;
446 ++LB;
447 if (isa<PHINode>(I) || I == LTerminator)
448 continue;
449
450 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000451 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000452 }
453
Devang Patel901f67e2007-08-10 18:07:13 +0000454 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000455
456 // Update Dominator Info.
457 // Only CFG change done is to remove Latch to Header edge. This
458 // does not change dominator tree because Latch did not dominate
459 // Header.
460 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
461 DominanceFrontier::iterator HeaderDF = DF->find(Header);
462 if (HeaderDF != DF->end())
463 DF->removeFromFrontier(HeaderDF, Header);
464
465 DominanceFrontier::iterator LatchDF = DF->find(Latch);
466 if (LatchDF != DF->end())
467 DF->removeFromFrontier(LatchDF, Header);
468 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000469 return true;
470}
471
472// If loop header includes loop variant instruction operands then
473// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000474bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000475
476 Instruction *Terminator = Header->getTerminator();
477 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
478 BI != BE; ++BI) {
479 Instruction *I = BI;
480
Devang Patel2bcb5012007-08-08 01:51:27 +0000481 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000482 if (isa<PHINode>(I))
483 continue;
484
485 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000486 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000487 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000488
Devang Patel2545f7b2007-08-09 01:39:01 +0000489 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000490 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000491 continue;
492
493 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000494 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000495 continue;
496
Devang Patelbc5fe632007-08-07 00:25:56 +0000497 // Terminator is also harmless.
498 if (I == Terminator)
499 continue;
500
501 // Otherwise we have a instruction that may not be safe.
502 return false;
503 }
504
505 return true;
506}
507
508// If Exit block includes loop variant instructions then this
509// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000510bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000511
Devang Patelbc5fe632007-08-07 00:25:56 +0000512 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
513 BI != BE; ++BI) {
514 Instruction *I = BI;
515
Devang Patel2bcb5012007-08-08 01:51:27 +0000516 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000517 if (isa<PHINode>(I))
518 continue;
519
Devang Patel2545f7b2007-08-09 01:39:01 +0000520 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000521 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000522 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000523
Devang Patel2545f7b2007-08-09 01:39:01 +0000524 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000525 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000526
527 Value *Op0 = I->getOperand(0);
528 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000529 PHINode *PN = NULL;
530 ConstantInt *CI = NULL;
531
532 if ((PN = dyn_cast<PHINode>(Op0))) {
533 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000534 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000535 } else
536 if ((PN = dyn_cast<PHINode>(Op1))) {
537 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000538 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000539 }
540
Devang Patel61571ca2007-08-10 00:33:50 +0000541 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000542 continue;
543 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000544
Devang Patelbc5fe632007-08-07 00:25:56 +0000545 // I is an Exit condition if next instruction is block terminator.
546 // Exit condition is OK if it compares loop invariant exit value,
547 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000548 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000549 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000550 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000551 }
552
Devang Patel61571ca2007-08-10 00:33:50 +0000553 if (I == ExitBlock->getTerminator())
554 continue;
555
Devang Patelbc5fe632007-08-07 00:25:56 +0000556 // Otherwise we have instruction that may not be safe.
557 return false;
558 }
559
Devang Patelbc5fe632007-08-07 00:25:56 +0000560 // We could not find any reason to consider ExitBlock unsafe.
561 return true;
562}
563
Devang Patel0aaeb172007-08-08 22:25:28 +0000564/// Find cost of spliting loop L. Cost is measured in terms of size growth.
565/// Size is growth is calculated based on amount of code duplicated in second
566/// loop.
567unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
568
569 unsigned Cost = 0;
570 BasicBlock *SDBlock = SD.SplitCondition->getParent();
571 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
572 I != E; ++I) {
573 BasicBlock *BB = *I;
574 // If a block is not dominated by split condition block then
575 // it must be duplicated in both loops.
576 if (!DT->dominates(SDBlock, BB))
577 Cost += BB->size();
578 }
579
580 return Cost;
581}
582
Devang Patelc8dadbf2007-08-08 21:02:17 +0000583bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000584
585 BasicBlock *Preheader = L->getLoopPreheader();
586
Devang Patel61571ca2007-08-10 00:33:50 +0000587 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000588
589 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000590 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000591 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000592 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000593 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
594 Value *TLExitValue = NULL;
595 Value *FLStartValue = NULL;
596 if (isa<ConstantInt>(SD.SplitValue)) {
597 TLExitValue = SD.SplitValue;
598 FLStartValue = SD.SplitValue;
599 }
600 else {
601 Value *C1 = new ICmpInst(SignedPredicate ?
602 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
603 SD.SplitValue, ExitValue, "lsplit.ev",
604 Preheader->getTerminator());
605 TLExitValue = new SelectInst(C1, SD.SplitValue, ExitValue,
606 "lsplit.ev", Preheader->getTerminator());
607
608 Value *C2 = new ICmpInst(SignedPredicate ?
609 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
610 SD.SplitValue, StartValue, "lsplit.sv",
611 Preheader->getTerminator());
612 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
613 "lsplit.sv", Preheader->getTerminator());
614 }
Devang Patel901f67e2007-08-10 18:07:13 +0000615
Devang Patel61571ca2007-08-10 00:33:50 +0000616 //[*] Split Exit Edge.
Devang Patel901f67e2007-08-10 18:07:13 +0000617 BasicBlock *ExitBlock = ExitCondition->getParent();
618 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
619 assert (ExitInsn && "Unable to find suitable loop exit branch");
620 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
621 if (L->contains(ExitDest))
622 ExitDest = ExitInsn->getSuccessor(0);
623 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
624 BasicBlock *ExitSplitBlock = SplitEdge(ExitBlock, ExitDest, this);
625
Devang Patel61571ca2007-08-10 00:33:50 +0000626 //[*] Clone loop. Avoid true destination of split condition and
627 // the blocks dominated by true destination.
Devang Patel901f67e2007-08-10 18:07:13 +0000628 DenseMap<const Value *, Value *> ValueMap;
629 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
630
Devang Patel61571ca2007-08-10 00:33:50 +0000631 //[*] True loops exit edge enters False loop.
632 //[*] Eliminate split condition's false branch from True loop.
633 // Update true loop dom info.
634 //[*] Update True loop's exit value using NewExitValue.
635 //[*] Update False loop's start value using NewStartValue.
636 //[*] Fix lack of true branch in False loop CFG.
637 // Update false loop dom info.
638 //[*] Update dom info in general.
Devang Patelbc5fe632007-08-07 00:25:56 +0000639 return false;
640}