blob: 56fc8d588476ca019808258cbb08d6fbc7dfb3cc [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"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel95fd7172007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel901f67e2007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
23#include "llvm/ADT/Statistic.h"
24
25using namespace llvm;
26
27STATISTIC(NumIndexSplit, "Number of loops index split");
28
29namespace {
30
31 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
32
33 public:
34 static char ID; // Pass ID, replacement for typeid
35 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
36
37 // Index split Loop L. Return true if loop is split.
38 bool runOnLoop(Loop *L, LPPassManager &LPM);
39
40 void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<ScalarEvolution>();
42 AU.addPreserved<ScalarEvolution>();
43 AU.addRequiredID(LCSSAID);
44 AU.addPreservedID(LCSSAID);
Devang Patel901f67e2007-08-10 18:07:13 +000045 AU.addRequired<LoopInfo>();
Devang Patelbc5fe632007-08-07 00:25:56 +000046 AU.addPreserved<LoopInfo>();
47 AU.addRequiredID(LoopSimplifyID);
48 AU.addPreservedID(LoopSimplifyID);
Devang Patel0aaeb172007-08-08 22:25:28 +000049 AU.addRequired<DominatorTree>();
Devang Patel95fd7172007-08-08 21:39:47 +000050 AU.addPreserved<DominatorTree>();
51 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000052 }
53
54 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000055
56 class SplitInfo {
57 public:
Devang Patel61571ca2007-08-10 00:33:50 +000058 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000059
Devang Patelc8dadbf2007-08-08 21:02:17 +000060 // Induction variable's range is split at this value.
61 Value *SplitValue;
62
Devang Patelc8dadbf2007-08-08 21:02:17 +000063 // This compare instruction compares IndVar against SplitValue.
64 ICmpInst *SplitCondition;
65
Devang Patel31696332007-08-08 21:18:27 +000066 // Clear split info.
67 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000068 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000069 SplitCondition = NULL;
Devang Patel31696332007-08-08 21:18:27 +000070 }
Devang Patel2545f7b2007-08-09 01:39:01 +000071
Devang Patelc8dadbf2007-08-08 21:02:17 +000072 };
Devang Patel61571ca2007-08-10 00:33:50 +000073
Devang Patelc8dadbf2007-08-08 21:02:17 +000074 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000075 /// Find condition inside a loop that is suitable candidate for index split.
76 void findSplitCondition();
77
Devang Patel61571ca2007-08-10 00:33:50 +000078 /// Find loop's exit condition.
79 void findLoopConditionals();
80
81 /// Return induction variable associated with value V.
82 void findIndVar(Value *V, Loop *L);
83
Devang Patelbc5fe632007-08-07 00:25:56 +000084 /// processOneIterationLoop - Current loop L contains compare instruction
85 /// that compares induction variable, IndVar, agains loop invariant. If
86 /// entire (i.e. meaningful) loop body is dominated by this compare
87 /// instruction then loop body is executed only for one iteration. In
88 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +000089 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +000090
Devang Patel0aaeb172007-08-08 22:25:28 +000091 /// If loop header includes loop variant instruction operands then
92 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000093 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000094
Devang Patel0aaeb172007-08-08 22:25:28 +000095 /// If Exit block includes loop variant instructions then this
96 /// loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000097 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000098
Devang Patel60a94c72007-08-14 18:35:57 +000099 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
100 /// This routine is used to remove split condition's dead branch, dominated by
101 /// DeadBB. LiveBB dominates split conidition's other branch.
102 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000103
Devang Patel0aaeb172007-08-08 22:25:28 +0000104 /// Find cost of spliting loop L.
105 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000106 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000107
Devang Patel61571ca2007-08-10 00:33:50 +0000108 void initialize() {
109 IndVar = NULL;
110 IndVarIncrement = NULL;
111 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000112 StartValue = NULL;
113 ExitValueNum = 0;
114 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000115 }
116
Devang Patelbc5fe632007-08-07 00:25:56 +0000117 private:
118
119 // Current Loop.
120 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000121 LPPassManager *LPM;
122 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000123 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000124 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000125 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000126 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000127
128 // Induction variable whose range is being split by this transformation.
129 PHINode *IndVar;
130 Instruction *IndVarIncrement;
131
132 // Loop exit condition.
133 ICmpInst *ExitCondition;
134
135 // Induction variable's initial value.
136 Value *StartValue;
137
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000138 // Induction variable's final loop exit value operand number in exit condition..
139 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000140 };
141
142 char LoopIndexSplit::ID = 0;
143 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
144}
145
146LoopPass *llvm::createLoopIndexSplitPass() {
147 return new LoopIndexSplit();
148}
149
150// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000151bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000152 bool Changed = false;
153 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000154 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000155
Devang Patel81fcdfb2007-08-15 02:14:55 +0000156 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000157 if (!L->getSubLoops().empty())
158 return false;
159
Devang Patelbc5fe632007-08-07 00:25:56 +0000160 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000161 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000162 LI = &getAnalysis<LoopInfo>();
Devang Patelb7639612007-08-13 22:13:24 +0000163 DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000164
Devang Patel61571ca2007-08-10 00:33:50 +0000165 initialize();
166
167 findLoopConditionals();
168
169 if (!ExitCondition)
170 return false;
171
Devang Patelbc5fe632007-08-07 00:25:56 +0000172 findSplitCondition();
173
Devang Patelc8dadbf2007-08-08 21:02:17 +0000174 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000175 return false;
176
Devang Patelc8dadbf2007-08-08 21:02:17 +0000177 // First see if it is possible to eliminate loop itself or not.
178 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
179 E = SplitData.end(); SI != E; ++SI) {
180 SplitInfo &SD = *SI;
181 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000182 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000183 if (Changed) {
184 ++NumIndexSplit;
185 // If is loop is eliminated then nothing else to do here.
186 return Changed;
187 }
188 }
189 }
190
Devang Patel0aaeb172007-08-08 22:25:28 +0000191 unsigned MaxCost = 99;
192 unsigned Index = 0;
193 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000194 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000195 E = SplitData.end(); SI != E; ++SI, ++Index) {
196 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000197
198 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000199 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000200 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000201
202 unsigned Cost = findSplitCost(L, SD);
203 if (Cost < MaxCost)
204 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000205 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000206
Devang Patel0aaeb172007-08-08 22:25:28 +0000207 // Split most profitiable condition.
208 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
209
Devang Patelbc5fe632007-08-07 00:25:56 +0000210 if (Changed)
211 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000212
Devang Patelbc5fe632007-08-07 00:25:56 +0000213 return Changed;
214}
215
Devang Patel2545f7b2007-08-09 01:39:01 +0000216/// Return true if V is a induction variable or induction variable's
217/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000218void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000219
220 Instruction *I = dyn_cast<Instruction>(V);
221 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000222 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000223
224 // Check if I is a phi node from loop header or not.
225 if (PHINode *PN = dyn_cast<PHINode>(V)) {
226 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000227 IndVar = PN;
228 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000229 }
230 }
231
232 // Check if I is a add instruction whose one operand is
233 // phi node from loop header and second operand is constant.
234 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000235 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000236
237 Value *Op0 = I->getOperand(0);
238 Value *Op1 = I->getOperand(1);
239
240 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
241 if (PN->getParent() == L->getHeader()
242 && isa<ConstantInt>(Op1)) {
243 IndVar = PN;
244 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000245 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000246 }
247 }
248
249 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
250 if (PN->getParent() == L->getHeader()
251 && isa<ConstantInt>(Op0)) {
252 IndVar = PN;
253 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000254 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000255 }
256 }
257
Devang Patel61571ca2007-08-10 00:33:50 +0000258 return;
259}
260
261// Find loop's exit condition and associated induction variable.
262void LoopIndexSplit::findLoopConditionals() {
263
264 BasicBlock *ExitBlock = NULL;
265
266 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
267 I != E; ++I) {
268 BasicBlock *BB = *I;
269 if (!L->isLoopExit(BB))
270 continue;
271 if (ExitBlock)
272 return;
273 ExitBlock = BB;
274 }
275
276 if (!ExitBlock)
277 return;
278
279 // If exit block's terminator is conditional branch inst then we have found
280 // exit condition.
281 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
282 if (!BR || BR->isUnconditional())
283 return;
284
285 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
286 if (!CI)
287 return;
288
289 ExitCondition = CI;
290
291 // Exit condition's one operand is loop invariant exit value and second
292 // operand is SCEVAddRecExpr based on induction variable.
293 Value *V0 = CI->getOperand(0);
294 Value *V1 = CI->getOperand(1);
295
296 SCEVHandle SH0 = SE->getSCEV(V0);
297 SCEVHandle SH1 = SE->getSCEV(V1);
298
299 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000300 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000301 findIndVar(V1, L);
302 }
303 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000304 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000305 findIndVar(V0, L);
306 }
307
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000308 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000309 ExitCondition = NULL;
310 else if (IndVar) {
311 BasicBlock *Preheader = L->getLoopPreheader();
312 StartValue = IndVar->getIncomingValueForBlock(Preheader);
313 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000314}
315
Devang Patelbc5fe632007-08-07 00:25:56 +0000316/// Find condition inside a loop that is suitable candidate for index split.
317void LoopIndexSplit::findSplitCondition() {
318
Devang Patelc8dadbf2007-08-08 21:02:17 +0000319 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000320 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000321
Devang Patel2545f7b2007-08-09 01:39:01 +0000322 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
323 I != E; ++I) {
324 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000325
Devang Patel2545f7b2007-08-09 01:39:01 +0000326 // If this basic block does not terminate in a conditional branch
327 // then terminator is not a suitable split condition.
328 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
329 if (!BR)
330 continue;
331
332 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000333 continue;
334
Devang Patel2545f7b2007-08-09 01:39:01 +0000335 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000336 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000337 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000338
Devang Patel2545f7b2007-08-09 01:39:01 +0000339 // If one operand is loop invariant and second operand is SCEVAddRecExpr
340 // based on induction variable then CI is a candidate split condition.
341 Value *V0 = CI->getOperand(0);
342 Value *V1 = CI->getOperand(1);
343
344 SCEVHandle SH0 = SE->getSCEV(V0);
345 SCEVHandle SH1 = SE->getSCEV(V1);
346
347 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
348 SD.SplitValue = V0;
349 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000350 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
351 if (PN == IndVar)
352 SplitData.push_back(SD);
353 }
354 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
355 if (IndVarIncrement && IndVarIncrement == Insn)
356 SplitData.push_back(SD);
357 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000358 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000359 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
360 SD.SplitValue = V1;
361 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000362 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
363 if (PN == IndVar)
364 SplitData.push_back(SD);
365 }
366 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
367 if (IndVarIncrement && IndVarIncrement == Insn)
368 SplitData.push_back(SD);
369 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000370 }
371 }
372}
373
374/// processOneIterationLoop - Current loop L contains compare instruction
375/// that compares induction variable, IndVar, against loop invariant. If
376/// entire (i.e. meaningful) loop body is dominated by this compare
377/// instruction then loop body is executed only once. In such case eliminate
378/// loop structure surrounding this loop body. For example,
379/// for (int i = start; i < end; ++i) {
380/// if ( i == somevalue) {
381/// loop_body
382/// }
383/// }
384/// can be transformed into
385/// if (somevalue >= start && somevalue < end) {
386/// i = somevalue;
387/// loop_body
388/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000389bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000390
391 BasicBlock *Header = L->getHeader();
392
393 // First of all, check if SplitCondition dominates entire loop body
394 // or not.
395
396 // If SplitCondition is not in loop header then this loop is not suitable
397 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000398 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000399 return false;
400
Devang Patelbc5fe632007-08-07 00:25:56 +0000401 // If loop header includes loop variant instruction operands then
402 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000403 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000404 return false;
405
406 // If Exit block includes loop variant instructions then this
407 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000408 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000409 return false;
410
Devang Patel2bcb5012007-08-08 01:51:27 +0000411 // Update CFG.
412
413 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000414 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000415 BasicBlock *LatchSucc = NULL;
416 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
417 if (!BR)
418 return false;
419 Header->removePredecessor(Latch);
420 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
421 SI != E; ++SI) {
422 if (Header != *SI)
423 LatchSucc = *SI;
424 }
425 BR->setUnconditionalDest(LatchSucc);
426
Devang Patelbc5fe632007-08-07 00:25:56 +0000427 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000428 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000429
Devang Patelbc5fe632007-08-07 00:25:56 +0000430 // Replace split condition in header.
431 // Transform
432 // SplitCondition : icmp eq i32 IndVar, SplitValue
433 // into
434 // c1 = icmp uge i32 SplitValue, StartValue
435 // c2 = icmp ult i32 vSplitValue, ExitValue
436 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000437 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000438 Instruction *C1 = new ICmpInst(SignedPredicate ?
439 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000440 SD.SplitValue, StartValue, "lisplit",
441 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000442 Instruction *C2 = new ICmpInst(SignedPredicate ?
443 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000444 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000445 Terminator);
446 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
447 Terminator);
448 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
449 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000450
Devang Patelbc5fe632007-08-07 00:25:56 +0000451 // Now, clear latch block. Remove instructions that are responsible
452 // to increment induction variable.
453 Instruction *LTerminator = Latch->getTerminator();
454 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
455 LB != LE; ) {
456 Instruction *I = LB;
457 ++LB;
458 if (isa<PHINode>(I) || I == LTerminator)
459 continue;
460
Devang Patel59e0c062007-08-14 01:30:57 +0000461 if (I == IndVarIncrement)
462 I->replaceAllUsesWith(ExitValue);
463 else
464 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000465 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000466 }
467
Devang Patel901f67e2007-08-10 18:07:13 +0000468 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000469
470 // Update Dominator Info.
471 // Only CFG change done is to remove Latch to Header edge. This
472 // does not change dominator tree because Latch did not dominate
473 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000474 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000475 DominanceFrontier::iterator HeaderDF = DF->find(Header);
476 if (HeaderDF != DF->end())
477 DF->removeFromFrontier(HeaderDF, Header);
478
479 DominanceFrontier::iterator LatchDF = DF->find(Latch);
480 if (LatchDF != DF->end())
481 DF->removeFromFrontier(LatchDF, Header);
482 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000483 return true;
484}
485
486// If loop header includes loop variant instruction operands then
487// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000488bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000489
490 Instruction *Terminator = Header->getTerminator();
491 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
492 BI != BE; ++BI) {
493 Instruction *I = BI;
494
Devang Patel59e0c062007-08-14 01:30:57 +0000495 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000496 if (isa<PHINode>(I))
497 continue;
498
499 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000500 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000501 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000502
Devang Patel2545f7b2007-08-09 01:39:01 +0000503 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000504 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000505 continue;
506
507 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000508 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000509 continue;
510
Devang Patelbc5fe632007-08-07 00:25:56 +0000511 // Terminator is also harmless.
512 if (I == Terminator)
513 continue;
514
515 // Otherwise we have a instruction that may not be safe.
516 return false;
517 }
518
519 return true;
520}
521
522// If Exit block includes loop variant instructions then this
523// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000524bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000525
Devang Patelbc5fe632007-08-07 00:25:56 +0000526 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
527 BI != BE; ++BI) {
528 Instruction *I = BI;
529
Devang Patel59e0c062007-08-14 01:30:57 +0000530 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000531 if (isa<PHINode>(I))
532 continue;
533
Devang Patel2545f7b2007-08-09 01:39:01 +0000534 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000535 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000536 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000537
Devang Patel2545f7b2007-08-09 01:39:01 +0000538 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000539 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000540
541 Value *Op0 = I->getOperand(0);
542 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000543 PHINode *PN = NULL;
544 ConstantInt *CI = NULL;
545
546 if ((PN = dyn_cast<PHINode>(Op0))) {
547 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000548 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000549 } else
550 if ((PN = dyn_cast<PHINode>(Op1))) {
551 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000552 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000553 }
554
Devang Patel61571ca2007-08-10 00:33:50 +0000555 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000556 continue;
557 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000558
Devang Patelbc5fe632007-08-07 00:25:56 +0000559 // I is an Exit condition if next instruction is block terminator.
560 // Exit condition is OK if it compares loop invariant exit value,
561 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000562 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000563 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000564 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000565 }
566
Devang Patel61571ca2007-08-10 00:33:50 +0000567 if (I == ExitBlock->getTerminator())
568 continue;
569
Devang Patelbc5fe632007-08-07 00:25:56 +0000570 // Otherwise we have instruction that may not be safe.
571 return false;
572 }
573
Devang Patelbc5fe632007-08-07 00:25:56 +0000574 // We could not find any reason to consider ExitBlock unsafe.
575 return true;
576}
577
Devang Patel0aaeb172007-08-08 22:25:28 +0000578/// Find cost of spliting loop L. Cost is measured in terms of size growth.
579/// Size is growth is calculated based on amount of code duplicated in second
580/// loop.
581unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
582
583 unsigned Cost = 0;
584 BasicBlock *SDBlock = SD.SplitCondition->getParent();
585 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
586 I != E; ++I) {
587 BasicBlock *BB = *I;
588 // If a block is not dominated by split condition block then
589 // it must be duplicated in both loops.
590 if (!DT->dominates(SDBlock, BB))
591 Cost += BB->size();
592 }
593
594 return Cost;
595}
596
Devang Patel60a94c72007-08-14 18:35:57 +0000597/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
598/// This routine is used to remove split condition's dead branch, dominated by
599/// DeadBB. LiveBB dominates split conidition's other branch.
600void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
601 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000602
Devang Patelb7639612007-08-13 22:13:24 +0000603 SmallVector<std::pair<BasicBlock *, succ_iterator>, 8> WorkList;
Devang Patel60a94c72007-08-14 18:35:57 +0000604 WorkList.push_back(std::make_pair(DeadBB, succ_begin(DeadBB)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000605 while (!WorkList.empty()) {
Devang Patelb7639612007-08-13 22:13:24 +0000606 BasicBlock *BB = WorkList.back(). first;
Devang Patel81fcdfb2007-08-15 02:14:55 +0000607 succ_iterator SIter = WorkList.back().second;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000608
Devang Patelb7639612007-08-13 22:13:24 +0000609 // If all successor's are processed then remove this block.
610 if (SIter == succ_end(BB)) {
611 WorkList.pop_back();
612 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
613 BBI != BBE; ++BBI) {
614 Instruction *I = BBI;
615 I->replaceAllUsesWith(UndefValue::get(I->getType()));
616 I->eraseFromParent();
617 }
Devang Pateld79bfdd2007-08-13 22:22:13 +0000618 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patelb7639612007-08-13 22:13:24 +0000619 DT->eraseNode(BB);
620 DF->removeBlock(BB);
621 LI->removeBlock(BB);
622 BB->eraseFromParent();
623 } else {
624 BasicBlock *SuccBB = *SIter;
625 ++WorkList.back().second;
626
627 if (DT->dominates(BB, SuccBB)) {
628 WorkList.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
629 continue;
630 } else {
631 // If SuccBB is not dominated by BB then it is not removed, however remove
632 // any PHI incoming edge from BB.
633 for(BasicBlock::iterator SBI = SuccBB->begin(), SBE = SuccBB->end();
634 SBI != SBE; ++SBI) {
635 if (PHINode *PN = dyn_cast<PHINode>(SBI))
636 PN->removeIncomingValue(BB);
637 else
638 break;
639 }
640
Devang Patel60a94c72007-08-14 18:35:57 +0000641 DT->changeImmediateDominator(SuccBB, LiveBB);
642
Devang Patelb7639612007-08-13 22:13:24 +0000643 // If BB is not dominating SuccBB then SuccBB is in BB's dominance
644 // frontiner.
645 DominanceFrontier::iterator BBDF = DF->find(BB);
646 DF->removeFromFrontier(BBDF, SuccBB);
Devang Patel60a94c72007-08-14 18:35:57 +0000647
648 // LiveBB is now dominating SuccBB. Which means SuccBB's dominance
649 // frontier is member of LiveBB's dominance frontier. However, SuccBB
650 // itself is not member of LiveBB's dominance frontier.
651 DominanceFrontier::iterator LiveDF = DF->find(LiveBB);
652 DominanceFrontier::iterator SuccDF = DF->find(SuccBB);
653 DominanceFrontier::DomSetType SuccBBSet = SuccDF->second;
654 for (DominanceFrontier::DomSetType::iterator SuccBBSetI = SuccBBSet.begin(),
655 SuccBBSetE = SuccBBSet.end(); SuccBBSetI != SuccBBSetE; ++SuccBBSetI) {
656 BasicBlock *DFMember = *SuccBBSetI;
657 // Insert only if LiveBB dominates DFMember.
658 if (!DT->dominates(LiveBB, DFMember))
659 LiveDF->second.insert(DFMember);
660 }
Devang Patel60a94c72007-08-14 18:35:57 +0000661
Devang Patel81fcdfb2007-08-15 02:14:55 +0000662 DF->removeFromFrontier(LiveDF, SuccBB);
Devang Patelb7639612007-08-13 22:13:24 +0000663 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000664 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000665 }
666}
667
Devang Patelc8dadbf2007-08-08 21:02:17 +0000668bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000669
670 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel81fcdfb2007-08-15 02:14:55 +0000671 BasicBlock *SplitBlock = SD.SplitCondition->getParent();
672 BasicBlock *Latch = L->getLoopLatch();
673 BasicBlock *Header = L->getHeader();
674 BranchInst *SplitTerminator = cast<BranchInst>(SplitBlock->getTerminator());
675
676 // FIXME - Unable to handle triange loops at the moment.
677 // In triangle loop, split condition is in header and one of the
678 // the split destination is loop latch. If split condition is EQ
679 // then such loops are already handle in processOneIterationLoop().
680 if (Header == SplitBlock
681 && (Latch == SplitTerminator->getSuccessor(0)
682 || Latch == SplitTerminator->getSuccessor(1)))
683 return false;
Devang Patelf824fb42007-08-10 00:53:35 +0000684
Devang Patel61571ca2007-08-10 00:33:50 +0000685 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000686
687 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000688 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000689 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000690 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000691 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
692 Value *TLExitValue = NULL;
693 Value *FLStartValue = NULL;
694 if (isa<ConstantInt>(SD.SplitValue)) {
695 TLExitValue = SD.SplitValue;
696 FLStartValue = SD.SplitValue;
697 }
698 else {
699 Value *C1 = new ICmpInst(SignedPredicate ?
700 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000701 SD.SplitValue,
702 ExitCondition->getOperand(ExitValueNum),
703 "lsplit.ev",
Devang Patelf824fb42007-08-10 00:53:35 +0000704 Preheader->getTerminator());
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000705 TLExitValue = new SelectInst(C1, SD.SplitValue,
706 ExitCondition->getOperand(ExitValueNum),
Devang Patelf824fb42007-08-10 00:53:35 +0000707 "lsplit.ev", Preheader->getTerminator());
708
709 Value *C2 = new ICmpInst(SignedPredicate ?
710 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
711 SD.SplitValue, StartValue, "lsplit.sv",
712 Preheader->getTerminator());
713 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
714 "lsplit.sv", Preheader->getTerminator());
715 }
Devang Patel901f67e2007-08-10 18:07:13 +0000716
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000717 //[*] Clone loop. Avoid true destination of split condition and
718 // the blocks dominated by true destination.
719 DenseMap<const Value *, Value *> ValueMap;
720 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
721 BasicBlock *FalseHeader = FalseLoop->getHeader();
722
723 //[*] True loop's exit edge enters False loop.
724 PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
Devang Patel901f67e2007-08-10 18:07:13 +0000725 BasicBlock *ExitBlock = ExitCondition->getParent();
726 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
727 assert (ExitInsn && "Unable to find suitable loop exit branch");
728 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000729
Devang Patel59e0c062007-08-14 01:30:57 +0000730 if (L->contains(ExitDest)) {
731 ExitDest = ExitInsn->getSuccessor(0);
732 ExitInsn->setSuccessor(0, FalseHeader);
733 } else
734 ExitInsn->setSuccessor(1, FalseHeader);
735
736 // Collect inverse map of Header PHINodes.
737 DenseMap<Value *, Value *> InverseMap;
738 for (BasicBlock::iterator BI = L->getHeader()->begin(),
739 BE = L->getHeader()->end(); BI != BE; ++BI) {
740 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
741 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
742 InverseMap[PNClone] = PN;
743 } else
744 break;
745 }
746
747 // Update False loop's header
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000748 for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
749 BI != BE; ++BI) {
750 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
751 PN->removeIncomingValue(Preheader);
752 if (PN == IndVarClone)
753 PN->addIncoming(FLStartValue, ExitBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000754 else {
755 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
756 Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
757 PN->addIncoming(V2, ExitBlock);
758 }
759 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000760 break;
761 }
762
Devang Patel59e0c062007-08-14 01:30:57 +0000763 // Update ExitDest. Now it's predecessor is False loop's exit block.
764 BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
765 for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
766 BI != BE; ++BI) {
767 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
768 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
769 PN->removeIncomingValue(ExitBlock);
770 } else
771 break;
772 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000773
Devang Patelb7639612007-08-13 22:13:24 +0000774 if (DT) {
775 DT->changeImmediateDominator(FalseHeader, ExitBlock);
776 DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
777 }
778
Devang Patel901f67e2007-08-10 18:07:13 +0000779 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
Devang Patel901f67e2007-08-10 18:07:13 +0000780
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000781 //[*] Split Exit Edge.
782 SplitEdge(ExitBlock, FalseHeader, this);
Devang Patel901f67e2007-08-10 18:07:13 +0000783
Devang Patel61571ca2007-08-10 00:33:50 +0000784 //[*] Eliminate split condition's false branch from True loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000785 BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
786 BasicBlock *FBB = BR->getSuccessor(1);
787 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel60a94c72007-08-14 18:35:57 +0000788 removeBlocks(FBB, L, BR->getSuccessor(0));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000789
790 //[*] Update True loop's exit value using new exit value.
791 ExitCondition->setOperand(ExitValueNum, TLExitValue);
792
793 //[*] Eliminate split condition's true branch in False loop CFG.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000794 BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
795 BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
796 BasicBlock *TBB = FBR->getSuccessor(0);
797 FBR->setUnconditionalDest(FBR->getSuccessor(1));
Devang Patel60a94c72007-08-14 18:35:57 +0000798 removeBlocks(TBB, FalseLoop, cast<BasicBlock>(FBR->getSuccessor(0)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000799
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000800 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000801}
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000802