blob: 3a046655d5efb1817a1f73052226f8a81bb7f7c0 [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
Devang Patel4cebc342007-09-10 18:33:42 +0000335 || CI->getPredicate() == ICmpInst::ICMP_UGE
336 || CI->getPredicate() == ICmpInst::ICMP_EQ
337 || CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Pateledea5b32007-08-25 00:56:38 +0000338 return;
339
Devang Patel61571ca2007-08-10 00:33:50 +0000340 ExitCondition = CI;
341
342 // Exit condition's one operand is loop invariant exit value and second
343 // operand is SCEVAddRecExpr based on induction variable.
344 Value *V0 = CI->getOperand(0);
345 Value *V1 = CI->getOperand(1);
346
347 SCEVHandle SH0 = SE->getSCEV(V0);
348 SCEVHandle SH1 = SE->getSCEV(V1);
349
350 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000351 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000352 findIndVar(V1, L);
353 }
354 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000355 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000356 findIndVar(V0, L);
357 }
358
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000359 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000360 ExitCondition = NULL;
361 else if (IndVar) {
362 BasicBlock *Preheader = L->getLoopPreheader();
363 StartValue = IndVar->getIncomingValueForBlock(Preheader);
364 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000365}
366
Devang Patelbc5fe632007-08-07 00:25:56 +0000367/// Find condition inside a loop that is suitable candidate for index split.
368void LoopIndexSplit::findSplitCondition() {
369
Devang Patelc8dadbf2007-08-08 21:02:17 +0000370 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000371 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000372
Devang Patel2545f7b2007-08-09 01:39:01 +0000373 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
374 I != E; ++I) {
375 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000376
Devang Patel2545f7b2007-08-09 01:39:01 +0000377 // If this basic block does not terminate in a conditional branch
378 // then terminator is not a suitable split condition.
379 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
380 if (!BR)
381 continue;
382
383 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000384 continue;
385
Devang Patel2545f7b2007-08-09 01:39:01 +0000386 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000387 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000388 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000389
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000390 if (CI->getPredicate() == ICmpInst::ICMP_NE)
391 return;
392
Devang Patel7f526a82007-08-24 06:17:19 +0000393 // If split condition predicate is GT or GE then first execute
394 // false branch of split condition.
395 if (CI->getPredicate() != ICmpInst::ICMP_ULT
396 && CI->getPredicate() != ICmpInst::ICMP_SLT
397 && CI->getPredicate() != ICmpInst::ICMP_ULE
398 && CI->getPredicate() != ICmpInst::ICMP_SLE)
399 SD.UseTrueBranchFirst = false;
400
Devang Patel2545f7b2007-08-09 01:39:01 +0000401 // If one operand is loop invariant and second operand is SCEVAddRecExpr
402 // based on induction variable then CI is a candidate split condition.
403 Value *V0 = CI->getOperand(0);
404 Value *V1 = CI->getOperand(1);
405
406 SCEVHandle SH0 = SE->getSCEV(V0);
407 SCEVHandle SH1 = SE->getSCEV(V1);
408
409 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
410 SD.SplitValue = V0;
411 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000412 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
413 if (PN == IndVar)
414 SplitData.push_back(SD);
415 }
416 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
417 if (IndVarIncrement && IndVarIncrement == Insn)
418 SplitData.push_back(SD);
419 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000420 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000421 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
422 SD.SplitValue = V1;
423 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000424 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
425 if (PN == IndVar)
426 SplitData.push_back(SD);
427 }
428 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
429 if (IndVarIncrement && IndVarIncrement == Insn)
430 SplitData.push_back(SD);
431 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000432 }
433 }
434}
435
436/// processOneIterationLoop - Current loop L contains compare instruction
437/// that compares induction variable, IndVar, against loop invariant. If
438/// entire (i.e. meaningful) loop body is dominated by this compare
439/// instruction then loop body is executed only once. In such case eliminate
440/// loop structure surrounding this loop body. For example,
441/// for (int i = start; i < end; ++i) {
442/// if ( i == somevalue) {
443/// loop_body
444/// }
445/// }
446/// can be transformed into
447/// if (somevalue >= start && somevalue < end) {
448/// i = somevalue;
449/// loop_body
450/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000451bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000452
453 BasicBlock *Header = L->getHeader();
454
455 // First of all, check if SplitCondition dominates entire loop body
456 // or not.
457
458 // If SplitCondition is not in loop header then this loop is not suitable
459 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000460 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000461 return false;
462
Devang Patelbc5fe632007-08-07 00:25:56 +0000463 // If loop header includes loop variant instruction operands then
464 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000465 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000466 return false;
467
Devang Patel9263fc32007-08-20 23:51:18 +0000468 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000469 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000470 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000471 return false;
472
Devang Patel2bcb5012007-08-08 01:51:27 +0000473 // Update CFG.
474
Devang Patelc166b952007-08-20 20:49:01 +0000475 // Replace index variable with split value in loop body. Loop body is executed
476 // only when index variable is equal to split value.
477 IndVar->replaceAllUsesWith(SD.SplitValue);
478
479 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000480 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000481 BasicBlock *LatchSucc = NULL;
482 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
483 if (!BR)
484 return false;
485 Header->removePredecessor(Latch);
486 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
487 SI != E; ++SI) {
488 if (Header != *SI)
489 LatchSucc = *SI;
490 }
491 BR->setUnconditionalDest(LatchSucc);
492
Devang Patelbc5fe632007-08-07 00:25:56 +0000493 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000494 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000495
Devang Patelbc5fe632007-08-07 00:25:56 +0000496 // Replace split condition in header.
497 // Transform
498 // SplitCondition : icmp eq i32 IndVar, SplitValue
499 // into
500 // c1 = icmp uge i32 SplitValue, StartValue
501 // c2 = icmp ult i32 vSplitValue, ExitValue
502 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000503 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000504 Instruction *C1 = new ICmpInst(SignedPredicate ?
505 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000506 SD.SplitValue, StartValue, "lisplit",
507 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000508 Instruction *C2 = new ICmpInst(SignedPredicate ?
509 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000510 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000511 Terminator);
512 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
513 Terminator);
514 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
515 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000516
Devang Patelbc5fe632007-08-07 00:25:56 +0000517 // Now, clear latch block. Remove instructions that are responsible
518 // to increment induction variable.
519 Instruction *LTerminator = Latch->getTerminator();
520 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
521 LB != LE; ) {
522 Instruction *I = LB;
523 ++LB;
524 if (isa<PHINode>(I) || I == LTerminator)
525 continue;
526
Devang Patel59e0c062007-08-14 01:30:57 +0000527 if (I == IndVarIncrement)
528 I->replaceAllUsesWith(ExitValue);
529 else
530 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000531 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000532 }
533
Devang Patel901f67e2007-08-10 18:07:13 +0000534 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000535
536 // Update Dominator Info.
537 // Only CFG change done is to remove Latch to Header edge. This
538 // does not change dominator tree because Latch did not dominate
539 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000540 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000541 DominanceFrontier::iterator HeaderDF = DF->find(Header);
542 if (HeaderDF != DF->end())
543 DF->removeFromFrontier(HeaderDF, Header);
544
545 DominanceFrontier::iterator LatchDF = DF->find(Latch);
546 if (LatchDF != DF->end())
547 DF->removeFromFrontier(LatchDF, Header);
548 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000549 return true;
550}
551
552// If loop header includes loop variant instruction operands then
553// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000554bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000555
556 Instruction *Terminator = Header->getTerminator();
557 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
558 BI != BE; ++BI) {
559 Instruction *I = BI;
560
Devang Patel59e0c062007-08-14 01:30:57 +0000561 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000562 if (isa<PHINode>(I))
563 continue;
564
565 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000566 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000567 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000568
Devang Patel2545f7b2007-08-09 01:39:01 +0000569 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000570 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000571 continue;
572
573 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000574 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000575 continue;
576
Devang Patelbc5fe632007-08-07 00:25:56 +0000577 // Terminator is also harmless.
578 if (I == Terminator)
579 continue;
580
581 // Otherwise we have a instruction that may not be safe.
582 return false;
583 }
584
585 return true;
586}
587
Devang Patel9263fc32007-08-20 23:51:18 +0000588// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000589// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000590bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
591 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000592
Devang Patel9263fc32007-08-20 23:51:18 +0000593 for (BasicBlock::iterator BI = ExitingBlock->begin(),
594 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000595 Instruction *I = BI;
596
Devang Patel59e0c062007-08-14 01:30:57 +0000597 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000598 if (isa<PHINode>(I))
599 continue;
600
Devang Patel2545f7b2007-08-09 01:39:01 +0000601 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000602 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000603 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000604
Devang Patel2545f7b2007-08-09 01:39:01 +0000605 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000606 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000607
608 Value *Op0 = I->getOperand(0);
609 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000610 PHINode *PN = NULL;
611 ConstantInt *CI = NULL;
612
613 if ((PN = dyn_cast<PHINode>(Op0))) {
614 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000615 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000616 } else
617 if ((PN = dyn_cast<PHINode>(Op1))) {
618 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000619 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000620 }
621
Devang Patel61571ca2007-08-10 00:33:50 +0000622 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000623 continue;
624 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000625
Devang Patelbc5fe632007-08-07 00:25:56 +0000626 // I is an Exit condition if next instruction is block terminator.
627 // Exit condition is OK if it compares loop invariant exit value,
628 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000629 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000630 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000631 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000632 }
633
Devang Patel9263fc32007-08-20 23:51:18 +0000634 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000635 continue;
636
Devang Patelbc5fe632007-08-07 00:25:56 +0000637 // Otherwise we have instruction that may not be safe.
638 return false;
639 }
640
Devang Patel9263fc32007-08-20 23:51:18 +0000641 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000642 return true;
643}
644
Devang Patel60a94c72007-08-14 18:35:57 +0000645/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
646/// This routine is used to remove split condition's dead branch, dominated by
647/// DeadBB. LiveBB dominates split conidition's other branch.
648void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
649 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000650
Devang Patelf4277122007-08-15 03:31:47 +0000651 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000652 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000653 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
654 if (DeadBBDF != DF->end()) {
655 SmallVector<BasicBlock *, 8> PredBlocks;
656
657 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
658 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
659 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
660 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000661 FrontierBBs.push_back(FrontierBB);
662
Devang Patelf4277122007-08-15 03:31:47 +0000663 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
664 PredBlocks.clear();
665 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
666 PI != PE; ++PI) {
667 BasicBlock *P = *PI;
668 if (P == DeadBB || DT->dominates(DeadBB, P))
669 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000670 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000671
Devang Patelf4277122007-08-15 03:31:47 +0000672 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
673 FBI != FBE; ++FBI) {
674 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
675 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
676 PE = PredBlocks.end(); PI != PE; ++PI) {
677 BasicBlock *P = *PI;
678 PN->removeIncomingValue(P);
679 }
680 }
681 else
682 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000683 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000684 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000685 }
Devang Patelf4277122007-08-15 03:31:47 +0000686
687 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
688 SmallVector<BasicBlock *, 32> WorkList;
689 DomTreeNode *DN = DT->getNode(DeadBB);
690 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
691 E = df_end(DN); DI != E; ++DI) {
692 BasicBlock *BB = DI->getBlock();
693 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000694 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000695 }
696
697 while (!WorkList.empty()) {
698 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
699 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
700 BBI != BBE; ++BBI) {
701 Instruction *I = BBI;
702 I->replaceAllUsesWith(UndefValue::get(I->getType()));
703 I->eraseFromParent();
704 }
705 LPM->deleteSimpleAnalysisValue(BB, LP);
706 DT->eraseNode(BB);
707 DF->removeBlock(BB);
708 LI->removeBlock(BB);
709 BB->eraseFromParent();
710 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000711
712 // Update Frontier BBs' dominator info.
713 while (!FrontierBBs.empty()) {
714 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
715 BasicBlock *NewDominator = FBB->getSinglePredecessor();
716 if (!NewDominator) {
717 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
718 NewDominator = *PI;
719 ++PI;
720 if (NewDominator != LiveBB) {
721 for(; PI != PE; ++PI) {
722 BasicBlock *P = *PI;
723 if (P == LiveBB) {
724 NewDominator = LiveBB;
725 break;
726 }
727 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
728 }
729 }
730 }
731 assert (NewDominator && "Unable to fix dominator info.");
732 DT->changeImmediateDominator(FBB, NewDominator);
733 DF->changeImmediateDominator(FBB, NewDominator, DT);
734 }
735
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000736}
737
Devang Pateld662ace2007-08-22 18:27:01 +0000738/// safeSplitCondition - Return true if it is possible to
739/// split loop using given split condition.
740bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000741
Devang Pateld662ace2007-08-22 18:27:01 +0000742 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000743
Devang Pateld662ace2007-08-22 18:27:01 +0000744 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000745 // In triangle loop, split condition is in header and one of the
746 // the split destination is loop latch. If split condition is EQ
747 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000748 BasicBlock *Latch = L->getLoopLatch();
749 BranchInst *SplitTerminator =
750 cast<BranchInst>(SplitCondBlock->getTerminator());
751 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
752 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
753 if (L->getHeader() == SplitCondBlock
754 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000755 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000756
Devang Patelac7c7c22007-08-27 21:34:31 +0000757 // If split condition branches heads do not have single predecessor,
758 // SplitCondBlock, then is not possible to remove inactive branch.
759 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000760 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000761
Devang Patel4e2075d2007-08-24 05:36:56 +0000762 // Finally this split condition is safe only if merge point for
763 // split condition branch is loop latch. This check along with previous
764 // check, to ensure that exit condition is in either loop latch or header,
765 // filters all loops with non-empty loop body between merge point
766 // and exit condition.
767 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
768 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
769 if (Succ0DF->second.count(Latch))
770 return true;
771
772 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
773 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
774 if (Succ1DF->second.count(Latch))
775 return true;
776
777 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000778}
779
Devang Pateledea5b32007-08-25 00:56:38 +0000780/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
781/// based on split value.
782void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
783
784 ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
785 const Type *Ty = SD.SplitValue->getType();
786 bool Sign = ExitCondition->isSignedPredicate();
787 BasicBlock *Preheader = L->getLoopPreheader();
788 Instruction *PHTerminator = Preheader->getTerminator();
789
790 // Initially use split value as upper loop bound for first loop and lower loop
791 // bound for second loop.
792 Value *AEV = SD.SplitValue;
793 Value *BSV = SD.SplitValue;
794
795 switch (ExitCondition->getPredicate()) {
796 case ICmpInst::ICMP_SGT:
797 case ICmpInst::ICMP_UGT:
798 case ICmpInst::ICMP_SGE:
799 case ICmpInst::ICMP_UGE:
800 default:
801 assert (0 && "Unexpected exit condition predicate");
802
803 case ICmpInst::ICMP_SLT:
804 case ICmpInst::ICMP_ULT:
805 {
806 switch (SP) {
807 case ICmpInst::ICMP_SLT:
808 case ICmpInst::ICMP_ULT:
809 //
810 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
811 //
812 // is transformed into
813 // AEV = BSV = SV
814 // for (i = LB; i < min(UB, AEV); ++i)
815 // A;
816 // for (i = max(LB, BSV); i < UB; ++i);
817 // B;
818 break;
819 case ICmpInst::ICMP_SLE:
820 case ICmpInst::ICMP_ULE:
821 {
822 //
823 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
824 //
825 // is transformed into
826 //
827 // AEV = SV + 1
828 // BSV = SV + 1
829 // for (i = LB; i < min(UB, AEV); ++i)
830 // A;
831 // for (i = max(LB, BSV); i < UB; ++i)
832 // B;
833 BSV = BinaryOperator::createAdd(SD.SplitValue,
834 ConstantInt::get(Ty, 1, Sign),
835 "lsplit.add", PHTerminator);
836 AEV = BSV;
837 }
838 break;
839 case ICmpInst::ICMP_SGE:
840 case ICmpInst::ICMP_UGE:
841 //
842 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
843 //
844 // is transformed into
845 // AEV = BSV = SV
846 // for (i = LB; i < min(UB, AEV); ++i)
847 // B;
848 // for (i = max(BSV, LB); i < UB; ++i)
849 // A;
850 break;
851 case ICmpInst::ICMP_SGT:
852 case ICmpInst::ICMP_UGT:
853 {
854 //
855 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
856 //
857 // is transformed into
858 //
859 // BSV = AEV = SV + 1
860 // for (i = LB; i < min(UB, AEV); ++i)
861 // B;
862 // for (i = max(LB, BSV); i < UB; ++i)
863 // A;
864 BSV = BinaryOperator::createAdd(SD.SplitValue,
865 ConstantInt::get(Ty, 1, Sign),
866 "lsplit.add", PHTerminator);
867 AEV = BSV;
868 }
869 break;
870 default:
871 assert (0 && "Unexpected split condition predicate");
872 break;
873 } // end switch (SP)
874 }
875 break;
876 case ICmpInst::ICMP_SLE:
877 case ICmpInst::ICMP_ULE:
878 {
879 switch (SP) {
880 case ICmpInst::ICMP_SLT:
881 case ICmpInst::ICMP_ULT:
882 //
883 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
884 //
885 // is transformed into
886 // AEV = SV - 1;
887 // BSV = SV;
888 // for (i = LB; i <= min(UB, AEV); ++i)
889 // A;
890 // for (i = max(LB, BSV); i <= UB; ++i)
891 // B;
892 AEV = BinaryOperator::createSub(SD.SplitValue,
893 ConstantInt::get(Ty, 1, Sign),
894 "lsplit.sub", PHTerminator);
895 break;
896 case ICmpInst::ICMP_SLE:
897 case ICmpInst::ICMP_ULE:
898 //
899 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
900 //
901 // is transformed into
902 // AEV = SV;
903 // BSV = SV + 1;
904 // for (i = LB; i <= min(UB, AEV); ++i)
905 // A;
906 // for (i = max(LB, BSV); i <= UB; ++i)
907 // B;
908 BSV = BinaryOperator::createAdd(SD.SplitValue,
909 ConstantInt::get(Ty, 1, Sign),
910 "lsplit.add", PHTerminator);
911 break;
912 case ICmpInst::ICMP_SGT:
913 case ICmpInst::ICMP_UGT:
914 //
915 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
916 //
917 // is transformed into
918 // AEV = SV;
919 // BSV = SV + 1;
920 // for (i = LB; i <= min(AEV, UB); ++i)
921 // B;
922 // for (i = max(LB, BSV); i <= UB; ++i)
923 // A;
924 BSV = BinaryOperator::createAdd(SD.SplitValue,
925 ConstantInt::get(Ty, 1, Sign),
926 "lsplit.add", PHTerminator);
927 break;
928 case ICmpInst::ICMP_SGE:
929 case ICmpInst::ICMP_UGE:
930 // ** TODO **
931 //
932 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
933 //
934 // is transformed into
935 // AEV = SV - 1;
936 // BSV = SV;
937 // for (i = LB; i <= min(AEV, UB); ++i)
938 // B;
939 // for (i = max(LB, BSV); i <= UB; ++i)
940 // A;
941 AEV = BinaryOperator::createSub(SD.SplitValue,
942 ConstantInt::get(Ty, 1, Sign),
943 "lsplit.sub", PHTerminator);
944 break;
945 default:
946 assert (0 && "Unexpected split condition predicate");
947 break;
948 } // end switch (SP)
949 }
950 break;
951 }
952
953 // Calculate ALoop induction variable's new exiting value and
954 // BLoop induction variable's new starting value. Calculuate these
955 // values in original loop's preheader.
956 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
957 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000958 Value *C1 = new ICmpInst(Sign ?
959 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
960 AEV,
961 ExitCondition->getOperand(ExitValueNum),
962 "lsplit.ev", PHTerminator);
963 SD.A_ExitValue = new SelectInst(C1, AEV,
964 ExitCondition->getOperand(ExitValueNum),
965 "lsplit.ev", PHTerminator);
966
967 Value *C2 = new ICmpInst(Sign ?
968 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
969 BSV, StartValue, "lsplit.sv",
970 PHTerminator);
971 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
972 "lsplit.sv", PHTerminator);
973}
974
Devang Pateld662ace2007-08-22 18:27:01 +0000975/// splitLoop - Split current loop L in two loops using split information
976/// SD. Update dominator information. Maintain LCSSA form.
977bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
978
979 if (!safeSplitCondition(SD))
980 return false;
981
Devang Patela0ac7262007-08-22 19:33:29 +0000982 // After loop is cloned there are two loops.
983 //
984 // First loop, referred as ALoop, executes first part of loop's iteration
985 // space split. Second loop, referred as BLoop, executes remaining
986 // part of loop's iteration space.
987 //
988 // ALoop's exit edge enters BLoop's header through a forwarding block which
989 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +0000990 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +0000991
Devang Pateledea5b32007-08-25 00:56:38 +0000992 // Calculate ALoop induction variable's new exiting value and
993 // BLoop induction variable's new starting value.
994 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +0000995
Devang Patela0ac7262007-08-22 19:33:29 +0000996 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000997 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +0000998 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +0000999 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001000 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001001
Devang Patela0ac7262007-08-22 19:33:29 +00001002 //[*] ALoop's exiting edge BLoop's header.
1003 // ALoop's original exit block becomes BLoop's exit block.
1004 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1005 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1006 BranchInst *A_ExitInsn =
1007 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1008 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1009 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1010 if (L->contains(B_ExitBlock)) {
1011 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1012 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001013 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001014 A_ExitInsn->setSuccessor(1, B_Header);
1015
1016 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001017 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001018
Devang Patela0ac7262007-08-22 19:33:29 +00001019 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1020 // original loop's preheader. Add incoming PHINode values from
1021 // ALoop's exiting block. Update BLoop header's domiantor info.
1022
Devang Patel59e0c062007-08-14 01:30:57 +00001023 // Collect inverse map of Header PHINodes.
1024 DenseMap<Value *, Value *> InverseMap;
1025 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1026 BE = L->getHeader()->end(); BI != BE; ++BI) {
1027 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1028 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1029 InverseMap[PNClone] = PN;
1030 } else
1031 break;
1032 }
Devang Pateledea5b32007-08-25 00:56:38 +00001033
Devang Patela0ac7262007-08-22 19:33:29 +00001034 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001035 BI != BE; ++BI) {
1036 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001037 // Remove incoming value from original preheader.
1038 PN->removeIncomingValue(Preheader);
1039
1040 // Add incoming value from A_ExitingBlock.
1041 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001042 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001043 else {
1044 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001045 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1046 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001047 }
1048 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001049 break;
1050 }
Devang Patela0ac7262007-08-22 19:33:29 +00001051 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1052 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001053
Devang Patela0ac7262007-08-22 19:33:29 +00001054 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1055 // block. Remove incoming PHINode values from ALoop's exiting block.
1056 // Add new incoming values from BLoop's incoming exiting value.
1057 // Update BLoop exit block's dominator info..
1058 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1059 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001060 BI != BE; ++BI) {
1061 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001062 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1063 B_ExitingBlock);
1064 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001065 } else
1066 break;
1067 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001068
Devang Patela0ac7262007-08-22 19:33:29 +00001069 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1070 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001071
Devang Patela0ac7262007-08-22 19:33:29 +00001072 //[*] Split ALoop's exit edge. This creates a new block which
1073 // serves two purposes. First one is to hold PHINode defnitions
1074 // to ensure that ALoop's LCSSA form. Second use it to act
1075 // as a preheader for BLoop.
1076 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001077
Devang Patela0ac7262007-08-22 19:33:29 +00001078 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1079 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1080 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001081 BI != BE; ++BI) {
1082 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001083 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001084 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001085 newPHI->addIncoming(V1, A_ExitingBlock);
1086 A_ExitBlock->getInstList().push_front(newPHI);
1087 PN->removeIncomingValue(A_ExitBlock);
1088 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001089 } else
1090 break;
1091 }
1092
Devang Patela0ac7262007-08-22 19:33:29 +00001093 //[*] Eliminate split condition's inactive branch from ALoop.
1094 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1095 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001096 BasicBlock *A_InactiveBranch = NULL;
1097 BasicBlock *A_ActiveBranch = NULL;
1098 if (SD.UseTrueBranchFirst) {
1099 A_ActiveBranch = A_BR->getSuccessor(0);
1100 A_InactiveBranch = A_BR->getSuccessor(1);
1101 } else {
1102 A_ActiveBranch = A_BR->getSuccessor(1);
1103 A_InactiveBranch = A_BR->getSuccessor(0);
1104 }
Devang Patel4e585c72007-08-24 19:32:26 +00001105 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001106 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1107
1108 //[*] Eliminate split condition's inactive branch in from BLoop.
1109 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1110 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001111 BasicBlock *B_InactiveBranch = NULL;
1112 BasicBlock *B_ActiveBranch = NULL;
1113 if (SD.UseTrueBranchFirst) {
1114 B_ActiveBranch = B_BR->getSuccessor(1);
1115 B_InactiveBranch = B_BR->getSuccessor(0);
1116 } else {
1117 B_ActiveBranch = B_BR->getSuccessor(0);
1118 B_InactiveBranch = B_BR->getSuccessor(1);
1119 }
Devang Patel4e585c72007-08-24 19:32:26 +00001120 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001121 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1122
Devang Patelcd71bed2007-08-25 02:39:24 +00001123 BasicBlock *A_Header = L->getHeader();
1124 if (A_ExitingBlock == A_Header)
1125 return true;
1126
1127 //[*] Move exit condition into split condition block to avoid
1128 // executing dead loop iteration.
1129 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1130 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1131 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1132
1133 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1134 SD.SplitCondition, IndVar, IndVarIncrement, ALoop);
1135
1136 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1137 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1138
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001139 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001140}
Devang Patelcd71bed2007-08-25 02:39:24 +00001141
1142// moveExitCondition - Move exit condition EC into split condition block CondBB.
1143void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1144 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1145 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1146
1147 BasicBlock *ExitingBB = EC->getParent();
1148 Instruction *CurrentBR = CondBB->getTerminator();
1149
1150 // Move exit condition into split condition block.
1151 EC->moveBefore(CurrentBR);
1152 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1153
1154 // Move exiting block's branch into split condition block. Update its branch
1155 // destination.
1156 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1157 ExitingBR->moveBefore(CurrentBR);
1158 if (ExitingBR->getSuccessor(0) == ExitBB)
1159 ExitingBR->setSuccessor(1, ActiveBB);
1160 else
1161 ExitingBR->setSuccessor(0, ActiveBB);
1162
1163 // Remove split condition and current split condition branch.
1164 SC->eraseFromParent();
1165 CurrentBR->eraseFromParent();
1166
1167 // Connect exiting block to split condition block.
1168 new BranchInst(CondBB, ExitingBB);
1169
1170 // Update PHINodes
1171 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1172
1173 // Fix dominator info.
1174 // ExitBB is now dominated by CondBB
1175 DT->changeImmediateDominator(ExitBB, CondBB);
1176 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1177
1178 // Basicblocks dominated by ActiveBB may have ExitingBB or
1179 // a basic block outside the loop in their DF list. If so,
1180 // replace it with CondBB.
1181 DomTreeNode *Node = DT->getNode(ActiveBB);
1182 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1183 DI != DE; ++DI) {
1184 BasicBlock *BB = DI->getBlock();
1185 DominanceFrontier::iterator BBDF = DF->find(BB);
1186 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1187 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1188 while (DomSetI != DomSetE) {
1189 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1190 ++DomSetI;
1191 BasicBlock *DFBB = *CurrentItr;
1192 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1193 BBDF->second.erase(DFBB);
1194 BBDF->second.insert(CondBB);
1195 }
1196 }
1197 }
1198}
1199
1200/// updatePHINodes - CFG has been changed.
1201/// Before
1202/// - ExitBB's single predecessor was Latch
1203/// - Latch's second successor was Header
1204/// Now
1205/// - ExitBB's single predecessor was Header
1206/// - Latch's one and only successor was Header
1207///
1208/// Update ExitBB PHINodes' to reflect this change.
1209void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1210 BasicBlock *Header,
1211 PHINode *IV, Instruction *IVIncrement) {
1212
1213 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1214 BI != BE; ++BI) {
1215 PHINode *PN = dyn_cast<PHINode>(BI);
1216 if (!PN)
1217 break;
1218
1219 Value *V = PN->getIncomingValueForBlock(Latch);
1220 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1221 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1222 // (i.e. PN :)).
1223 // The second use is in Header and it is new incoming value for PN.
1224 PHINode *U1 = NULL;
1225 PHINode *U2 = NULL;
1226 Value *NewV = NULL;
1227 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1228 UI != E; ++UI) {
1229 if (!U1)
1230 U1 = cast<PHINode>(*UI);
1231 else if (!U2)
1232 U2 = cast<PHINode>(*UI);
1233 else
1234 assert ( 0 && "Unexpected third use of this PHINode");
1235 }
1236 assert (U1 && U2 && "Unable to find two uses");
1237
1238 if (U1->getParent() == Header)
1239 NewV = U1;
1240 else
1241 NewV = U2;
1242 PN->addIncoming(NewV, Header);
1243
1244 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1245 // If this instruction is IVIncrement then IV is new incoming value
1246 // from header otherwise this instruction must be incoming value from
1247 // header because loop is in LCSSA form.
1248 if (PHI == IVIncrement)
1249 PN->addIncoming(IV, Header);
1250 else
1251 PN->addIncoming(V, Header);
1252 } else
1253 // Otherwise this is an incoming value from header because loop is in
1254 // LCSSA form.
1255 PN->addIncoming(V, Header);
1256
1257 // Remove incoming value from Latch.
1258 PN->removeIncomingValue(Latch);
1259 }
1260}