blob: 6e04e9f4809a8967272fe22e84600ffc8cb678e1 [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 Patel60a94c72007-08-14 18:35:57 +0000100 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
101 /// This routine is used to remove split condition's dead branch, dominated by
102 /// DeadBB. LiveBB dominates split conidition's other branch.
103 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000104
Devang Patel0aaeb172007-08-08 22:25:28 +0000105 /// Find cost of spliting loop L.
106 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000107 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000108
Devang Patel61571ca2007-08-10 00:33:50 +0000109 void initialize() {
110 IndVar = NULL;
111 IndVarIncrement = NULL;
112 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000113 StartValue = NULL;
114 ExitValueNum = 0;
115 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000116 }
117
Devang Patelbc5fe632007-08-07 00:25:56 +0000118 private:
119
120 // Current Loop.
121 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000122 LPPassManager *LPM;
123 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000124 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000125 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000126 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000127 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000128
129 // Induction variable whose range is being split by this transformation.
130 PHINode *IndVar;
131 Instruction *IndVarIncrement;
132
133 // Loop exit condition.
134 ICmpInst *ExitCondition;
135
136 // Induction variable's initial value.
137 Value *StartValue;
138
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000139 // Induction variable's final loop exit value operand number in exit condition..
140 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000141 };
142
143 char LoopIndexSplit::ID = 0;
144 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
145}
146
147LoopPass *llvm::createLoopIndexSplitPass() {
148 return new LoopIndexSplit();
149}
150
151// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000152bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000153 bool Changed = false;
154 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000155 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000156
Devang Patel81fcdfb2007-08-15 02:14:55 +0000157 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000158 if (!L->getSubLoops().empty())
159 return false;
160
Devang Patelbc5fe632007-08-07 00:25:56 +0000161 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000162 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000163 LI = &getAnalysis<LoopInfo>();
Devang Patelb7639612007-08-13 22:13:24 +0000164 DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000165
Devang Patel61571ca2007-08-10 00:33:50 +0000166 initialize();
167
168 findLoopConditionals();
169
170 if (!ExitCondition)
171 return false;
172
Devang Patelbc5fe632007-08-07 00:25:56 +0000173 findSplitCondition();
174
Devang Patelc8dadbf2007-08-08 21:02:17 +0000175 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000176 return false;
177
Devang Patelc8dadbf2007-08-08 21:02:17 +0000178 // First see if it is possible to eliminate loop itself or not.
179 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
180 E = SplitData.end(); SI != E; ++SI) {
181 SplitInfo &SD = *SI;
182 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000183 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000184 if (Changed) {
185 ++NumIndexSplit;
186 // If is loop is eliminated then nothing else to do here.
187 return Changed;
188 }
189 }
190 }
191
Devang Patel0aaeb172007-08-08 22:25:28 +0000192 unsigned MaxCost = 99;
193 unsigned Index = 0;
194 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000195 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000196 E = SplitData.end(); SI != E; ++SI, ++Index) {
197 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000198
199 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000200 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000201 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000202
203 unsigned Cost = findSplitCost(L, SD);
204 if (Cost < MaxCost)
205 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000206 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000207
Devang Patel0aaeb172007-08-08 22:25:28 +0000208 // Split most profitiable condition.
209 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
210
Devang Patelbc5fe632007-08-07 00:25:56 +0000211 if (Changed)
212 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000213
Devang Patelbc5fe632007-08-07 00:25:56 +0000214 return Changed;
215}
216
Devang Patel2545f7b2007-08-09 01:39:01 +0000217/// Return true if V is a induction variable or induction variable's
218/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000219void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000220
221 Instruction *I = dyn_cast<Instruction>(V);
222 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000223 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000224
225 // Check if I is a phi node from loop header or not.
226 if (PHINode *PN = dyn_cast<PHINode>(V)) {
227 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000228 IndVar = PN;
229 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000230 }
231 }
232
233 // Check if I is a add instruction whose one operand is
234 // phi node from loop header and second operand is constant.
235 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000236 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000237
238 Value *Op0 = I->getOperand(0);
239 Value *Op1 = I->getOperand(1);
240
241 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
242 if (PN->getParent() == L->getHeader()
243 && isa<ConstantInt>(Op1)) {
244 IndVar = PN;
245 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000246 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000247 }
248 }
249
250 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
251 if (PN->getParent() == L->getHeader()
252 && isa<ConstantInt>(Op0)) {
253 IndVar = PN;
254 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000255 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000256 }
257 }
258
Devang Patel61571ca2007-08-10 00:33:50 +0000259 return;
260}
261
262// Find loop's exit condition and associated induction variable.
263void LoopIndexSplit::findLoopConditionals() {
264
265 BasicBlock *ExitBlock = NULL;
266
267 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
268 I != E; ++I) {
269 BasicBlock *BB = *I;
270 if (!L->isLoopExit(BB))
271 continue;
272 if (ExitBlock)
273 return;
274 ExitBlock = BB;
275 }
276
277 if (!ExitBlock)
278 return;
279
280 // If exit block's terminator is conditional branch inst then we have found
281 // exit condition.
282 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
283 if (!BR || BR->isUnconditional())
284 return;
285
286 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
287 if (!CI)
288 return;
289
290 ExitCondition = CI;
291
292 // Exit condition's one operand is loop invariant exit value and second
293 // operand is SCEVAddRecExpr based on induction variable.
294 Value *V0 = CI->getOperand(0);
295 Value *V1 = CI->getOperand(1);
296
297 SCEVHandle SH0 = SE->getSCEV(V0);
298 SCEVHandle SH1 = SE->getSCEV(V1);
299
300 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000301 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000302 findIndVar(V1, L);
303 }
304 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000305 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000306 findIndVar(V0, L);
307 }
308
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000309 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000310 ExitCondition = NULL;
311 else if (IndVar) {
312 BasicBlock *Preheader = L->getLoopPreheader();
313 StartValue = IndVar->getIncomingValueForBlock(Preheader);
314 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000315}
316
Devang Patelbc5fe632007-08-07 00:25:56 +0000317/// Find condition inside a loop that is suitable candidate for index split.
318void LoopIndexSplit::findSplitCondition() {
319
Devang Patelc8dadbf2007-08-08 21:02:17 +0000320 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000321 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000322
Devang Patel2545f7b2007-08-09 01:39:01 +0000323 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
324 I != E; ++I) {
325 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000326
Devang Patel2545f7b2007-08-09 01:39:01 +0000327 // If this basic block does not terminate in a conditional branch
328 // then terminator is not a suitable split condition.
329 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
330 if (!BR)
331 continue;
332
333 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000334 continue;
335
Devang Patel2545f7b2007-08-09 01:39:01 +0000336 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000337 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000338 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000339
Devang Patel2545f7b2007-08-09 01:39:01 +0000340 // If one operand is loop invariant and second operand is SCEVAddRecExpr
341 // based on induction variable then CI is a candidate split condition.
342 Value *V0 = CI->getOperand(0);
343 Value *V1 = CI->getOperand(1);
344
345 SCEVHandle SH0 = SE->getSCEV(V0);
346 SCEVHandle SH1 = SE->getSCEV(V1);
347
348 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
349 SD.SplitValue = V0;
350 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000351 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
352 if (PN == IndVar)
353 SplitData.push_back(SD);
354 }
355 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
356 if (IndVarIncrement && IndVarIncrement == Insn)
357 SplitData.push_back(SD);
358 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000359 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000360 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
361 SD.SplitValue = V1;
362 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000363 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
364 if (PN == IndVar)
365 SplitData.push_back(SD);
366 }
367 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
368 if (IndVarIncrement && IndVarIncrement == Insn)
369 SplitData.push_back(SD);
370 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000371 }
372 }
373}
374
375/// processOneIterationLoop - Current loop L contains compare instruction
376/// that compares induction variable, IndVar, against loop invariant. If
377/// entire (i.e. meaningful) loop body is dominated by this compare
378/// instruction then loop body is executed only once. In such case eliminate
379/// loop structure surrounding this loop body. For example,
380/// for (int i = start; i < end; ++i) {
381/// if ( i == somevalue) {
382/// loop_body
383/// }
384/// }
385/// can be transformed into
386/// if (somevalue >= start && somevalue < end) {
387/// i = somevalue;
388/// loop_body
389/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000390bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000391
392 BasicBlock *Header = L->getHeader();
393
394 // First of all, check if SplitCondition dominates entire loop body
395 // or not.
396
397 // If SplitCondition is not in loop header then this loop is not suitable
398 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000399 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000400 return false;
401
Devang Patelbc5fe632007-08-07 00:25:56 +0000402 // If loop header includes loop variant instruction operands then
403 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000404 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000405 return false;
406
407 // If Exit block includes loop variant instructions then this
408 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000409 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000410 return false;
411
Devang Patel2bcb5012007-08-08 01:51:27 +0000412 // Update CFG.
413
414 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000415 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000416 BasicBlock *LatchSucc = NULL;
417 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
418 if (!BR)
419 return false;
420 Header->removePredecessor(Latch);
421 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
422 SI != E; ++SI) {
423 if (Header != *SI)
424 LatchSucc = *SI;
425 }
426 BR->setUnconditionalDest(LatchSucc);
427
Devang Patelbc5fe632007-08-07 00:25:56 +0000428 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000429 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000430
Devang Patelbc5fe632007-08-07 00:25:56 +0000431 // Replace split condition in header.
432 // Transform
433 // SplitCondition : icmp eq i32 IndVar, SplitValue
434 // into
435 // c1 = icmp uge i32 SplitValue, StartValue
436 // c2 = icmp ult i32 vSplitValue, ExitValue
437 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000438 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000439 Instruction *C1 = new ICmpInst(SignedPredicate ?
440 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000441 SD.SplitValue, StartValue, "lisplit",
442 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000443 Instruction *C2 = new ICmpInst(SignedPredicate ?
444 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000445 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000446 Terminator);
447 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
448 Terminator);
449 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
450 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000451
Devang Patelbc5fe632007-08-07 00:25:56 +0000452 // Now, clear latch block. Remove instructions that are responsible
453 // to increment induction variable.
454 Instruction *LTerminator = Latch->getTerminator();
455 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
456 LB != LE; ) {
457 Instruction *I = LB;
458 ++LB;
459 if (isa<PHINode>(I) || I == LTerminator)
460 continue;
461
Devang Patel59e0c062007-08-14 01:30:57 +0000462 if (I == IndVarIncrement)
463 I->replaceAllUsesWith(ExitValue);
464 else
465 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000466 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000467 }
468
Devang Patel901f67e2007-08-10 18:07:13 +0000469 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000470
471 // Update Dominator Info.
472 // Only CFG change done is to remove Latch to Header edge. This
473 // does not change dominator tree because Latch did not dominate
474 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000475 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000476 DominanceFrontier::iterator HeaderDF = DF->find(Header);
477 if (HeaderDF != DF->end())
478 DF->removeFromFrontier(HeaderDF, Header);
479
480 DominanceFrontier::iterator LatchDF = DF->find(Latch);
481 if (LatchDF != DF->end())
482 DF->removeFromFrontier(LatchDF, Header);
483 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000484 return true;
485}
486
487// If loop header includes loop variant instruction operands then
488// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000489bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000490
491 Instruction *Terminator = Header->getTerminator();
492 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
493 BI != BE; ++BI) {
494 Instruction *I = BI;
495
Devang Patel59e0c062007-08-14 01:30:57 +0000496 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000497 if (isa<PHINode>(I))
498 continue;
499
500 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000501 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000502 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000503
Devang Patel2545f7b2007-08-09 01:39:01 +0000504 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000505 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000506 continue;
507
508 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000509 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000510 continue;
511
Devang Patelbc5fe632007-08-07 00:25:56 +0000512 // Terminator is also harmless.
513 if (I == Terminator)
514 continue;
515
516 // Otherwise we have a instruction that may not be safe.
517 return false;
518 }
519
520 return true;
521}
522
523// If Exit block includes loop variant instructions then this
524// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000525bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000526
Devang Patelbc5fe632007-08-07 00:25:56 +0000527 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
528 BI != BE; ++BI) {
529 Instruction *I = BI;
530
Devang Patel59e0c062007-08-14 01:30:57 +0000531 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000532 if (isa<PHINode>(I))
533 continue;
534
Devang Patel2545f7b2007-08-09 01:39:01 +0000535 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000536 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000537 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000538
Devang Patel2545f7b2007-08-09 01:39:01 +0000539 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000540 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000541
542 Value *Op0 = I->getOperand(0);
543 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000544 PHINode *PN = NULL;
545 ConstantInt *CI = NULL;
546
547 if ((PN = dyn_cast<PHINode>(Op0))) {
548 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000549 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000550 } else
551 if ((PN = dyn_cast<PHINode>(Op1))) {
552 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000553 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000554 }
555
Devang Patel61571ca2007-08-10 00:33:50 +0000556 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000557 continue;
558 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000559
Devang Patelbc5fe632007-08-07 00:25:56 +0000560 // I is an Exit condition if next instruction is block terminator.
561 // Exit condition is OK if it compares loop invariant exit value,
562 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000563 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000564 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000565 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000566 }
567
Devang Patel61571ca2007-08-10 00:33:50 +0000568 if (I == ExitBlock->getTerminator())
569 continue;
570
Devang Patelbc5fe632007-08-07 00:25:56 +0000571 // Otherwise we have instruction that may not be safe.
572 return false;
573 }
574
Devang Patelbc5fe632007-08-07 00:25:56 +0000575 // We could not find any reason to consider ExitBlock unsafe.
576 return true;
577}
578
Devang Patel0aaeb172007-08-08 22:25:28 +0000579/// Find cost of spliting loop L. Cost is measured in terms of size growth.
580/// Size is growth is calculated based on amount of code duplicated in second
581/// loop.
582unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
583
584 unsigned Cost = 0;
585 BasicBlock *SDBlock = SD.SplitCondition->getParent();
586 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
587 I != E; ++I) {
588 BasicBlock *BB = *I;
589 // If a block is not dominated by split condition block then
590 // it must be duplicated in both loops.
591 if (!DT->dominates(SDBlock, BB))
592 Cost += BB->size();
593 }
594
595 return Cost;
596}
597
Devang Patel60a94c72007-08-14 18:35:57 +0000598/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
599/// This routine is used to remove split condition's dead branch, dominated by
600/// DeadBB. LiveBB dominates split conidition's other branch.
601void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
602 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000603
Devang Patelb7639612007-08-13 22:13:24 +0000604 SmallVector<std::pair<BasicBlock *, succ_iterator>, 8> WorkList;
Devang Patel60a94c72007-08-14 18:35:57 +0000605 WorkList.push_back(std::make_pair(DeadBB, succ_begin(DeadBB)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000606 while (!WorkList.empty()) {
Devang Patelb7639612007-08-13 22:13:24 +0000607 BasicBlock *BB = WorkList.back(). first;
Devang Patel81fcdfb2007-08-15 02:14:55 +0000608 succ_iterator SIter = WorkList.back().second;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000609
Devang Patelb7639612007-08-13 22:13:24 +0000610 // If all successor's are processed then remove this block.
611 if (SIter == succ_end(BB)) {
612 WorkList.pop_back();
613 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
614 BBI != BBE; ++BBI) {
615 Instruction *I = BBI;
616 I->replaceAllUsesWith(UndefValue::get(I->getType()));
617 I->eraseFromParent();
618 }
Devang Pateld79bfdd2007-08-13 22:22:13 +0000619 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patelb7639612007-08-13 22:13:24 +0000620 DT->eraseNode(BB);
621 DF->removeBlock(BB);
622 LI->removeBlock(BB);
623 BB->eraseFromParent();
624 } else {
625 BasicBlock *SuccBB = *SIter;
626 ++WorkList.back().second;
627
628 if (DT->dominates(BB, SuccBB)) {
629 WorkList.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
630 continue;
631 } else {
632 // If SuccBB is not dominated by BB then it is not removed, however remove
633 // any PHI incoming edge from BB.
634 for(BasicBlock::iterator SBI = SuccBB->begin(), SBE = SuccBB->end();
635 SBI != SBE; ++SBI) {
636 if (PHINode *PN = dyn_cast<PHINode>(SBI))
637 PN->removeIncomingValue(BB);
638 else
639 break;
640 }
641
Devang Patel60a94c72007-08-14 18:35:57 +0000642 DT->changeImmediateDominator(SuccBB, LiveBB);
643
Devang Patelb7639612007-08-13 22:13:24 +0000644 // If BB is not dominating SuccBB then SuccBB is in BB's dominance
645 // frontiner.
646 DominanceFrontier::iterator BBDF = DF->find(BB);
647 DF->removeFromFrontier(BBDF, SuccBB);
Devang Patel60a94c72007-08-14 18:35:57 +0000648
649 // LiveBB is now dominating SuccBB. Which means SuccBB's dominance
650 // frontier is member of LiveBB's dominance frontier. However, SuccBB
651 // itself is not member of LiveBB's dominance frontier.
652 DominanceFrontier::iterator LiveDF = DF->find(LiveBB);
653 DominanceFrontier::iterator SuccDF = DF->find(SuccBB);
654 DominanceFrontier::DomSetType SuccBBSet = SuccDF->second;
655 for (DominanceFrontier::DomSetType::iterator SuccBBSetI = SuccBBSet.begin(),
656 SuccBBSetE = SuccBBSet.end(); SuccBBSetI != SuccBBSetE; ++SuccBBSetI) {
657 BasicBlock *DFMember = *SuccBBSetI;
658 // Insert only if LiveBB dominates DFMember.
659 if (!DT->dominates(LiveBB, DFMember))
660 LiveDF->second.insert(DFMember);
661 }
Devang Patel60a94c72007-08-14 18:35:57 +0000662
Devang Patel81fcdfb2007-08-15 02:14:55 +0000663 DF->removeFromFrontier(LiveDF, SuccBB);
Devang Patelb7639612007-08-13 22:13:24 +0000664 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000665 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000666 }
667}
668
Devang Patelc8dadbf2007-08-08 21:02:17 +0000669bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000670
671 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel81fcdfb2007-08-15 02:14:55 +0000672 BasicBlock *SplitBlock = SD.SplitCondition->getParent();
673 BasicBlock *Latch = L->getLoopLatch();
674 BasicBlock *Header = L->getHeader();
675 BranchInst *SplitTerminator = cast<BranchInst>(SplitBlock->getTerminator());
676
677 // FIXME - Unable to handle triange loops at the moment.
678 // In triangle loop, split condition is in header and one of the
679 // the split destination is loop latch. If split condition is EQ
680 // then such loops are already handle in processOneIterationLoop().
681 if (Header == SplitBlock
682 && (Latch == SplitTerminator->getSuccessor(0)
683 || Latch == SplitTerminator->getSuccessor(1)))
684 return false;
Devang Patelf824fb42007-08-10 00:53:35 +0000685
Devang Patel61571ca2007-08-10 00:33:50 +0000686 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000687
688 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000689 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000690 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000691 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000692 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
693 Value *TLExitValue = NULL;
694 Value *FLStartValue = NULL;
695 if (isa<ConstantInt>(SD.SplitValue)) {
696 TLExitValue = SD.SplitValue;
697 FLStartValue = SD.SplitValue;
698 }
699 else {
700 Value *C1 = new ICmpInst(SignedPredicate ?
701 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000702 SD.SplitValue,
703 ExitCondition->getOperand(ExitValueNum),
704 "lsplit.ev",
Devang Patelf824fb42007-08-10 00:53:35 +0000705 Preheader->getTerminator());
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000706 TLExitValue = new SelectInst(C1, SD.SplitValue,
707 ExitCondition->getOperand(ExitValueNum),
Devang Patelf824fb42007-08-10 00:53:35 +0000708 "lsplit.ev", Preheader->getTerminator());
709
710 Value *C2 = new ICmpInst(SignedPredicate ?
711 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
712 SD.SplitValue, StartValue, "lsplit.sv",
713 Preheader->getTerminator());
714 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
715 "lsplit.sv", Preheader->getTerminator());
716 }
Devang Patel901f67e2007-08-10 18:07:13 +0000717
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000718 //[*] Clone loop. Avoid true destination of split condition and
719 // the blocks dominated by true destination.
720 DenseMap<const Value *, Value *> ValueMap;
721 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
722 BasicBlock *FalseHeader = FalseLoop->getHeader();
723
724 //[*] True loop's exit edge enters False loop.
725 PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
Devang Patel901f67e2007-08-10 18:07:13 +0000726 BasicBlock *ExitBlock = ExitCondition->getParent();
727 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
728 assert (ExitInsn && "Unable to find suitable loop exit branch");
729 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000730
Devang Patel59e0c062007-08-14 01:30:57 +0000731 if (L->contains(ExitDest)) {
732 ExitDest = ExitInsn->getSuccessor(0);
733 ExitInsn->setSuccessor(0, FalseHeader);
734 } else
735 ExitInsn->setSuccessor(1, FalseHeader);
736
737 // Collect inverse map of Header PHINodes.
738 DenseMap<Value *, Value *> InverseMap;
739 for (BasicBlock::iterator BI = L->getHeader()->begin(),
740 BE = L->getHeader()->end(); BI != BE; ++BI) {
741 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
742 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
743 InverseMap[PNClone] = PN;
744 } else
745 break;
746 }
747
748 // Update False loop's header
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000749 for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
750 BI != BE; ++BI) {
751 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
752 PN->removeIncomingValue(Preheader);
753 if (PN == IndVarClone)
754 PN->addIncoming(FLStartValue, ExitBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000755 else {
756 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
757 Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
758 PN->addIncoming(V2, ExitBlock);
759 }
760 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000761 break;
762 }
763
Devang Patel59e0c062007-08-14 01:30:57 +0000764 // Update ExitDest. Now it's predecessor is False loop's exit block.
765 BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
766 for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
767 BI != BE; ++BI) {
768 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
769 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
770 PN->removeIncomingValue(ExitBlock);
771 } else
772 break;
773 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000774
Devang Patelb7639612007-08-13 22:13:24 +0000775 if (DT) {
776 DT->changeImmediateDominator(FalseHeader, ExitBlock);
777 DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
778 }
779
Devang Patel901f67e2007-08-10 18:07:13 +0000780 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
Devang Patel901f67e2007-08-10 18:07:13 +0000781
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000782 //[*] Split Exit Edge.
783 SplitEdge(ExitBlock, FalseHeader, this);
Devang Patel901f67e2007-08-10 18:07:13 +0000784
Devang Patel61571ca2007-08-10 00:33:50 +0000785 //[*] Eliminate split condition's false branch from True loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000786 BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
787 BasicBlock *FBB = BR->getSuccessor(1);
788 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel60a94c72007-08-14 18:35:57 +0000789 removeBlocks(FBB, L, BR->getSuccessor(0));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000790
791 //[*] Update True loop's exit value using new exit value.
792 ExitCondition->setOperand(ExitValueNum, TLExitValue);
793
794 //[*] Eliminate split condition's true branch in False loop CFG.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000795 BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
796 BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
797 BasicBlock *TBB = FBR->getSuccessor(0);
798 FBR->setUnconditionalDest(FBR->getSuccessor(1));
Devang Patel60a94c72007-08-14 18:35:57 +0000799 removeBlocks(TBB, FalseLoop, cast<BasicBlock>(FBR->getSuccessor(0)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000800
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000801 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000802}
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000803