blob: 02a812be0c2e4a43e60b9d94dd2a47ef5e07e427 [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 Patel6a2d6ef2007-08-12 07:02:51 +0000100 /// removeBlocks - Remove basic block BB and all blocks dominated by BB.
Devang Pateld79bfdd2007-08-13 22:22:13 +0000101 void removeBlocks(BasicBlock *InBB, Loop *LP);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000102
Devang Patel0aaeb172007-08-08 22:25:28 +0000103 /// Find cost of spliting loop L.
104 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000105 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000106
Devang Patel61571ca2007-08-10 00:33:50 +0000107 void initialize() {
108 IndVar = NULL;
109 IndVarIncrement = NULL;
110 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000111 StartValue = NULL;
112 ExitValueNum = 0;
113 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000114 }
115
Devang Patelbc5fe632007-08-07 00:25:56 +0000116 private:
117
118 // Current Loop.
119 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000120 LPPassManager *LPM;
121 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000122 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000123 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000124 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000125 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000126
127 // Induction variable whose range is being split by this transformation.
128 PHINode *IndVar;
129 Instruction *IndVarIncrement;
130
131 // Loop exit condition.
132 ICmpInst *ExitCondition;
133
134 // Induction variable's initial value.
135 Value *StartValue;
136
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000137 // Induction variable's final loop exit value operand number in exit condition..
138 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000139 };
140
141 char LoopIndexSplit::ID = 0;
142 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
143}
144
145LoopPass *llvm::createLoopIndexSplitPass() {
146 return new LoopIndexSplit();
147}
148
149// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000150bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000151 bool Changed = false;
152 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000153 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000154
Devang Patelbc5fe632007-08-07 00:25:56 +0000155 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000156 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000157 LI = &getAnalysis<LoopInfo>();
Devang Patelb7639612007-08-13 22:13:24 +0000158 DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000159
Devang Patel61571ca2007-08-10 00:33:50 +0000160 initialize();
161
162 findLoopConditionals();
163
164 if (!ExitCondition)
165 return false;
166
Devang Patelbc5fe632007-08-07 00:25:56 +0000167 findSplitCondition();
168
Devang Patelc8dadbf2007-08-08 21:02:17 +0000169 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000170 return false;
171
Devang Patelc8dadbf2007-08-08 21:02:17 +0000172 // First see if it is possible to eliminate loop itself or not.
173 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
174 E = SplitData.end(); SI != E; ++SI) {
175 SplitInfo &SD = *SI;
176 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000177 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000178 if (Changed) {
179 ++NumIndexSplit;
180 // If is loop is eliminated then nothing else to do here.
181 return Changed;
182 }
183 }
184 }
185
Devang Patel0aaeb172007-08-08 22:25:28 +0000186 unsigned MaxCost = 99;
187 unsigned Index = 0;
188 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000189 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000190 E = SplitData.end(); SI != E; ++SI, ++Index) {
191 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000192
193 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000194 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000195 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000196
197 unsigned Cost = findSplitCost(L, SD);
198 if (Cost < MaxCost)
199 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000200 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000201
Devang Patel0aaeb172007-08-08 22:25:28 +0000202 // Split most profitiable condition.
203 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
204
Devang Patelbc5fe632007-08-07 00:25:56 +0000205 if (Changed)
206 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000207
Devang Patelbc5fe632007-08-07 00:25:56 +0000208 return Changed;
209}
210
Devang Patel2545f7b2007-08-09 01:39:01 +0000211/// Return true if V is a induction variable or induction variable's
212/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000213void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000214
215 Instruction *I = dyn_cast<Instruction>(V);
216 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000217 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000218
219 // Check if I is a phi node from loop header or not.
220 if (PHINode *PN = dyn_cast<PHINode>(V)) {
221 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000222 IndVar = PN;
223 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000224 }
225 }
226
227 // Check if I is a add instruction whose one operand is
228 // phi node from loop header and second operand is constant.
229 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000230 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000231
232 Value *Op0 = I->getOperand(0);
233 Value *Op1 = I->getOperand(1);
234
235 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
236 if (PN->getParent() == L->getHeader()
237 && isa<ConstantInt>(Op1)) {
238 IndVar = PN;
239 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000240 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000241 }
242 }
243
244 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
245 if (PN->getParent() == L->getHeader()
246 && isa<ConstantInt>(Op0)) {
247 IndVar = PN;
248 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000249 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000250 }
251 }
252
Devang Patel61571ca2007-08-10 00:33:50 +0000253 return;
254}
255
256// Find loop's exit condition and associated induction variable.
257void LoopIndexSplit::findLoopConditionals() {
258
259 BasicBlock *ExitBlock = NULL;
260
261 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
262 I != E; ++I) {
263 BasicBlock *BB = *I;
264 if (!L->isLoopExit(BB))
265 continue;
266 if (ExitBlock)
267 return;
268 ExitBlock = BB;
269 }
270
271 if (!ExitBlock)
272 return;
273
274 // If exit block's terminator is conditional branch inst then we have found
275 // exit condition.
276 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
277 if (!BR || BR->isUnconditional())
278 return;
279
280 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
281 if (!CI)
282 return;
283
284 ExitCondition = CI;
285
286 // Exit condition's one operand is loop invariant exit value and second
287 // operand is SCEVAddRecExpr based on induction variable.
288 Value *V0 = CI->getOperand(0);
289 Value *V1 = CI->getOperand(1);
290
291 SCEVHandle SH0 = SE->getSCEV(V0);
292 SCEVHandle SH1 = SE->getSCEV(V1);
293
294 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000295 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000296 findIndVar(V1, L);
297 }
298 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000299 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000300 findIndVar(V0, L);
301 }
302
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000303 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000304 ExitCondition = NULL;
305 else if (IndVar) {
306 BasicBlock *Preheader = L->getLoopPreheader();
307 StartValue = IndVar->getIncomingValueForBlock(Preheader);
308 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000309}
310
Devang Patelbc5fe632007-08-07 00:25:56 +0000311/// Find condition inside a loop that is suitable candidate for index split.
312void LoopIndexSplit::findSplitCondition() {
313
Devang Patelc8dadbf2007-08-08 21:02:17 +0000314 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000315 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000316
Devang Patel2545f7b2007-08-09 01:39:01 +0000317 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
318 I != E; ++I) {
319 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000320
Devang Patel2545f7b2007-08-09 01:39:01 +0000321 // If this basic block does not terminate in a conditional branch
322 // then terminator is not a suitable split condition.
323 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
324 if (!BR)
325 continue;
326
327 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000328 continue;
329
Devang Patel2545f7b2007-08-09 01:39:01 +0000330 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000331 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000332 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000333
Devang Patel2545f7b2007-08-09 01:39:01 +0000334 // If one operand is loop invariant and second operand is SCEVAddRecExpr
335 // based on induction variable then CI is a candidate split condition.
336 Value *V0 = CI->getOperand(0);
337 Value *V1 = CI->getOperand(1);
338
339 SCEVHandle SH0 = SE->getSCEV(V0);
340 SCEVHandle SH1 = SE->getSCEV(V1);
341
342 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
343 SD.SplitValue = V0;
344 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000345 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
346 if (PN == IndVar)
347 SplitData.push_back(SD);
348 }
349 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
350 if (IndVarIncrement && IndVarIncrement == Insn)
351 SplitData.push_back(SD);
352 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000353 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000354 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
355 SD.SplitValue = V1;
356 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000357 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
358 if (PN == IndVar)
359 SplitData.push_back(SD);
360 }
361 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
362 if (IndVarIncrement && IndVarIncrement == Insn)
363 SplitData.push_back(SD);
364 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000365 }
366 }
367}
368
369/// processOneIterationLoop - Current loop L contains compare instruction
370/// that compares induction variable, IndVar, against loop invariant. If
371/// entire (i.e. meaningful) loop body is dominated by this compare
372/// instruction then loop body is executed only once. In such case eliminate
373/// loop structure surrounding this loop body. For example,
374/// for (int i = start; i < end; ++i) {
375/// if ( i == somevalue) {
376/// loop_body
377/// }
378/// }
379/// can be transformed into
380/// if (somevalue >= start && somevalue < end) {
381/// i = somevalue;
382/// loop_body
383/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000384bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000385
386 BasicBlock *Header = L->getHeader();
387
388 // First of all, check if SplitCondition dominates entire loop body
389 // or not.
390
391 // If SplitCondition is not in loop header then this loop is not suitable
392 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000393 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000394 return false;
395
Devang Patelbc5fe632007-08-07 00:25:56 +0000396 // If loop header includes loop variant instruction operands then
397 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000398 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000399 return false;
400
401 // If Exit block includes loop variant instructions then this
402 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000403 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000404 return false;
405
Devang Patel2bcb5012007-08-08 01:51:27 +0000406 // Update CFG.
407
408 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000409 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000410 BasicBlock *LatchSucc = NULL;
411 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
412 if (!BR)
413 return false;
414 Header->removePredecessor(Latch);
415 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
416 SI != E; ++SI) {
417 if (Header != *SI)
418 LatchSucc = *SI;
419 }
420 BR->setUnconditionalDest(LatchSucc);
421
Devang Patelbc5fe632007-08-07 00:25:56 +0000422 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000423 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000424
Devang Patelbc5fe632007-08-07 00:25:56 +0000425 // Replace split condition in header.
426 // Transform
427 // SplitCondition : icmp eq i32 IndVar, SplitValue
428 // into
429 // c1 = icmp uge i32 SplitValue, StartValue
430 // c2 = icmp ult i32 vSplitValue, ExitValue
431 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000432 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000433 Instruction *C1 = new ICmpInst(SignedPredicate ?
434 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000435 SD.SplitValue, StartValue, "lisplit",
436 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000437 Instruction *C2 = new ICmpInst(SignedPredicate ?
438 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000439 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000440 Terminator);
441 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
442 Terminator);
443 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
444 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000445
Devang Patelbc5fe632007-08-07 00:25:56 +0000446 // Now, clear latch block. Remove instructions that are responsible
447 // to increment induction variable.
448 Instruction *LTerminator = Latch->getTerminator();
449 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
450 LB != LE; ) {
451 Instruction *I = LB;
452 ++LB;
453 if (isa<PHINode>(I) || I == LTerminator)
454 continue;
455
Devang Patel59e0c062007-08-14 01:30:57 +0000456 if (I == IndVarIncrement)
457 I->replaceAllUsesWith(ExitValue);
458 else
459 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000460 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000461 }
462
Devang Patel901f67e2007-08-10 18:07:13 +0000463 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000464
465 // Update Dominator Info.
466 // Only CFG change done is to remove Latch to Header edge. This
467 // does not change dominator tree because Latch did not dominate
468 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000469 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000470 DominanceFrontier::iterator HeaderDF = DF->find(Header);
471 if (HeaderDF != DF->end())
472 DF->removeFromFrontier(HeaderDF, Header);
473
474 DominanceFrontier::iterator LatchDF = DF->find(Latch);
475 if (LatchDF != DF->end())
476 DF->removeFromFrontier(LatchDF, Header);
477 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000478 return true;
479}
480
481// If loop header includes loop variant instruction operands then
482// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000483bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000484
485 Instruction *Terminator = Header->getTerminator();
486 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
487 BI != BE; ++BI) {
488 Instruction *I = BI;
489
Devang Patel59e0c062007-08-14 01:30:57 +0000490 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000491 if (isa<PHINode>(I))
492 continue;
493
494 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000495 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000496 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000497
Devang Patel2545f7b2007-08-09 01:39:01 +0000498 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000499 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000500 continue;
501
502 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000503 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000504 continue;
505
Devang Patelbc5fe632007-08-07 00:25:56 +0000506 // Terminator is also harmless.
507 if (I == Terminator)
508 continue;
509
510 // Otherwise we have a instruction that may not be safe.
511 return false;
512 }
513
514 return true;
515}
516
517// If Exit block includes loop variant instructions then this
518// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000519bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000520
Devang Patelbc5fe632007-08-07 00:25:56 +0000521 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
522 BI != BE; ++BI) {
523 Instruction *I = BI;
524
Devang Patel59e0c062007-08-14 01:30:57 +0000525 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000526 if (isa<PHINode>(I))
527 continue;
528
Devang Patel2545f7b2007-08-09 01:39:01 +0000529 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000530 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000531 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000532
Devang Patel2545f7b2007-08-09 01:39:01 +0000533 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000534 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000535
536 Value *Op0 = I->getOperand(0);
537 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000538 PHINode *PN = NULL;
539 ConstantInt *CI = NULL;
540
541 if ((PN = dyn_cast<PHINode>(Op0))) {
542 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000543 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000544 } else
545 if ((PN = dyn_cast<PHINode>(Op1))) {
546 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000547 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000548 }
549
Devang Patel61571ca2007-08-10 00:33:50 +0000550 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000551 continue;
552 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000553
Devang Patelbc5fe632007-08-07 00:25:56 +0000554 // I is an Exit condition if next instruction is block terminator.
555 // Exit condition is OK if it compares loop invariant exit value,
556 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000557 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000558 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000559 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000560 }
561
Devang Patel61571ca2007-08-10 00:33:50 +0000562 if (I == ExitBlock->getTerminator())
563 continue;
564
Devang Patelbc5fe632007-08-07 00:25:56 +0000565 // Otherwise we have instruction that may not be safe.
566 return false;
567 }
568
Devang Patelbc5fe632007-08-07 00:25:56 +0000569 // We could not find any reason to consider ExitBlock unsafe.
570 return true;
571}
572
Devang Patel0aaeb172007-08-08 22:25:28 +0000573/// Find cost of spliting loop L. Cost is measured in terms of size growth.
574/// Size is growth is calculated based on amount of code duplicated in second
575/// loop.
576unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
577
578 unsigned Cost = 0;
579 BasicBlock *SDBlock = SD.SplitCondition->getParent();
580 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
581 I != E; ++I) {
582 BasicBlock *BB = *I;
583 // If a block is not dominated by split condition block then
584 // it must be duplicated in both loops.
585 if (!DT->dominates(SDBlock, BB))
586 Cost += BB->size();
587 }
588
589 return Cost;
590}
591
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000592/// removeBlocks - Remove basic block BB and all blocks dominated by BB.
Devang Pateld79bfdd2007-08-13 22:22:13 +0000593void LoopIndexSplit::removeBlocks(BasicBlock *InBB, Loop *LP) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000594
Devang Patelb7639612007-08-13 22:13:24 +0000595 SmallVector<std::pair<BasicBlock *, succ_iterator>, 8> WorkList;
596 WorkList.push_back(std::make_pair(InBB, succ_begin(InBB)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000597 while (!WorkList.empty()) {
Devang Patelb7639612007-08-13 22:13:24 +0000598 BasicBlock *BB = WorkList.back(). first;
599 succ_iterator SIter =WorkList.back().second;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000600
Devang Patelb7639612007-08-13 22:13:24 +0000601 // If all successor's are processed then remove this block.
602 if (SIter == succ_end(BB)) {
603 WorkList.pop_back();
604 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
605 BBI != BBE; ++BBI) {
606 Instruction *I = BBI;
607 I->replaceAllUsesWith(UndefValue::get(I->getType()));
608 I->eraseFromParent();
609 }
Devang Pateld79bfdd2007-08-13 22:22:13 +0000610 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patelb7639612007-08-13 22:13:24 +0000611 DT->eraseNode(BB);
612 DF->removeBlock(BB);
613 LI->removeBlock(BB);
614 BB->eraseFromParent();
615 } else {
616 BasicBlock *SuccBB = *SIter;
617 ++WorkList.back().second;
618
619 if (DT->dominates(BB, SuccBB)) {
620 WorkList.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
621 continue;
622 } else {
623 // If SuccBB is not dominated by BB then it is not removed, however remove
624 // any PHI incoming edge from BB.
625 for(BasicBlock::iterator SBI = SuccBB->begin(), SBE = SuccBB->end();
626 SBI != SBE; ++SBI) {
627 if (PHINode *PN = dyn_cast<PHINode>(SBI))
628 PN->removeIncomingValue(BB);
629 else
630 break;
631 }
632
633 // If BB is not dominating SuccBB then SuccBB is in BB's dominance
634 // frontiner.
635 DominanceFrontier::iterator BBDF = DF->find(BB);
636 DF->removeFromFrontier(BBDF, SuccBB);
637 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000638 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000639 }
640}
641
Devang Patelc8dadbf2007-08-08 21:02:17 +0000642bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000643
644 BasicBlock *Preheader = L->getLoopPreheader();
645
Devang Patel61571ca2007-08-10 00:33:50 +0000646 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000647
648 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000649 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000650 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000651 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000652 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
653 Value *TLExitValue = NULL;
654 Value *FLStartValue = NULL;
655 if (isa<ConstantInt>(SD.SplitValue)) {
656 TLExitValue = SD.SplitValue;
657 FLStartValue = SD.SplitValue;
658 }
659 else {
660 Value *C1 = new ICmpInst(SignedPredicate ?
661 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000662 SD.SplitValue,
663 ExitCondition->getOperand(ExitValueNum),
664 "lsplit.ev",
Devang Patelf824fb42007-08-10 00:53:35 +0000665 Preheader->getTerminator());
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000666 TLExitValue = new SelectInst(C1, SD.SplitValue,
667 ExitCondition->getOperand(ExitValueNum),
Devang Patelf824fb42007-08-10 00:53:35 +0000668 "lsplit.ev", Preheader->getTerminator());
669
670 Value *C2 = new ICmpInst(SignedPredicate ?
671 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
672 SD.SplitValue, StartValue, "lsplit.sv",
673 Preheader->getTerminator());
674 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
675 "lsplit.sv", Preheader->getTerminator());
676 }
Devang Patel901f67e2007-08-10 18:07:13 +0000677
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000678 //[*] Clone loop. Avoid true destination of split condition and
679 // the blocks dominated by true destination.
680 DenseMap<const Value *, Value *> ValueMap;
681 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
682 BasicBlock *FalseHeader = FalseLoop->getHeader();
683
684 //[*] True loop's exit edge enters False loop.
685 PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
Devang Patel901f67e2007-08-10 18:07:13 +0000686 BasicBlock *ExitBlock = ExitCondition->getParent();
687 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
688 assert (ExitInsn && "Unable to find suitable loop exit branch");
689 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000690
Devang Patel59e0c062007-08-14 01:30:57 +0000691 if (L->contains(ExitDest)) {
692 ExitDest = ExitInsn->getSuccessor(0);
693 ExitInsn->setSuccessor(0, FalseHeader);
694 } else
695 ExitInsn->setSuccessor(1, FalseHeader);
696
697 // Collect inverse map of Header PHINodes.
698 DenseMap<Value *, Value *> InverseMap;
699 for (BasicBlock::iterator BI = L->getHeader()->begin(),
700 BE = L->getHeader()->end(); BI != BE; ++BI) {
701 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
702 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
703 InverseMap[PNClone] = PN;
704 } else
705 break;
706 }
707
708 // Update False loop's header
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000709 for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
710 BI != BE; ++BI) {
711 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
712 PN->removeIncomingValue(Preheader);
713 if (PN == IndVarClone)
714 PN->addIncoming(FLStartValue, ExitBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000715 else {
716 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
717 Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
718 PN->addIncoming(V2, ExitBlock);
719 }
720 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000721 break;
722 }
723
Devang Patel59e0c062007-08-14 01:30:57 +0000724 // Update ExitDest. Now it's predecessor is False loop's exit block.
725 BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
726 for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
727 BI != BE; ++BI) {
728 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
729 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
730 PN->removeIncomingValue(ExitBlock);
731 } else
732 break;
733 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000734
Devang Patelb7639612007-08-13 22:13:24 +0000735 if (DT) {
736 DT->changeImmediateDominator(FalseHeader, ExitBlock);
737 DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
738 }
739
Devang Patel901f67e2007-08-10 18:07:13 +0000740 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
Devang Patel901f67e2007-08-10 18:07:13 +0000741
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000742 //[*] Split Exit Edge.
743 SplitEdge(ExitBlock, FalseHeader, this);
Devang Patel901f67e2007-08-10 18:07:13 +0000744
Devang Patel61571ca2007-08-10 00:33:50 +0000745 //[*] Eliminate split condition's false branch from True loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000746 BasicBlock *SplitBlock = SD.SplitCondition->getParent();
747 BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
748 BasicBlock *FBB = BR->getSuccessor(1);
749 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Pateld79bfdd2007-08-13 22:22:13 +0000750 removeBlocks(FBB, L);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000751
752 //[*] Update True loop's exit value using new exit value.
753 ExitCondition->setOperand(ExitValueNum, TLExitValue);
754
755 //[*] Eliminate split condition's true branch in False loop CFG.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000756 BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
757 BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
758 BasicBlock *TBB = FBR->getSuccessor(0);
759 FBR->setUnconditionalDest(FBR->getSuccessor(1));
Devang Pateld79bfdd2007-08-13 22:22:13 +0000760 removeBlocks(TBB, FalseLoop);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000761
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000762 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000763}
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000764