blob: 4a6202e7836773a04da123624d24d4392e7f5a45 [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"
Devang Patelf4277122007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000024#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 Patelf4277122007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel95fd7172007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel7f526a82007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Pateledea5b32007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000063
Devang Patelc8dadbf2007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patelc8dadbf2007-08-08 21:02:17 +000067 // This compare instruction compares IndVar against SplitValue.
68 ICmpInst *SplitCondition;
69
Devang Patel7f526a82007-08-24 06:17:19 +000070 // True if after loop index split, first loop will execute split condition's
71 // true branch.
72 bool UseTrueBranchFirst;
Devang Pateledea5b32007-08-25 00:56:38 +000073
74 // Exit value for first loop after loop split.
75 Value *A_ExitValue;
76
77 // Start value for second loop after loop split.
78 Value *B_StartValue;
79
Devang Patel31696332007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel7f526a82007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Pateledea5b32007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000087 }
Devang Patel2545f7b2007-08-09 01:39:01 +000088
Devang Patelc8dadbf2007-08-08 21:02:17 +000089 };
Devang Patel61571ca2007-08-10 00:33:50 +000090
Devang Patelc8dadbf2007-08-08 21:02:17 +000091 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000092 /// Find condition inside a loop that is suitable candidate for index split.
93 void findSplitCondition();
94
Devang Patel61571ca2007-08-10 00:33:50 +000095 /// Find loop's exit condition.
96 void findLoopConditionals();
97
98 /// Return induction variable associated with value V.
99 void findIndVar(Value *V, Loop *L);
100
Devang Patelbc5fe632007-08-07 00:25:56 +0000101 /// processOneIterationLoop - Current loop L contains compare instruction
102 /// that compares induction variable, IndVar, agains loop invariant. If
103 /// entire (i.e. meaningful) loop body is dominated by this compare
104 /// instruction then loop body is executed only for one iteration. In
105 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +0000106 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000107
Devang Patel0aaeb172007-08-08 22:25:28 +0000108 /// If loop header includes loop variant instruction operands then
109 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000110 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000111
Devang Patel9263fc32007-08-20 23:51:18 +0000112 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +0000113 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000114 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000115
Devang Patel60a94c72007-08-14 18:35:57 +0000116 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117 /// This routine is used to remove split condition's dead branch, dominated by
118 /// DeadBB. LiveBB dominates split conidition's other branch.
119 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000120
Devang Pateld662ace2007-08-22 18:27:01 +0000121 /// safeSplitCondition - Return true if it is possible to
122 /// split loop using given split condition.
123 bool safeSplitCondition(SplitInfo &SD);
124
Devang Pateledea5b32007-08-25 00:56:38 +0000125 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126 /// based on split value.
127 void calculateLoopBounds(SplitInfo &SD);
128
Devang Patelcd71bed2007-08-25 02:39:24 +0000129 /// updatePHINodes - CFG has been changed.
130 /// Before
131 /// - ExitBB's single predecessor was Latch
132 /// - Latch's second successor was Header
133 /// Now
134 /// - ExitBB's single predecessor was Header
135 /// - Latch's one and only successor was Header
136 ///
137 /// Update ExitBB PHINodes' to reflect this change.
138 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
139 BasicBlock *Header,
140 PHINode *IV, Instruction *IVIncrement);
141
142 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
143 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
144 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
145 PHINode *IV, Instruction *IVAdd, Loop *LP);
146
Devang Pateld662ace2007-08-22 18:27:01 +0000147 /// splitLoop - Split current loop L in two loops using split information
148 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000149 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000150
Devang Patel61571ca2007-08-10 00:33:50 +0000151 void initialize() {
152 IndVar = NULL;
153 IndVarIncrement = NULL;
154 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000155 StartValue = NULL;
156 ExitValueNum = 0;
157 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000158 }
159
Devang Patelbc5fe632007-08-07 00:25:56 +0000160 private:
161
162 // Current Loop.
163 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000164 LPPassManager *LPM;
165 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000166 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000167 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000168 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000169 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000170
171 // Induction variable whose range is being split by this transformation.
172 PHINode *IndVar;
173 Instruction *IndVarIncrement;
174
175 // Loop exit condition.
176 ICmpInst *ExitCondition;
177
178 // Induction variable's initial value.
179 Value *StartValue;
180
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000181 // Induction variable's final loop exit value operand number in exit condition..
182 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000183 };
184
185 char LoopIndexSplit::ID = 0;
186 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
187}
188
189LoopPass *llvm::createLoopIndexSplitPass() {
190 return new LoopIndexSplit();
191}
192
193// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000194bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000195 bool Changed = false;
196 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000197 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000198
Devang Patel81fcdfb2007-08-15 02:14:55 +0000199 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000200 if (!L->getSubLoops().empty())
201 return false;
202
Devang Patelbc5fe632007-08-07 00:25:56 +0000203 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000204 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000205 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000206 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000207
Devang Patel61571ca2007-08-10 00:33:50 +0000208 initialize();
209
210 findLoopConditionals();
211
212 if (!ExitCondition)
213 return false;
214
Devang Patelbc5fe632007-08-07 00:25:56 +0000215 findSplitCondition();
216
Devang Patelc8dadbf2007-08-08 21:02:17 +0000217 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000218 return false;
219
Devang Patelc8dadbf2007-08-08 21:02:17 +0000220 // First see if it is possible to eliminate loop itself or not.
221 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000222 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000223 SplitInfo &SD = *SI;
224 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000225 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000226 if (Changed) {
227 ++NumIndexSplit;
228 // If is loop is eliminated then nothing else to do here.
229 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000230 } else {
231 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
232 ++SI;
233 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000234 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000235 } else
236 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000237 }
238
Devang Patel7f526a82007-08-24 06:17:19 +0000239 if (SplitData.empty())
240 return false;
241
Devang Patel0aaeb172007-08-08 22:25:28 +0000242 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000243 // FIXME : Implement cost analysis.
244 unsigned MostProfitableSDIndex = 0;
245 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000246
Devang Patelbc5fe632007-08-07 00:25:56 +0000247 if (Changed)
248 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000249
Devang Patelbc5fe632007-08-07 00:25:56 +0000250 return Changed;
251}
252
Devang Patel2545f7b2007-08-09 01:39:01 +0000253/// Return true if V is a induction variable or induction variable's
254/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000255void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000256
257 Instruction *I = dyn_cast<Instruction>(V);
258 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000259 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000260
261 // Check if I is a phi node from loop header or not.
262 if (PHINode *PN = dyn_cast<PHINode>(V)) {
263 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000264 IndVar = PN;
265 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000266 }
267 }
268
269 // Check if I is a add instruction whose one operand is
270 // phi node from loop header and second operand is constant.
271 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000272 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000273
274 Value *Op0 = I->getOperand(0);
275 Value *Op1 = I->getOperand(1);
276
277 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
278 if (PN->getParent() == L->getHeader()
279 && isa<ConstantInt>(Op1)) {
280 IndVar = PN;
281 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000282 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000283 }
284 }
285
286 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
287 if (PN->getParent() == L->getHeader()
288 && isa<ConstantInt>(Op0)) {
289 IndVar = PN;
290 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000291 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000292 }
293 }
294
Devang Patel61571ca2007-08-10 00:33:50 +0000295 return;
296}
297
298// Find loop's exit condition and associated induction variable.
299void LoopIndexSplit::findLoopConditionals() {
300
Devang Patel9263fc32007-08-20 23:51:18 +0000301 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000302
303 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
304 I != E; ++I) {
305 BasicBlock *BB = *I;
306 if (!L->isLoopExit(BB))
307 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000308 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000309 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000310 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000311 }
312
Devang Patel9263fc32007-08-20 23:51:18 +0000313 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000314 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000315
316 // If exiting block is neither loop header nor loop latch then this loop is
317 // not suitable.
318 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
319 return;
320
Devang Patel61571ca2007-08-10 00:33:50 +0000321 // If exit block's terminator is conditional branch inst then we have found
322 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000323 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000324 if (!BR || BR->isUnconditional())
325 return;
326
327 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
328 if (!CI)
329 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000330
331 // FIXME
332 if (CI->getPredicate() == ICmpInst::ICMP_SGT
333 || CI->getPredicate() == ICmpInst::ICMP_UGT
334 || CI->getPredicate() == ICmpInst::ICMP_SGE
335 || CI->getPredicate() == ICmpInst::ICMP_UGE)
336 return;
337
Devang Patel61571ca2007-08-10 00:33:50 +0000338 ExitCondition = CI;
339
340 // Exit condition's one operand is loop invariant exit value and second
341 // operand is SCEVAddRecExpr based on induction variable.
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)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000349 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000350 findIndVar(V1, L);
351 }
352 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000353 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000354 findIndVar(V0, L);
355 }
356
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000357 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000358 ExitCondition = NULL;
359 else if (IndVar) {
360 BasicBlock *Preheader = L->getLoopPreheader();
361 StartValue = IndVar->getIncomingValueForBlock(Preheader);
362 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000363}
364
Devang Patelbc5fe632007-08-07 00:25:56 +0000365/// Find condition inside a loop that is suitable candidate for index split.
366void LoopIndexSplit::findSplitCondition() {
367
Devang Patelc8dadbf2007-08-08 21:02:17 +0000368 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000369 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000370
Devang Patel2545f7b2007-08-09 01:39:01 +0000371 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
372 I != E; ++I) {
373 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000374
Devang Patel2545f7b2007-08-09 01:39:01 +0000375 // If this basic block does not terminate in a conditional branch
376 // then terminator is not a suitable split condition.
377 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
378 if (!BR)
379 continue;
380
381 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000382 continue;
383
Devang Patel2545f7b2007-08-09 01:39:01 +0000384 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000385 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000386 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000387
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000388 if (CI->getPredicate() == ICmpInst::ICMP_NE)
389 return;
390
Devang Patel7f526a82007-08-24 06:17:19 +0000391 // If split condition predicate is GT or GE then first execute
392 // false branch of split condition.
393 if (CI->getPredicate() != ICmpInst::ICMP_ULT
394 && CI->getPredicate() != ICmpInst::ICMP_SLT
395 && CI->getPredicate() != ICmpInst::ICMP_ULE
396 && CI->getPredicate() != ICmpInst::ICMP_SLE)
397 SD.UseTrueBranchFirst = false;
398
Devang Patel2545f7b2007-08-09 01:39:01 +0000399 // If one operand is loop invariant and second operand is SCEVAddRecExpr
400 // based on induction variable then CI is a candidate split condition.
401 Value *V0 = CI->getOperand(0);
402 Value *V1 = CI->getOperand(1);
403
404 SCEVHandle SH0 = SE->getSCEV(V0);
405 SCEVHandle SH1 = SE->getSCEV(V1);
406
407 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
408 SD.SplitValue = V0;
409 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000410 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
411 if (PN == IndVar)
412 SplitData.push_back(SD);
413 }
414 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
415 if (IndVarIncrement && IndVarIncrement == Insn)
416 SplitData.push_back(SD);
417 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000418 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000419 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
420 SD.SplitValue = V1;
421 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000422 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
423 if (PN == IndVar)
424 SplitData.push_back(SD);
425 }
426 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
427 if (IndVarIncrement && IndVarIncrement == Insn)
428 SplitData.push_back(SD);
429 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000430 }
431 }
432}
433
434/// processOneIterationLoop - Current loop L contains compare instruction
435/// that compares induction variable, IndVar, against loop invariant. If
436/// entire (i.e. meaningful) loop body is dominated by this compare
437/// instruction then loop body is executed only once. In such case eliminate
438/// loop structure surrounding this loop body. For example,
439/// for (int i = start; i < end; ++i) {
440/// if ( i == somevalue) {
441/// loop_body
442/// }
443/// }
444/// can be transformed into
445/// if (somevalue >= start && somevalue < end) {
446/// i = somevalue;
447/// loop_body
448/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000449bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000450
451 BasicBlock *Header = L->getHeader();
452
453 // First of all, check if SplitCondition dominates entire loop body
454 // or not.
455
456 // If SplitCondition is not in loop header then this loop is not suitable
457 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000458 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000459 return false;
460
Devang Patelbc5fe632007-08-07 00:25:56 +0000461 // If loop header includes loop variant instruction operands then
462 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000463 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000464 return false;
465
Devang Patel9263fc32007-08-20 23:51:18 +0000466 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000467 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000468 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000469 return false;
470
Devang Patel2bcb5012007-08-08 01:51:27 +0000471 // Update CFG.
472
Devang Patelc166b952007-08-20 20:49:01 +0000473 // Replace index variable with split value in loop body. Loop body is executed
474 // only when index variable is equal to split value.
475 IndVar->replaceAllUsesWith(SD.SplitValue);
476
477 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000478 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000479 BasicBlock *LatchSucc = NULL;
480 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
481 if (!BR)
482 return false;
483 Header->removePredecessor(Latch);
484 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
485 SI != E; ++SI) {
486 if (Header != *SI)
487 LatchSucc = *SI;
488 }
489 BR->setUnconditionalDest(LatchSucc);
490
Devang Patelbc5fe632007-08-07 00:25:56 +0000491 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000492 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000493
Devang Patelbc5fe632007-08-07 00:25:56 +0000494 // Replace split condition in header.
495 // Transform
496 // SplitCondition : icmp eq i32 IndVar, SplitValue
497 // into
498 // c1 = icmp uge i32 SplitValue, StartValue
499 // c2 = icmp ult i32 vSplitValue, ExitValue
500 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000501 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000502 Instruction *C1 = new ICmpInst(SignedPredicate ?
503 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000504 SD.SplitValue, StartValue, "lisplit",
505 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000506 Instruction *C2 = new ICmpInst(SignedPredicate ?
507 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000508 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000509 Terminator);
510 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
511 Terminator);
512 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
513 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000514
Devang Patelbc5fe632007-08-07 00:25:56 +0000515 // Now, clear latch block. Remove instructions that are responsible
516 // to increment induction variable.
517 Instruction *LTerminator = Latch->getTerminator();
518 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
519 LB != LE; ) {
520 Instruction *I = LB;
521 ++LB;
522 if (isa<PHINode>(I) || I == LTerminator)
523 continue;
524
Devang Patel59e0c062007-08-14 01:30:57 +0000525 if (I == IndVarIncrement)
526 I->replaceAllUsesWith(ExitValue);
527 else
528 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000529 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000530 }
531
Devang Patel901f67e2007-08-10 18:07:13 +0000532 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000533
534 // Update Dominator Info.
535 // Only CFG change done is to remove Latch to Header edge. This
536 // does not change dominator tree because Latch did not dominate
537 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000538 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000539 DominanceFrontier::iterator HeaderDF = DF->find(Header);
540 if (HeaderDF != DF->end())
541 DF->removeFromFrontier(HeaderDF, Header);
542
543 DominanceFrontier::iterator LatchDF = DF->find(Latch);
544 if (LatchDF != DF->end())
545 DF->removeFromFrontier(LatchDF, Header);
546 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000547 return true;
548}
549
550// If loop header includes loop variant instruction operands then
551// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000552bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000553
554 Instruction *Terminator = Header->getTerminator();
555 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
556 BI != BE; ++BI) {
557 Instruction *I = BI;
558
Devang Patel59e0c062007-08-14 01:30:57 +0000559 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000560 if (isa<PHINode>(I))
561 continue;
562
563 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000564 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000565 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000566
Devang Patel2545f7b2007-08-09 01:39:01 +0000567 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000568 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000569 continue;
570
571 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000572 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000573 continue;
574
Devang Patelbc5fe632007-08-07 00:25:56 +0000575 // Terminator is also harmless.
576 if (I == Terminator)
577 continue;
578
579 // Otherwise we have a instruction that may not be safe.
580 return false;
581 }
582
583 return true;
584}
585
Devang Patel9263fc32007-08-20 23:51:18 +0000586// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000587// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000588bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
589 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000590
Devang Patel9263fc32007-08-20 23:51:18 +0000591 for (BasicBlock::iterator BI = ExitingBlock->begin(),
592 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000593 Instruction *I = BI;
594
Devang Patel59e0c062007-08-14 01:30:57 +0000595 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000596 if (isa<PHINode>(I))
597 continue;
598
Devang Patel2545f7b2007-08-09 01:39:01 +0000599 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000600 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000601 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000602
Devang Patel2545f7b2007-08-09 01:39:01 +0000603 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000604 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000605
606 Value *Op0 = I->getOperand(0);
607 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000608 PHINode *PN = NULL;
609 ConstantInt *CI = NULL;
610
611 if ((PN = dyn_cast<PHINode>(Op0))) {
612 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000613 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000614 } else
615 if ((PN = dyn_cast<PHINode>(Op1))) {
616 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000617 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000618 }
619
Devang Patel61571ca2007-08-10 00:33:50 +0000620 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000621 continue;
622 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000623
Devang Patelbc5fe632007-08-07 00:25:56 +0000624 // I is an Exit condition if next instruction is block terminator.
625 // Exit condition is OK if it compares loop invariant exit value,
626 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000627 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000628 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000629 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000630 }
631
Devang Patel9263fc32007-08-20 23:51:18 +0000632 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000633 continue;
634
Devang Patelbc5fe632007-08-07 00:25:56 +0000635 // Otherwise we have instruction that may not be safe.
636 return false;
637 }
638
Devang Patel9263fc32007-08-20 23:51:18 +0000639 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000640 return true;
641}
642
Devang Patel60a94c72007-08-14 18:35:57 +0000643/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
644/// This routine is used to remove split condition's dead branch, dominated by
645/// DeadBB. LiveBB dominates split conidition's other branch.
646void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
647 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000648
Devang Patelf4277122007-08-15 03:31:47 +0000649 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000650 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000651 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
652 if (DeadBBDF != DF->end()) {
653 SmallVector<BasicBlock *, 8> PredBlocks;
654
655 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
656 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
657 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
658 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000659 FrontierBBs.push_back(FrontierBB);
660
Devang Patelf4277122007-08-15 03:31:47 +0000661 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
662 PredBlocks.clear();
663 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
664 PI != PE; ++PI) {
665 BasicBlock *P = *PI;
666 if (P == DeadBB || DT->dominates(DeadBB, P))
667 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000668 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000669
Devang Patelf4277122007-08-15 03:31:47 +0000670 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
671 FBI != FBE; ++FBI) {
672 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
673 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
674 PE = PredBlocks.end(); PI != PE; ++PI) {
675 BasicBlock *P = *PI;
676 PN->removeIncomingValue(P);
677 }
678 }
679 else
680 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000681 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000682 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000683 }
Devang Patelf4277122007-08-15 03:31:47 +0000684
685 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
686 SmallVector<BasicBlock *, 32> WorkList;
687 DomTreeNode *DN = DT->getNode(DeadBB);
688 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
689 E = df_end(DN); DI != E; ++DI) {
690 BasicBlock *BB = DI->getBlock();
691 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000692 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000693 }
694
695 while (!WorkList.empty()) {
696 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
697 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
698 BBI != BBE; ++BBI) {
699 Instruction *I = BBI;
700 I->replaceAllUsesWith(UndefValue::get(I->getType()));
701 I->eraseFromParent();
702 }
703 LPM->deleteSimpleAnalysisValue(BB, LP);
704 DT->eraseNode(BB);
705 DF->removeBlock(BB);
706 LI->removeBlock(BB);
707 BB->eraseFromParent();
708 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000709
710 // Update Frontier BBs' dominator info.
711 while (!FrontierBBs.empty()) {
712 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
713 BasicBlock *NewDominator = FBB->getSinglePredecessor();
714 if (!NewDominator) {
715 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
716 NewDominator = *PI;
717 ++PI;
718 if (NewDominator != LiveBB) {
719 for(; PI != PE; ++PI) {
720 BasicBlock *P = *PI;
721 if (P == LiveBB) {
722 NewDominator = LiveBB;
723 break;
724 }
725 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
726 }
727 }
728 }
729 assert (NewDominator && "Unable to fix dominator info.");
730 DT->changeImmediateDominator(FBB, NewDominator);
731 DF->changeImmediateDominator(FBB, NewDominator, DT);
732 }
733
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000734}
735
Devang Pateld662ace2007-08-22 18:27:01 +0000736/// safeSplitCondition - Return true if it is possible to
737/// split loop using given split condition.
738bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000739
Devang Pateld662ace2007-08-22 18:27:01 +0000740 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000741
Devang Pateld662ace2007-08-22 18:27:01 +0000742 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000743 // In triangle loop, split condition is in header and one of the
744 // the split destination is loop latch. If split condition is EQ
745 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000746 BasicBlock *Latch = L->getLoopLatch();
747 BranchInst *SplitTerminator =
748 cast<BranchInst>(SplitCondBlock->getTerminator());
749 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
750 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
751 if (L->getHeader() == SplitCondBlock
752 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000753 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000754
Devang Patelac7c7c22007-08-27 21:34:31 +0000755 // If split condition branches heads do not have single predecessor,
756 // SplitCondBlock, then is not possible to remove inactive branch.
757 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000758 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000759
Devang Patel4e2075d2007-08-24 05:36:56 +0000760 // Finally this split condition is safe only if merge point for
761 // split condition branch is loop latch. This check along with previous
762 // check, to ensure that exit condition is in either loop latch or header,
763 // filters all loops with non-empty loop body between merge point
764 // and exit condition.
765 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
766 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
767 if (Succ0DF->second.count(Latch))
768 return true;
769
770 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
771 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
772 if (Succ1DF->second.count(Latch))
773 return true;
774
775 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000776}
777
Devang Pateledea5b32007-08-25 00:56:38 +0000778/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
779/// based on split value.
780void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
781
782 ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
783 const Type *Ty = SD.SplitValue->getType();
784 bool Sign = ExitCondition->isSignedPredicate();
785 BasicBlock *Preheader = L->getLoopPreheader();
786 Instruction *PHTerminator = Preheader->getTerminator();
787
788 // Initially use split value as upper loop bound for first loop and lower loop
789 // bound for second loop.
790 Value *AEV = SD.SplitValue;
791 Value *BSV = SD.SplitValue;
792
793 switch (ExitCondition->getPredicate()) {
794 case ICmpInst::ICMP_SGT:
795 case ICmpInst::ICMP_UGT:
796 case ICmpInst::ICMP_SGE:
797 case ICmpInst::ICMP_UGE:
798 default:
799 assert (0 && "Unexpected exit condition predicate");
800
801 case ICmpInst::ICMP_SLT:
802 case ICmpInst::ICMP_ULT:
803 {
804 switch (SP) {
805 case ICmpInst::ICMP_SLT:
806 case ICmpInst::ICMP_ULT:
807 //
808 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
809 //
810 // is transformed into
811 // AEV = BSV = SV
812 // for (i = LB; i < min(UB, AEV); ++i)
813 // A;
814 // for (i = max(LB, BSV); i < UB; ++i);
815 // B;
816 break;
817 case ICmpInst::ICMP_SLE:
818 case ICmpInst::ICMP_ULE:
819 {
820 //
821 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
822 //
823 // is transformed into
824 //
825 // AEV = SV + 1
826 // BSV = SV + 1
827 // for (i = LB; i < min(UB, AEV); ++i)
828 // A;
829 // for (i = max(LB, BSV); i < UB; ++i)
830 // B;
831 BSV = BinaryOperator::createAdd(SD.SplitValue,
832 ConstantInt::get(Ty, 1, Sign),
833 "lsplit.add", PHTerminator);
834 AEV = BSV;
835 }
836 break;
837 case ICmpInst::ICMP_SGE:
838 case ICmpInst::ICMP_UGE:
839 //
840 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
841 //
842 // is transformed into
843 // AEV = BSV = SV
844 // for (i = LB; i < min(UB, AEV); ++i)
845 // B;
846 // for (i = max(BSV, LB); i < UB; ++i)
847 // A;
848 break;
849 case ICmpInst::ICMP_SGT:
850 case ICmpInst::ICMP_UGT:
851 {
852 //
853 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
854 //
855 // is transformed into
856 //
857 // BSV = AEV = SV + 1
858 // for (i = LB; i < min(UB, AEV); ++i)
859 // B;
860 // for (i = max(LB, BSV); i < UB; ++i)
861 // A;
862 BSV = BinaryOperator::createAdd(SD.SplitValue,
863 ConstantInt::get(Ty, 1, Sign),
864 "lsplit.add", PHTerminator);
865 AEV = BSV;
866 }
867 break;
868 default:
869 assert (0 && "Unexpected split condition predicate");
870 break;
871 } // end switch (SP)
872 }
873 break;
874 case ICmpInst::ICMP_SLE:
875 case ICmpInst::ICMP_ULE:
876 {
877 switch (SP) {
878 case ICmpInst::ICMP_SLT:
879 case ICmpInst::ICMP_ULT:
880 //
881 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
882 //
883 // is transformed into
884 // AEV = SV - 1;
885 // BSV = SV;
886 // for (i = LB; i <= min(UB, AEV); ++i)
887 // A;
888 // for (i = max(LB, BSV); i <= UB; ++i)
889 // B;
890 AEV = BinaryOperator::createSub(SD.SplitValue,
891 ConstantInt::get(Ty, 1, Sign),
892 "lsplit.sub", PHTerminator);
893 break;
894 case ICmpInst::ICMP_SLE:
895 case ICmpInst::ICMP_ULE:
896 //
897 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
898 //
899 // is transformed into
900 // AEV = SV;
901 // BSV = SV + 1;
902 // for (i = LB; i <= min(UB, AEV); ++i)
903 // A;
904 // for (i = max(LB, BSV); i <= UB; ++i)
905 // B;
906 BSV = BinaryOperator::createAdd(SD.SplitValue,
907 ConstantInt::get(Ty, 1, Sign),
908 "lsplit.add", PHTerminator);
909 break;
910 case ICmpInst::ICMP_SGT:
911 case ICmpInst::ICMP_UGT:
912 //
913 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
914 //
915 // is transformed into
916 // AEV = SV;
917 // BSV = SV + 1;
918 // for (i = LB; i <= min(AEV, UB); ++i)
919 // B;
920 // for (i = max(LB, BSV); i <= UB; ++i)
921 // A;
922 BSV = BinaryOperator::createAdd(SD.SplitValue,
923 ConstantInt::get(Ty, 1, Sign),
924 "lsplit.add", PHTerminator);
925 break;
926 case ICmpInst::ICMP_SGE:
927 case ICmpInst::ICMP_UGE:
928 // ** TODO **
929 //
930 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
931 //
932 // is transformed into
933 // AEV = SV - 1;
934 // BSV = SV;
935 // for (i = LB; i <= min(AEV, UB); ++i)
936 // B;
937 // for (i = max(LB, BSV); i <= UB; ++i)
938 // A;
939 AEV = BinaryOperator::createSub(SD.SplitValue,
940 ConstantInt::get(Ty, 1, Sign),
941 "lsplit.sub", PHTerminator);
942 break;
943 default:
944 assert (0 && "Unexpected split condition predicate");
945 break;
946 } // end switch (SP)
947 }
948 break;
949 }
950
951 // Calculate ALoop induction variable's new exiting value and
952 // BLoop induction variable's new starting value. Calculuate these
953 // values in original loop's preheader.
954 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
955 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000956 Value *C1 = new ICmpInst(Sign ?
957 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
958 AEV,
959 ExitCondition->getOperand(ExitValueNum),
960 "lsplit.ev", PHTerminator);
961 SD.A_ExitValue = new SelectInst(C1, AEV,
962 ExitCondition->getOperand(ExitValueNum),
963 "lsplit.ev", PHTerminator);
964
965 Value *C2 = new ICmpInst(Sign ?
966 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
967 BSV, StartValue, "lsplit.sv",
968 PHTerminator);
969 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
970 "lsplit.sv", PHTerminator);
971}
972
Devang Pateld662ace2007-08-22 18:27:01 +0000973/// splitLoop - Split current loop L in two loops using split information
974/// SD. Update dominator information. Maintain LCSSA form.
975bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
976
977 if (!safeSplitCondition(SD))
978 return false;
979
Devang Patela0ac7262007-08-22 19:33:29 +0000980 // After loop is cloned there are two loops.
981 //
982 // First loop, referred as ALoop, executes first part of loop's iteration
983 // space split. Second loop, referred as BLoop, executes remaining
984 // part of loop's iteration space.
985 //
986 // ALoop's exit edge enters BLoop's header through a forwarding block which
987 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +0000988 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +0000989
Devang Pateledea5b32007-08-25 00:56:38 +0000990 // Calculate ALoop induction variable's new exiting value and
991 // BLoop induction variable's new starting value.
992 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +0000993
Devang Patela0ac7262007-08-22 19:33:29 +0000994 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000995 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +0000996 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +0000997 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +0000998 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000999
Devang Patela0ac7262007-08-22 19:33:29 +00001000 //[*] ALoop's exiting edge BLoop's header.
1001 // ALoop's original exit block becomes BLoop's exit block.
1002 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1003 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1004 BranchInst *A_ExitInsn =
1005 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1006 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1007 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1008 if (L->contains(B_ExitBlock)) {
1009 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1010 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001011 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001012 A_ExitInsn->setSuccessor(1, B_Header);
1013
1014 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001015 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001016
Devang Patela0ac7262007-08-22 19:33:29 +00001017 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1018 // original loop's preheader. Add incoming PHINode values from
1019 // ALoop's exiting block. Update BLoop header's domiantor info.
1020
Devang Patel59e0c062007-08-14 01:30:57 +00001021 // Collect inverse map of Header PHINodes.
1022 DenseMap<Value *, Value *> InverseMap;
1023 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1024 BE = L->getHeader()->end(); BI != BE; ++BI) {
1025 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1026 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1027 InverseMap[PNClone] = PN;
1028 } else
1029 break;
1030 }
Devang Pateledea5b32007-08-25 00:56:38 +00001031
Devang Patela0ac7262007-08-22 19:33:29 +00001032 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001033 BI != BE; ++BI) {
1034 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001035 // Remove incoming value from original preheader.
1036 PN->removeIncomingValue(Preheader);
1037
1038 // Add incoming value from A_ExitingBlock.
1039 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001040 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001041 else {
1042 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001043 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1044 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001045 }
1046 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001047 break;
1048 }
Devang Patela0ac7262007-08-22 19:33:29 +00001049 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1050 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001051
Devang Patela0ac7262007-08-22 19:33:29 +00001052 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1053 // block. Remove incoming PHINode values from ALoop's exiting block.
1054 // Add new incoming values from BLoop's incoming exiting value.
1055 // Update BLoop exit block's dominator info..
1056 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1057 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001058 BI != BE; ++BI) {
1059 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001060 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1061 B_ExitingBlock);
1062 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001063 } else
1064 break;
1065 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001066
Devang Patela0ac7262007-08-22 19:33:29 +00001067 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1068 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001069
Devang Patela0ac7262007-08-22 19:33:29 +00001070 //[*] Split ALoop's exit edge. This creates a new block which
1071 // serves two purposes. First one is to hold PHINode defnitions
1072 // to ensure that ALoop's LCSSA form. Second use it to act
1073 // as a preheader for BLoop.
1074 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001075
Devang Patela0ac7262007-08-22 19:33:29 +00001076 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1077 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1078 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001079 BI != BE; ++BI) {
1080 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001081 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001082 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001083 newPHI->addIncoming(V1, A_ExitingBlock);
1084 A_ExitBlock->getInstList().push_front(newPHI);
1085 PN->removeIncomingValue(A_ExitBlock);
1086 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001087 } else
1088 break;
1089 }
1090
Devang Patela0ac7262007-08-22 19:33:29 +00001091 //[*] Eliminate split condition's inactive branch from ALoop.
1092 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1093 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001094 BasicBlock *A_InactiveBranch = NULL;
1095 BasicBlock *A_ActiveBranch = NULL;
1096 if (SD.UseTrueBranchFirst) {
1097 A_ActiveBranch = A_BR->getSuccessor(0);
1098 A_InactiveBranch = A_BR->getSuccessor(1);
1099 } else {
1100 A_ActiveBranch = A_BR->getSuccessor(1);
1101 A_InactiveBranch = A_BR->getSuccessor(0);
1102 }
Devang Patel4e585c72007-08-24 19:32:26 +00001103 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001104 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1105
1106 //[*] Eliminate split condition's inactive branch in from BLoop.
1107 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1108 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001109 BasicBlock *B_InactiveBranch = NULL;
1110 BasicBlock *B_ActiveBranch = NULL;
1111 if (SD.UseTrueBranchFirst) {
1112 B_ActiveBranch = B_BR->getSuccessor(1);
1113 B_InactiveBranch = B_BR->getSuccessor(0);
1114 } else {
1115 B_ActiveBranch = B_BR->getSuccessor(0);
1116 B_InactiveBranch = B_BR->getSuccessor(1);
1117 }
Devang Patel4e585c72007-08-24 19:32:26 +00001118 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001119 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1120
Devang Patelcd71bed2007-08-25 02:39:24 +00001121 BasicBlock *A_Header = L->getHeader();
1122 if (A_ExitingBlock == A_Header)
1123 return true;
1124
1125 //[*] Move exit condition into split condition block to avoid
1126 // executing dead loop iteration.
1127 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1128 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1129 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1130
1131 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1132 SD.SplitCondition, IndVar, IndVarIncrement, ALoop);
1133
1134 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1135 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1136
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001137 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001138}
Devang Patelcd71bed2007-08-25 02:39:24 +00001139
1140// moveExitCondition - Move exit condition EC into split condition block CondBB.
1141void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1142 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1143 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1144
1145 BasicBlock *ExitingBB = EC->getParent();
1146 Instruction *CurrentBR = CondBB->getTerminator();
1147
1148 // Move exit condition into split condition block.
1149 EC->moveBefore(CurrentBR);
1150 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1151
1152 // Move exiting block's branch into split condition block. Update its branch
1153 // destination.
1154 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1155 ExitingBR->moveBefore(CurrentBR);
1156 if (ExitingBR->getSuccessor(0) == ExitBB)
1157 ExitingBR->setSuccessor(1, ActiveBB);
1158 else
1159 ExitingBR->setSuccessor(0, ActiveBB);
1160
1161 // Remove split condition and current split condition branch.
1162 SC->eraseFromParent();
1163 CurrentBR->eraseFromParent();
1164
1165 // Connect exiting block to split condition block.
1166 new BranchInst(CondBB, ExitingBB);
1167
1168 // Update PHINodes
1169 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1170
1171 // Fix dominator info.
1172 // ExitBB is now dominated by CondBB
1173 DT->changeImmediateDominator(ExitBB, CondBB);
1174 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1175
1176 // Basicblocks dominated by ActiveBB may have ExitingBB or
1177 // a basic block outside the loop in their DF list. If so,
1178 // replace it with CondBB.
1179 DomTreeNode *Node = DT->getNode(ActiveBB);
1180 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1181 DI != DE; ++DI) {
1182 BasicBlock *BB = DI->getBlock();
1183 DominanceFrontier::iterator BBDF = DF->find(BB);
1184 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1185 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1186 while (DomSetI != DomSetE) {
1187 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1188 ++DomSetI;
1189 BasicBlock *DFBB = *CurrentItr;
1190 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1191 BBDF->second.erase(DFBB);
1192 BBDF->second.insert(CondBB);
1193 }
1194 }
1195 }
1196}
1197
1198/// updatePHINodes - CFG has been changed.
1199/// Before
1200/// - ExitBB's single predecessor was Latch
1201/// - Latch's second successor was Header
1202/// Now
1203/// - ExitBB's single predecessor was Header
1204/// - Latch's one and only successor was Header
1205///
1206/// Update ExitBB PHINodes' to reflect this change.
1207void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1208 BasicBlock *Header,
1209 PHINode *IV, Instruction *IVIncrement) {
1210
1211 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1212 BI != BE; ++BI) {
1213 PHINode *PN = dyn_cast<PHINode>(BI);
1214 if (!PN)
1215 break;
1216
1217 Value *V = PN->getIncomingValueForBlock(Latch);
1218 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1219 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1220 // (i.e. PN :)).
1221 // The second use is in Header and it is new incoming value for PN.
1222 PHINode *U1 = NULL;
1223 PHINode *U2 = NULL;
1224 Value *NewV = NULL;
1225 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1226 UI != E; ++UI) {
1227 if (!U1)
1228 U1 = cast<PHINode>(*UI);
1229 else if (!U2)
1230 U2 = cast<PHINode>(*UI);
1231 else
1232 assert ( 0 && "Unexpected third use of this PHINode");
1233 }
1234 assert (U1 && U2 && "Unable to find two uses");
1235
1236 if (U1->getParent() == Header)
1237 NewV = U1;
1238 else
1239 NewV = U2;
1240 PN->addIncoming(NewV, Header);
1241
1242 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1243 // If this instruction is IVIncrement then IV is new incoming value
1244 // from header otherwise this instruction must be incoming value from
1245 // header because loop is in LCSSA form.
1246 if (PHI == IVIncrement)
1247 PN->addIncoming(IV, Header);
1248 else
1249 PN->addIncoming(V, Header);
1250 } else
1251 // Otherwise this is an incoming value from header because loop is in
1252 // LCSSA form.
1253 PN->addIncoming(V, Header);
1254
1255 // Remove incoming value from Latch.
1256 PN->removeIncomingValue(Latch);
1257 }
1258}