blob: 1398692afdeb354af2d4bc6ea4043ea149a59bb2 [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 Patelbc5fe632007-08-07 00:25:56 +0000157 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000158 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000159 LI = &getAnalysis<LoopInfo>();
Devang Patelb7639612007-08-13 22:13:24 +0000160 DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000161
Devang Patel61571ca2007-08-10 00:33:50 +0000162 initialize();
163
164 findLoopConditionals();
165
166 if (!ExitCondition)
167 return false;
168
Devang Patelbc5fe632007-08-07 00:25:56 +0000169 findSplitCondition();
170
Devang Patelc8dadbf2007-08-08 21:02:17 +0000171 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000172 return false;
173
Devang Patelc8dadbf2007-08-08 21:02:17 +0000174 // First see if it is possible to eliminate loop itself or not.
175 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
176 E = SplitData.end(); SI != E; ++SI) {
177 SplitInfo &SD = *SI;
178 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000179 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000180 if (Changed) {
181 ++NumIndexSplit;
182 // If is loop is eliminated then nothing else to do here.
183 return Changed;
184 }
185 }
186 }
187
Devang Patel0aaeb172007-08-08 22:25:28 +0000188 unsigned MaxCost = 99;
189 unsigned Index = 0;
190 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000191 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000192 E = SplitData.end(); SI != E; ++SI, ++Index) {
193 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000194
195 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000196 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000197 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000198
199 unsigned Cost = findSplitCost(L, SD);
200 if (Cost < MaxCost)
201 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000202 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000203
Devang Patel0aaeb172007-08-08 22:25:28 +0000204 // Split most profitiable condition.
205 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
206
Devang Patelbc5fe632007-08-07 00:25:56 +0000207 if (Changed)
208 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000209
Devang Patelbc5fe632007-08-07 00:25:56 +0000210 return Changed;
211}
212
Devang Patel2545f7b2007-08-09 01:39:01 +0000213/// Return true if V is a induction variable or induction variable's
214/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000215void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000216
217 Instruction *I = dyn_cast<Instruction>(V);
218 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000219 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000220
221 // Check if I is a phi node from loop header or not.
222 if (PHINode *PN = dyn_cast<PHINode>(V)) {
223 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000224 IndVar = PN;
225 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000226 }
227 }
228
229 // Check if I is a add instruction whose one operand is
230 // phi node from loop header and second operand is constant.
231 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000232 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000233
234 Value *Op0 = I->getOperand(0);
235 Value *Op1 = I->getOperand(1);
236
237 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
238 if (PN->getParent() == L->getHeader()
239 && isa<ConstantInt>(Op1)) {
240 IndVar = PN;
241 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000242 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000243 }
244 }
245
246 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
247 if (PN->getParent() == L->getHeader()
248 && isa<ConstantInt>(Op0)) {
249 IndVar = PN;
250 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000251 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000252 }
253 }
254
Devang Patel61571ca2007-08-10 00:33:50 +0000255 return;
256}
257
258// Find loop's exit condition and associated induction variable.
259void LoopIndexSplit::findLoopConditionals() {
260
261 BasicBlock *ExitBlock = NULL;
262
263 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
264 I != E; ++I) {
265 BasicBlock *BB = *I;
266 if (!L->isLoopExit(BB))
267 continue;
268 if (ExitBlock)
269 return;
270 ExitBlock = BB;
271 }
272
273 if (!ExitBlock)
274 return;
275
276 // If exit block's terminator is conditional branch inst then we have found
277 // exit condition.
278 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
279 if (!BR || BR->isUnconditional())
280 return;
281
282 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
283 if (!CI)
284 return;
285
286 ExitCondition = CI;
287
288 // Exit condition's one operand is loop invariant exit value and second
289 // operand is SCEVAddRecExpr based on induction variable.
290 Value *V0 = CI->getOperand(0);
291 Value *V1 = CI->getOperand(1);
292
293 SCEVHandle SH0 = SE->getSCEV(V0);
294 SCEVHandle SH1 = SE->getSCEV(V1);
295
296 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000297 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000298 findIndVar(V1, L);
299 }
300 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000301 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000302 findIndVar(V0, L);
303 }
304
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000305 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000306 ExitCondition = NULL;
307 else if (IndVar) {
308 BasicBlock *Preheader = L->getLoopPreheader();
309 StartValue = IndVar->getIncomingValueForBlock(Preheader);
310 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000311}
312
Devang Patelbc5fe632007-08-07 00:25:56 +0000313/// Find condition inside a loop that is suitable candidate for index split.
314void LoopIndexSplit::findSplitCondition() {
315
Devang Patelc8dadbf2007-08-08 21:02:17 +0000316 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000317 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000318
Devang Patel2545f7b2007-08-09 01:39:01 +0000319 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
320 I != E; ++I) {
321 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000322
Devang Patel2545f7b2007-08-09 01:39:01 +0000323 // If this basic block does not terminate in a conditional branch
324 // then terminator is not a suitable split condition.
325 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
326 if (!BR)
327 continue;
328
329 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000330 continue;
331
Devang Patel2545f7b2007-08-09 01:39:01 +0000332 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000333 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000334 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000335
Devang Patel2545f7b2007-08-09 01:39:01 +0000336 // If one operand is loop invariant and second operand is SCEVAddRecExpr
337 // based on induction variable then CI is a candidate split condition.
338 Value *V0 = CI->getOperand(0);
339 Value *V1 = CI->getOperand(1);
340
341 SCEVHandle SH0 = SE->getSCEV(V0);
342 SCEVHandle SH1 = SE->getSCEV(V1);
343
344 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
345 SD.SplitValue = V0;
346 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000347 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
348 if (PN == IndVar)
349 SplitData.push_back(SD);
350 }
351 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
352 if (IndVarIncrement && IndVarIncrement == Insn)
353 SplitData.push_back(SD);
354 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000355 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000356 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
357 SD.SplitValue = V1;
358 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000359 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
360 if (PN == IndVar)
361 SplitData.push_back(SD);
362 }
363 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
364 if (IndVarIncrement && IndVarIncrement == Insn)
365 SplitData.push_back(SD);
366 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000367 }
368 }
369}
370
371/// processOneIterationLoop - Current loop L contains compare instruction
372/// that compares induction variable, IndVar, against loop invariant. If
373/// entire (i.e. meaningful) loop body is dominated by this compare
374/// instruction then loop body is executed only once. In such case eliminate
375/// loop structure surrounding this loop body. For example,
376/// for (int i = start; i < end; ++i) {
377/// if ( i == somevalue) {
378/// loop_body
379/// }
380/// }
381/// can be transformed into
382/// if (somevalue >= start && somevalue < end) {
383/// i = somevalue;
384/// loop_body
385/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000386bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000387
388 BasicBlock *Header = L->getHeader();
389
390 // First of all, check if SplitCondition dominates entire loop body
391 // or not.
392
393 // If SplitCondition is not in loop header then this loop is not suitable
394 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000395 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000396 return false;
397
Devang Patelbc5fe632007-08-07 00:25:56 +0000398 // If loop header includes loop variant instruction operands then
399 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000400 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000401 return false;
402
403 // If Exit block includes loop variant instructions then this
404 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000405 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000406 return false;
407
Devang Patel2bcb5012007-08-08 01:51:27 +0000408 // Update CFG.
409
410 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000411 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000412 BasicBlock *LatchSucc = NULL;
413 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
414 if (!BR)
415 return false;
416 Header->removePredecessor(Latch);
417 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
418 SI != E; ++SI) {
419 if (Header != *SI)
420 LatchSucc = *SI;
421 }
422 BR->setUnconditionalDest(LatchSucc);
423
Devang Patelbc5fe632007-08-07 00:25:56 +0000424 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000425 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000426
Devang Patelbc5fe632007-08-07 00:25:56 +0000427 // Replace split condition in header.
428 // Transform
429 // SplitCondition : icmp eq i32 IndVar, SplitValue
430 // into
431 // c1 = icmp uge i32 SplitValue, StartValue
432 // c2 = icmp ult i32 vSplitValue, ExitValue
433 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000434 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000435 Instruction *C1 = new ICmpInst(SignedPredicate ?
436 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000437 SD.SplitValue, StartValue, "lisplit",
438 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000439 Instruction *C2 = new ICmpInst(SignedPredicate ?
440 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000441 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000442 Terminator);
443 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
444 Terminator);
445 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
446 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000447
Devang Patelbc5fe632007-08-07 00:25:56 +0000448 // Now, clear latch block. Remove instructions that are responsible
449 // to increment induction variable.
450 Instruction *LTerminator = Latch->getTerminator();
451 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
452 LB != LE; ) {
453 Instruction *I = LB;
454 ++LB;
455 if (isa<PHINode>(I) || I == LTerminator)
456 continue;
457
Devang Patel59e0c062007-08-14 01:30:57 +0000458 if (I == IndVarIncrement)
459 I->replaceAllUsesWith(ExitValue);
460 else
461 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000462 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000463 }
464
Devang Patel901f67e2007-08-10 18:07:13 +0000465 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000466
467 // Update Dominator Info.
468 // Only CFG change done is to remove Latch to Header edge. This
469 // does not change dominator tree because Latch did not dominate
470 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000471 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000472 DominanceFrontier::iterator HeaderDF = DF->find(Header);
473 if (HeaderDF != DF->end())
474 DF->removeFromFrontier(HeaderDF, Header);
475
476 DominanceFrontier::iterator LatchDF = DF->find(Latch);
477 if (LatchDF != DF->end())
478 DF->removeFromFrontier(LatchDF, Header);
479 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000480 return true;
481}
482
483// If loop header includes loop variant instruction operands then
484// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000485bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000486
487 Instruction *Terminator = Header->getTerminator();
488 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
489 BI != BE; ++BI) {
490 Instruction *I = BI;
491
Devang Patel59e0c062007-08-14 01:30:57 +0000492 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000493 if (isa<PHINode>(I))
494 continue;
495
496 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000497 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000498 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000499
Devang Patel2545f7b2007-08-09 01:39:01 +0000500 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000501 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000502 continue;
503
504 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000505 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000506 continue;
507
Devang Patelbc5fe632007-08-07 00:25:56 +0000508 // Terminator is also harmless.
509 if (I == Terminator)
510 continue;
511
512 // Otherwise we have a instruction that may not be safe.
513 return false;
514 }
515
516 return true;
517}
518
519// If Exit block includes loop variant instructions then this
520// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000521bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000522
Devang Patelbc5fe632007-08-07 00:25:56 +0000523 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
524 BI != BE; ++BI) {
525 Instruction *I = BI;
526
Devang Patel59e0c062007-08-14 01:30:57 +0000527 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000528 if (isa<PHINode>(I))
529 continue;
530
Devang Patel2545f7b2007-08-09 01:39:01 +0000531 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000532 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000533 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000534
Devang Patel2545f7b2007-08-09 01:39:01 +0000535 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000536 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000537
538 Value *Op0 = I->getOperand(0);
539 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000540 PHINode *PN = NULL;
541 ConstantInt *CI = NULL;
542
543 if ((PN = dyn_cast<PHINode>(Op0))) {
544 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000545 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000546 } else
547 if ((PN = dyn_cast<PHINode>(Op1))) {
548 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000549 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000550 }
551
Devang Patel61571ca2007-08-10 00:33:50 +0000552 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000553 continue;
554 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000555
Devang Patelbc5fe632007-08-07 00:25:56 +0000556 // I is an Exit condition if next instruction is block terminator.
557 // Exit condition is OK if it compares loop invariant exit value,
558 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000559 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000560 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000561 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000562 }
563
Devang Patel61571ca2007-08-10 00:33:50 +0000564 if (I == ExitBlock->getTerminator())
565 continue;
566
Devang Patelbc5fe632007-08-07 00:25:56 +0000567 // Otherwise we have instruction that may not be safe.
568 return false;
569 }
570
Devang Patelbc5fe632007-08-07 00:25:56 +0000571 // We could not find any reason to consider ExitBlock unsafe.
572 return true;
573}
574
Devang Patel0aaeb172007-08-08 22:25:28 +0000575/// Find cost of spliting loop L. Cost is measured in terms of size growth.
576/// Size is growth is calculated based on amount of code duplicated in second
577/// loop.
578unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
579
580 unsigned Cost = 0;
581 BasicBlock *SDBlock = SD.SplitCondition->getParent();
582 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
583 I != E; ++I) {
584 BasicBlock *BB = *I;
585 // If a block is not dominated by split condition block then
586 // it must be duplicated in both loops.
587 if (!DT->dominates(SDBlock, BB))
588 Cost += BB->size();
589 }
590
591 return Cost;
592}
593
Devang Patel60a94c72007-08-14 18:35:57 +0000594/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
595/// This routine is used to remove split condition's dead branch, dominated by
596/// DeadBB. LiveBB dominates split conidition's other branch.
597void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
598 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000599
Devang Patelb7639612007-08-13 22:13:24 +0000600 SmallVector<std::pair<BasicBlock *, succ_iterator>, 8> WorkList;
Devang Patel60a94c72007-08-14 18:35:57 +0000601 WorkList.push_back(std::make_pair(DeadBB, succ_begin(DeadBB)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000602 while (!WorkList.empty()) {
Devang Patelb7639612007-08-13 22:13:24 +0000603 BasicBlock *BB = WorkList.back(). first;
604 succ_iterator SIter =WorkList.back().second;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000605
Devang Patelb7639612007-08-13 22:13:24 +0000606 // If all successor's are processed then remove this block.
607 if (SIter == succ_end(BB)) {
608 WorkList.pop_back();
609 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
610 BBI != BBE; ++BBI) {
611 Instruction *I = BBI;
612 I->replaceAllUsesWith(UndefValue::get(I->getType()));
613 I->eraseFromParent();
614 }
Devang Pateld79bfdd2007-08-13 22:22:13 +0000615 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patelb7639612007-08-13 22:13:24 +0000616 DT->eraseNode(BB);
617 DF->removeBlock(BB);
618 LI->removeBlock(BB);
619 BB->eraseFromParent();
620 } else {
621 BasicBlock *SuccBB = *SIter;
622 ++WorkList.back().second;
623
624 if (DT->dominates(BB, SuccBB)) {
625 WorkList.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
626 continue;
627 } else {
628 // If SuccBB is not dominated by BB then it is not removed, however remove
629 // any PHI incoming edge from BB.
630 for(BasicBlock::iterator SBI = SuccBB->begin(), SBE = SuccBB->end();
631 SBI != SBE; ++SBI) {
632 if (PHINode *PN = dyn_cast<PHINode>(SBI))
633 PN->removeIncomingValue(BB);
634 else
635 break;
636 }
637
Devang Patel60a94c72007-08-14 18:35:57 +0000638 DT->changeImmediateDominator(SuccBB, LiveBB);
639
Devang Patelb7639612007-08-13 22:13:24 +0000640 // If BB is not dominating SuccBB then SuccBB is in BB's dominance
641 // frontiner.
642 DominanceFrontier::iterator BBDF = DF->find(BB);
643 DF->removeFromFrontier(BBDF, SuccBB);
Devang Patel60a94c72007-08-14 18:35:57 +0000644
645 // LiveBB is now dominating SuccBB. Which means SuccBB's dominance
646 // frontier is member of LiveBB's dominance frontier. However, SuccBB
647 // itself is not member of LiveBB's dominance frontier.
648 DominanceFrontier::iterator LiveDF = DF->find(LiveBB);
649 DominanceFrontier::iterator SuccDF = DF->find(SuccBB);
650 DominanceFrontier::DomSetType SuccBBSet = SuccDF->second;
651 for (DominanceFrontier::DomSetType::iterator SuccBBSetI = SuccBBSet.begin(),
652 SuccBBSetE = SuccBBSet.end(); SuccBBSetI != SuccBBSetE; ++SuccBBSetI) {
653 BasicBlock *DFMember = *SuccBBSetI;
654 // Insert only if LiveBB dominates DFMember.
655 if (!DT->dominates(LiveBB, DFMember))
656 LiveDF->second.insert(DFMember);
657 }
658 DF->removeFromFrontier(LiveDF, SuccBB);
659
Devang Patelb7639612007-08-13 22:13:24 +0000660 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000661 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000662 }
663}
664
Devang Patelc8dadbf2007-08-08 21:02:17 +0000665bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000666
667 BasicBlock *Preheader = L->getLoopPreheader();
668
Devang Patel61571ca2007-08-10 00:33:50 +0000669 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000670
671 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000672 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000673 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000674 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000675 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
676 Value *TLExitValue = NULL;
677 Value *FLStartValue = NULL;
678 if (isa<ConstantInt>(SD.SplitValue)) {
679 TLExitValue = SD.SplitValue;
680 FLStartValue = SD.SplitValue;
681 }
682 else {
683 Value *C1 = new ICmpInst(SignedPredicate ?
684 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000685 SD.SplitValue,
686 ExitCondition->getOperand(ExitValueNum),
687 "lsplit.ev",
Devang Patelf824fb42007-08-10 00:53:35 +0000688 Preheader->getTerminator());
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000689 TLExitValue = new SelectInst(C1, SD.SplitValue,
690 ExitCondition->getOperand(ExitValueNum),
Devang Patelf824fb42007-08-10 00:53:35 +0000691 "lsplit.ev", Preheader->getTerminator());
692
693 Value *C2 = new ICmpInst(SignedPredicate ?
694 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
695 SD.SplitValue, StartValue, "lsplit.sv",
696 Preheader->getTerminator());
697 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
698 "lsplit.sv", Preheader->getTerminator());
699 }
Devang Patel901f67e2007-08-10 18:07:13 +0000700
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000701 //[*] Clone loop. Avoid true destination of split condition and
702 // the blocks dominated by true destination.
703 DenseMap<const Value *, Value *> ValueMap;
704 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
705 BasicBlock *FalseHeader = FalseLoop->getHeader();
706
707 //[*] True loop's exit edge enters False loop.
708 PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
Devang Patel901f67e2007-08-10 18:07:13 +0000709 BasicBlock *ExitBlock = ExitCondition->getParent();
710 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
711 assert (ExitInsn && "Unable to find suitable loop exit branch");
712 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000713
Devang Patel59e0c062007-08-14 01:30:57 +0000714 if (L->contains(ExitDest)) {
715 ExitDest = ExitInsn->getSuccessor(0);
716 ExitInsn->setSuccessor(0, FalseHeader);
717 } else
718 ExitInsn->setSuccessor(1, FalseHeader);
719
720 // Collect inverse map of Header PHINodes.
721 DenseMap<Value *, Value *> InverseMap;
722 for (BasicBlock::iterator BI = L->getHeader()->begin(),
723 BE = L->getHeader()->end(); BI != BE; ++BI) {
724 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
725 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
726 InverseMap[PNClone] = PN;
727 } else
728 break;
729 }
730
731 // Update False loop's header
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000732 for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
733 BI != BE; ++BI) {
734 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
735 PN->removeIncomingValue(Preheader);
736 if (PN == IndVarClone)
737 PN->addIncoming(FLStartValue, ExitBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000738 else {
739 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
740 Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
741 PN->addIncoming(V2, ExitBlock);
742 }
743 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000744 break;
745 }
746
Devang Patel59e0c062007-08-14 01:30:57 +0000747 // Update ExitDest. Now it's predecessor is False loop's exit block.
748 BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
749 for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
750 BI != BE; ++BI) {
751 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
752 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
753 PN->removeIncomingValue(ExitBlock);
754 } else
755 break;
756 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000757
Devang Patelb7639612007-08-13 22:13:24 +0000758 if (DT) {
759 DT->changeImmediateDominator(FalseHeader, ExitBlock);
760 DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
761 }
762
Devang Patel901f67e2007-08-10 18:07:13 +0000763 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
Devang Patel901f67e2007-08-10 18:07:13 +0000764
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000765 //[*] Split Exit Edge.
766 SplitEdge(ExitBlock, FalseHeader, this);
Devang Patel901f67e2007-08-10 18:07:13 +0000767
Devang Patel61571ca2007-08-10 00:33:50 +0000768 //[*] Eliminate split condition's false branch from True loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000769 BasicBlock *SplitBlock = SD.SplitCondition->getParent();
770 BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
771 BasicBlock *FBB = BR->getSuccessor(1);
772 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel60a94c72007-08-14 18:35:57 +0000773 removeBlocks(FBB, L, BR->getSuccessor(0));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000774
775 //[*] Update True loop's exit value using new exit value.
776 ExitCondition->setOperand(ExitValueNum, TLExitValue);
777
778 //[*] Eliminate split condition's true branch in False loop CFG.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000779 BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
780 BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
781 BasicBlock *TBB = FBR->getSuccessor(0);
782 FBR->setUnconditionalDest(FBR->getSuccessor(1));
Devang Patel60a94c72007-08-14 18:35:57 +0000783 removeBlocks(TBB, FalseLoop, cast<BasicBlock>(FBR->getSuccessor(0)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000784
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000785 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000786}
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000787