blob: f4be5ddef9c749e22a54879b5b37a2ce5d7da397 [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 Patel5bc8a2c2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patelc8dadbf2007-08-08 21:02:17 +000069
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;
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000224 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
225 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000226 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000227 if (Changed) {
228 ++NumIndexSplit;
229 // If is loop is eliminated then nothing else to do here.
230 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000231 } else {
232 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
233 ++SI;
234 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000235 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000236 } else
237 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000238 }
239
Devang Patel7f526a82007-08-24 06:17:19 +0000240 if (SplitData.empty())
241 return false;
242
Devang Patel0aaeb172007-08-08 22:25:28 +0000243 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000244 // FIXME : Implement cost analysis.
245 unsigned MostProfitableSDIndex = 0;
246 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000247
Devang Patelbc5fe632007-08-07 00:25:56 +0000248 if (Changed)
249 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000250
Devang Patelbc5fe632007-08-07 00:25:56 +0000251 return Changed;
252}
253
Devang Patel2545f7b2007-08-09 01:39:01 +0000254/// Return true if V is a induction variable or induction variable's
255/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000256void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000257
258 Instruction *I = dyn_cast<Instruction>(V);
259 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000260 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000261
262 // Check if I is a phi node from loop header or not.
263 if (PHINode *PN = dyn_cast<PHINode>(V)) {
264 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000265 IndVar = PN;
266 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000267 }
268 }
269
270 // Check if I is a add instruction whose one operand is
271 // phi node from loop header and second operand is constant.
272 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000273 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000274
275 Value *Op0 = I->getOperand(0);
276 Value *Op1 = I->getOperand(1);
277
278 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
279 if (PN->getParent() == L->getHeader()
280 && isa<ConstantInt>(Op1)) {
281 IndVar = PN;
282 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000283 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000284 }
285 }
286
287 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
288 if (PN->getParent() == L->getHeader()
289 && isa<ConstantInt>(Op0)) {
290 IndVar = PN;
291 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000292 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000293 }
294 }
295
Devang Patel61571ca2007-08-10 00:33:50 +0000296 return;
297}
298
299// Find loop's exit condition and associated induction variable.
300void LoopIndexSplit::findLoopConditionals() {
301
Devang Patel9263fc32007-08-20 23:51:18 +0000302 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000303
304 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
305 I != E; ++I) {
306 BasicBlock *BB = *I;
307 if (!L->isLoopExit(BB))
308 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000309 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000310 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000311 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000312 }
313
Devang Patel9263fc32007-08-20 23:51:18 +0000314 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000315 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000316
317 // If exiting block is neither loop header nor loop latch then this loop is
318 // not suitable.
319 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
320 return;
321
Devang Patel61571ca2007-08-10 00:33:50 +0000322 // If exit block's terminator is conditional branch inst then we have found
323 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000324 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000325 if (!BR || BR->isUnconditional())
326 return;
327
328 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
329 if (!CI)
330 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000331
Devang Patel7ea9ad22007-09-10 23:34:06 +0000332 // FIXME
333 if (CI->getPredicate() == ICmpInst::ICMP_EQ
334 || CI->getPredicate() == ICmpInst::ICMP_NE)
335 return;
336
Devang Pateledea5b32007-08-25 00:56:38 +0000337 if (CI->getPredicate() == ICmpInst::ICMP_SGT
338 || CI->getPredicate() == ICmpInst::ICMP_UGT
339 || CI->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel7ea9ad22007-09-10 23:34:06 +0000340 || CI->getPredicate() == ICmpInst::ICMP_UGE) {
341
342 BasicBlock *FirstSuccessor = BR->getSuccessor(0);
343 // splitLoop() is expecting LT/LE as exit condition predicate.
344 // Swap operands here if possible to meet this requirement.
345 if (!L->contains(FirstSuccessor))
346 CI->swapOperands();
347 else
348 return;
349 }
Devang Pateledea5b32007-08-25 00:56:38 +0000350
Devang Patel61571ca2007-08-10 00:33:50 +0000351 ExitCondition = CI;
352
353 // Exit condition's one operand is loop invariant exit value and second
354 // operand is SCEVAddRecExpr based on induction variable.
355 Value *V0 = CI->getOperand(0);
356 Value *V1 = CI->getOperand(1);
357
358 SCEVHandle SH0 = SE->getSCEV(V0);
359 SCEVHandle SH1 = SE->getSCEV(V1);
360
361 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000362 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000363 findIndVar(V1, L);
364 }
365 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000366 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000367 findIndVar(V0, L);
368 }
369
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000370 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000371 ExitCondition = NULL;
372 else if (IndVar) {
373 BasicBlock *Preheader = L->getLoopPreheader();
374 StartValue = IndVar->getIncomingValueForBlock(Preheader);
375 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000376}
377
Devang Patelbc5fe632007-08-07 00:25:56 +0000378/// Find condition inside a loop that is suitable candidate for index split.
379void LoopIndexSplit::findSplitCondition() {
380
Devang Patelc8dadbf2007-08-08 21:02:17 +0000381 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000382 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000383 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
384 I != E; ++I) {
385 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000386
Devang Patel2545f7b2007-08-09 01:39:01 +0000387 // If this basic block does not terminate in a conditional branch
388 // then terminator is not a suitable split condition.
389 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
390 if (!BR)
391 continue;
392
393 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000394 continue;
395
Devang Patel2545f7b2007-08-09 01:39:01 +0000396 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000397 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000398 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000399
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000400 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000401 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000402
Devang Patel7f526a82007-08-24 06:17:19 +0000403 // If split condition predicate is GT or GE then first execute
404 // false branch of split condition.
405 if (CI->getPredicate() != ICmpInst::ICMP_ULT
406 && CI->getPredicate() != ICmpInst::ICMP_SLT
407 && CI->getPredicate() != ICmpInst::ICMP_ULE
408 && CI->getPredicate() != ICmpInst::ICMP_SLE)
409 SD.UseTrueBranchFirst = false;
410
Devang Patel2545f7b2007-08-09 01:39:01 +0000411 // If one operand is loop invariant and second operand is SCEVAddRecExpr
412 // based on induction variable then CI is a candidate split condition.
413 Value *V0 = CI->getOperand(0);
414 Value *V1 = CI->getOperand(1);
415
416 SCEVHandle SH0 = SE->getSCEV(V0);
417 SCEVHandle SH1 = SE->getSCEV(V1);
418
419 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
420 SD.SplitValue = V0;
421 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000422 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
423 if (PN == IndVar)
424 SplitData.push_back(SD);
425 }
426 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
427 if (IndVarIncrement && IndVarIncrement == Insn)
428 SplitData.push_back(SD);
429 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000430 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000431 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
432 SD.SplitValue = V1;
433 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000434 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
435 if (PN == IndVar)
436 SplitData.push_back(SD);
437 }
438 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
439 if (IndVarIncrement && IndVarIncrement == Insn)
440 SplitData.push_back(SD);
441 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000442 }
443 }
444}
445
446/// processOneIterationLoop - Current loop L contains compare instruction
447/// that compares induction variable, IndVar, against loop invariant. If
448/// entire (i.e. meaningful) loop body is dominated by this compare
449/// instruction then loop body is executed only once. In such case eliminate
450/// loop structure surrounding this loop body. For example,
451/// for (int i = start; i < end; ++i) {
452/// if ( i == somevalue) {
453/// loop_body
454/// }
455/// }
456/// can be transformed into
457/// if (somevalue >= start && somevalue < end) {
458/// i = somevalue;
459/// loop_body
460/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000461bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000462
463 BasicBlock *Header = L->getHeader();
464
465 // First of all, check if SplitCondition dominates entire loop body
466 // or not.
467
468 // If SplitCondition is not in loop header then this loop is not suitable
469 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000470 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000471 return false;
472
Devang Patelbc5fe632007-08-07 00:25:56 +0000473 // If loop header includes loop variant instruction operands then
474 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000475 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000476 return false;
477
Devang Patel9263fc32007-08-20 23:51:18 +0000478 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000479 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000480 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000481 return false;
482
Devang Patel2bcb5012007-08-08 01:51:27 +0000483 // Update CFG.
484
Devang Patelc166b952007-08-20 20:49:01 +0000485 // Replace index variable with split value in loop body. Loop body is executed
486 // only when index variable is equal to split value.
487 IndVar->replaceAllUsesWith(SD.SplitValue);
488
489 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000490 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000491 BasicBlock *LatchSucc = NULL;
492 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
493 if (!BR)
494 return false;
495 Header->removePredecessor(Latch);
496 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
497 SI != E; ++SI) {
498 if (Header != *SI)
499 LatchSucc = *SI;
500 }
501 BR->setUnconditionalDest(LatchSucc);
502
Devang Patelbc5fe632007-08-07 00:25:56 +0000503 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000504 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000505
Devang Patelbc5fe632007-08-07 00:25:56 +0000506 // Replace split condition in header.
507 // Transform
508 // SplitCondition : icmp eq i32 IndVar, SplitValue
509 // into
510 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000511 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000512 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000513 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000514 Instruction *C1 = new ICmpInst(SignedPredicate ?
515 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000516 SD.SplitValue, StartValue, "lisplit",
517 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000518 Instruction *C2 = new ICmpInst(SignedPredicate ?
519 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000520 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000521 Terminator);
522 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
523 Terminator);
524 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
525 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000526
Devang Patelbc5fe632007-08-07 00:25:56 +0000527 // Now, clear latch block. Remove instructions that are responsible
528 // to increment induction variable.
529 Instruction *LTerminator = Latch->getTerminator();
530 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
531 LB != LE; ) {
532 Instruction *I = LB;
533 ++LB;
534 if (isa<PHINode>(I) || I == LTerminator)
535 continue;
536
Devang Patel59e0c062007-08-14 01:30:57 +0000537 if (I == IndVarIncrement)
538 I->replaceAllUsesWith(ExitValue);
539 else
540 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000541 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000542 }
543
Devang Patel901f67e2007-08-10 18:07:13 +0000544 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000545
546 // Update Dominator Info.
547 // Only CFG change done is to remove Latch to Header edge. This
548 // does not change dominator tree because Latch did not dominate
549 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000550 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000551 DominanceFrontier::iterator HeaderDF = DF->find(Header);
552 if (HeaderDF != DF->end())
553 DF->removeFromFrontier(HeaderDF, Header);
554
555 DominanceFrontier::iterator LatchDF = DF->find(Latch);
556 if (LatchDF != DF->end())
557 DF->removeFromFrontier(LatchDF, Header);
558 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000559 return true;
560}
561
562// If loop header includes loop variant instruction operands then
563// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000564bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000565
566 Instruction *Terminator = Header->getTerminator();
567 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
568 BI != BE; ++BI) {
569 Instruction *I = BI;
570
Devang Patel59e0c062007-08-14 01:30:57 +0000571 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000572 if (isa<PHINode>(I))
573 continue;
574
575 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000576 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000577 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000578
Devang Patel2545f7b2007-08-09 01:39:01 +0000579 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000580 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000581 continue;
582
583 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000584 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000585 continue;
586
Devang Patelbc5fe632007-08-07 00:25:56 +0000587 // Terminator is also harmless.
588 if (I == Terminator)
589 continue;
590
591 // Otherwise we have a instruction that may not be safe.
592 return false;
593 }
594
595 return true;
596}
597
Devang Patel9263fc32007-08-20 23:51:18 +0000598// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000599// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000600bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
601 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000602
Devang Patel9263fc32007-08-20 23:51:18 +0000603 for (BasicBlock::iterator BI = ExitingBlock->begin(),
604 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000605 Instruction *I = BI;
606
Devang Patel59e0c062007-08-14 01:30:57 +0000607 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000608 if (isa<PHINode>(I))
609 continue;
610
Devang Patel2545f7b2007-08-09 01:39:01 +0000611 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000612 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000613 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000614
Devang Patel2545f7b2007-08-09 01:39:01 +0000615 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000616 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000617
618 Value *Op0 = I->getOperand(0);
619 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000620 PHINode *PN = NULL;
621 ConstantInt *CI = NULL;
622
623 if ((PN = dyn_cast<PHINode>(Op0))) {
624 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000625 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000626 } else
627 if ((PN = dyn_cast<PHINode>(Op1))) {
628 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000629 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000630 }
631
Devang Patel61571ca2007-08-10 00:33:50 +0000632 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000633 continue;
634 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000635
Devang Patelbc5fe632007-08-07 00:25:56 +0000636 // I is an Exit condition if next instruction is block terminator.
637 // Exit condition is OK if it compares loop invariant exit value,
638 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000639 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000640 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000641 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000642 }
643
Devang Patel9263fc32007-08-20 23:51:18 +0000644 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000645 continue;
646
Devang Patelbc5fe632007-08-07 00:25:56 +0000647 // Otherwise we have instruction that may not be safe.
648 return false;
649 }
650
Devang Patel9263fc32007-08-20 23:51:18 +0000651 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000652 return true;
653}
654
Devang Patel60a94c72007-08-14 18:35:57 +0000655/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
656/// This routine is used to remove split condition's dead branch, dominated by
657/// DeadBB. LiveBB dominates split conidition's other branch.
658void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
659 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000660
Devang Patelf4277122007-08-15 03:31:47 +0000661 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000662 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000663 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
664 if (DeadBBDF != DF->end()) {
665 SmallVector<BasicBlock *, 8> PredBlocks;
666
667 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
668 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
669 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
670 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000671 FrontierBBs.push_back(FrontierBB);
672
Devang Patelf4277122007-08-15 03:31:47 +0000673 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
674 PredBlocks.clear();
675 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
676 PI != PE; ++PI) {
677 BasicBlock *P = *PI;
678 if (P == DeadBB || DT->dominates(DeadBB, P))
679 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000680 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000681
Devang Patelf4277122007-08-15 03:31:47 +0000682 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
683 FBI != FBE; ++FBI) {
684 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
685 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
686 PE = PredBlocks.end(); PI != PE; ++PI) {
687 BasicBlock *P = *PI;
688 PN->removeIncomingValue(P);
689 }
690 }
691 else
692 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000693 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000694 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000695 }
Devang Patelf4277122007-08-15 03:31:47 +0000696
697 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
698 SmallVector<BasicBlock *, 32> WorkList;
699 DomTreeNode *DN = DT->getNode(DeadBB);
700 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
701 E = df_end(DN); DI != E; ++DI) {
702 BasicBlock *BB = DI->getBlock();
703 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000704 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000705 }
706
707 while (!WorkList.empty()) {
708 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
709 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
710 BBI != BBE; ++BBI) {
711 Instruction *I = BBI;
712 I->replaceAllUsesWith(UndefValue::get(I->getType()));
713 I->eraseFromParent();
714 }
715 LPM->deleteSimpleAnalysisValue(BB, LP);
716 DT->eraseNode(BB);
717 DF->removeBlock(BB);
718 LI->removeBlock(BB);
719 BB->eraseFromParent();
720 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000721
722 // Update Frontier BBs' dominator info.
723 while (!FrontierBBs.empty()) {
724 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
725 BasicBlock *NewDominator = FBB->getSinglePredecessor();
726 if (!NewDominator) {
727 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
728 NewDominator = *PI;
729 ++PI;
730 if (NewDominator != LiveBB) {
731 for(; PI != PE; ++PI) {
732 BasicBlock *P = *PI;
733 if (P == LiveBB) {
734 NewDominator = LiveBB;
735 break;
736 }
737 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
738 }
739 }
740 }
741 assert (NewDominator && "Unable to fix dominator info.");
742 DT->changeImmediateDominator(FBB, NewDominator);
743 DF->changeImmediateDominator(FBB, NewDominator, DT);
744 }
745
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000746}
747
Devang Pateld662ace2007-08-22 18:27:01 +0000748/// safeSplitCondition - Return true if it is possible to
749/// split loop using given split condition.
750bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000751
Devang Pateld662ace2007-08-22 18:27:01 +0000752 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000753
Devang Pateld662ace2007-08-22 18:27:01 +0000754 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000755 // In triangle loop, split condition is in header and one of the
756 // the split destination is loop latch. If split condition is EQ
757 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000758 BasicBlock *Latch = L->getLoopLatch();
759 BranchInst *SplitTerminator =
760 cast<BranchInst>(SplitCondBlock->getTerminator());
761 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
762 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
763 if (L->getHeader() == SplitCondBlock
764 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000765 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000766
Devang Patelac7c7c22007-08-27 21:34:31 +0000767 // If split condition branches heads do not have single predecessor,
768 // SplitCondBlock, then is not possible to remove inactive branch.
769 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000770 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000771
Devang Patel4e2075d2007-08-24 05:36:56 +0000772 // Finally this split condition is safe only if merge point for
773 // split condition branch is loop latch. This check along with previous
774 // check, to ensure that exit condition is in either loop latch or header,
775 // filters all loops with non-empty loop body between merge point
776 // and exit condition.
777 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
778 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
779 if (Succ0DF->second.count(Latch))
780 return true;
781
782 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
783 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
784 if (Succ1DF->second.count(Latch))
785 return true;
786
787 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000788}
789
Devang Pateledea5b32007-08-25 00:56:38 +0000790/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
791/// based on split value.
792void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
793
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000794 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
795 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +0000796 const Type *Ty = SD.SplitValue->getType();
797 bool Sign = ExitCondition->isSignedPredicate();
798 BasicBlock *Preheader = L->getLoopPreheader();
799 Instruction *PHTerminator = Preheader->getTerminator();
800
801 // Initially use split value as upper loop bound for first loop and lower loop
802 // bound for second loop.
803 Value *AEV = SD.SplitValue;
804 Value *BSV = SD.SplitValue;
805
806 switch (ExitCondition->getPredicate()) {
807 case ICmpInst::ICMP_SGT:
808 case ICmpInst::ICMP_UGT:
809 case ICmpInst::ICMP_SGE:
810 case ICmpInst::ICMP_UGE:
811 default:
812 assert (0 && "Unexpected exit condition predicate");
813
814 case ICmpInst::ICMP_SLT:
815 case ICmpInst::ICMP_ULT:
816 {
817 switch (SP) {
818 case ICmpInst::ICMP_SLT:
819 case ICmpInst::ICMP_ULT:
820 //
821 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
822 //
823 // is transformed into
824 // AEV = BSV = SV
825 // for (i = LB; i < min(UB, AEV); ++i)
826 // A;
827 // for (i = max(LB, BSV); i < UB; ++i);
828 // B;
829 break;
830 case ICmpInst::ICMP_SLE:
831 case ICmpInst::ICMP_ULE:
832 {
833 //
834 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
835 //
836 // is transformed into
837 //
838 // AEV = SV + 1
839 // BSV = SV + 1
840 // for (i = LB; i < min(UB, AEV); ++i)
841 // A;
842 // for (i = max(LB, BSV); i < UB; ++i)
843 // B;
844 BSV = BinaryOperator::createAdd(SD.SplitValue,
845 ConstantInt::get(Ty, 1, Sign),
846 "lsplit.add", PHTerminator);
847 AEV = BSV;
848 }
849 break;
850 case ICmpInst::ICMP_SGE:
851 case ICmpInst::ICMP_UGE:
852 //
853 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
854 //
855 // is transformed into
856 // AEV = BSV = SV
857 // for (i = LB; i < min(UB, AEV); ++i)
858 // B;
859 // for (i = max(BSV, LB); i < UB; ++i)
860 // A;
861 break;
862 case ICmpInst::ICMP_SGT:
863 case ICmpInst::ICMP_UGT:
864 {
865 //
866 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
867 //
868 // is transformed into
869 //
870 // BSV = AEV = SV + 1
871 // for (i = LB; i < min(UB, AEV); ++i)
872 // B;
873 // for (i = max(LB, BSV); i < UB; ++i)
874 // A;
875 BSV = BinaryOperator::createAdd(SD.SplitValue,
876 ConstantInt::get(Ty, 1, Sign),
877 "lsplit.add", PHTerminator);
878 AEV = BSV;
879 }
880 break;
881 default:
882 assert (0 && "Unexpected split condition predicate");
883 break;
884 } // end switch (SP)
885 }
886 break;
887 case ICmpInst::ICMP_SLE:
888 case ICmpInst::ICMP_ULE:
889 {
890 switch (SP) {
891 case ICmpInst::ICMP_SLT:
892 case ICmpInst::ICMP_ULT:
893 //
894 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
895 //
896 // is transformed into
897 // AEV = SV - 1;
898 // BSV = SV;
899 // for (i = LB; i <= min(UB, AEV); ++i)
900 // A;
901 // for (i = max(LB, BSV); i <= UB; ++i)
902 // B;
903 AEV = BinaryOperator::createSub(SD.SplitValue,
904 ConstantInt::get(Ty, 1, Sign),
905 "lsplit.sub", PHTerminator);
906 break;
907 case ICmpInst::ICMP_SLE:
908 case ICmpInst::ICMP_ULE:
909 //
910 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
911 //
912 // is transformed into
913 // AEV = SV;
914 // BSV = SV + 1;
915 // for (i = LB; i <= min(UB, AEV); ++i)
916 // A;
917 // for (i = max(LB, BSV); i <= UB; ++i)
918 // B;
919 BSV = BinaryOperator::createAdd(SD.SplitValue,
920 ConstantInt::get(Ty, 1, Sign),
921 "lsplit.add", PHTerminator);
922 break;
923 case ICmpInst::ICMP_SGT:
924 case ICmpInst::ICMP_UGT:
925 //
926 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
927 //
928 // is transformed into
929 // AEV = SV;
930 // BSV = SV + 1;
931 // for (i = LB; i <= min(AEV, UB); ++i)
932 // B;
933 // for (i = max(LB, BSV); i <= UB; ++i)
934 // A;
935 BSV = BinaryOperator::createAdd(SD.SplitValue,
936 ConstantInt::get(Ty, 1, Sign),
937 "lsplit.add", PHTerminator);
938 break;
939 case ICmpInst::ICMP_SGE:
940 case ICmpInst::ICMP_UGE:
941 // ** TODO **
942 //
943 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
944 //
945 // is transformed into
946 // AEV = SV - 1;
947 // BSV = SV;
948 // for (i = LB; i <= min(AEV, UB); ++i)
949 // B;
950 // for (i = max(LB, BSV); i <= UB; ++i)
951 // A;
952 AEV = BinaryOperator::createSub(SD.SplitValue,
953 ConstantInt::get(Ty, 1, Sign),
954 "lsplit.sub", PHTerminator);
955 break;
956 default:
957 assert (0 && "Unexpected split condition predicate");
958 break;
959 } // end switch (SP)
960 }
961 break;
962 }
963
964 // Calculate ALoop induction variable's new exiting value and
965 // BLoop induction variable's new starting value. Calculuate these
966 // values in original loop's preheader.
967 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
968 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000969 Value *C1 = new ICmpInst(Sign ?
970 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
971 AEV,
972 ExitCondition->getOperand(ExitValueNum),
973 "lsplit.ev", PHTerminator);
974 SD.A_ExitValue = new SelectInst(C1, AEV,
975 ExitCondition->getOperand(ExitValueNum),
976 "lsplit.ev", PHTerminator);
977
978 Value *C2 = new ICmpInst(Sign ?
979 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
980 BSV, StartValue, "lsplit.sv",
981 PHTerminator);
982 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
983 "lsplit.sv", PHTerminator);
984}
985
Devang Pateld662ace2007-08-22 18:27:01 +0000986/// splitLoop - Split current loop L in two loops using split information
987/// SD. Update dominator information. Maintain LCSSA form.
988bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
989
990 if (!safeSplitCondition(SD))
991 return false;
992
Devang Patela0ac7262007-08-22 19:33:29 +0000993 // After loop is cloned there are two loops.
994 //
995 // First loop, referred as ALoop, executes first part of loop's iteration
996 // space split. Second loop, referred as BLoop, executes remaining
997 // part of loop's iteration space.
998 //
999 // ALoop's exit edge enters BLoop's header through a forwarding block which
1000 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001001 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001002
Devang Pateledea5b32007-08-25 00:56:38 +00001003 // Calculate ALoop induction variable's new exiting value and
1004 // BLoop induction variable's new starting value.
1005 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001006
Devang Patela0ac7262007-08-22 19:33:29 +00001007 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001008 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001009 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001010 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001011 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001012
Devang Patela0ac7262007-08-22 19:33:29 +00001013 //[*] ALoop's exiting edge BLoop's header.
1014 // ALoop's original exit block becomes BLoop's exit block.
1015 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1016 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1017 BranchInst *A_ExitInsn =
1018 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1019 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1020 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1021 if (L->contains(B_ExitBlock)) {
1022 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1023 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001024 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001025 A_ExitInsn->setSuccessor(1, B_Header);
1026
1027 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001028 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001029
Devang Patela0ac7262007-08-22 19:33:29 +00001030 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1031 // original loop's preheader. Add incoming PHINode values from
1032 // ALoop's exiting block. Update BLoop header's domiantor info.
1033
Devang Patel59e0c062007-08-14 01:30:57 +00001034 // Collect inverse map of Header PHINodes.
1035 DenseMap<Value *, Value *> InverseMap;
1036 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1037 BE = L->getHeader()->end(); BI != BE; ++BI) {
1038 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1039 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1040 InverseMap[PNClone] = PN;
1041 } else
1042 break;
1043 }
Devang Pateledea5b32007-08-25 00:56:38 +00001044
Devang Patela0ac7262007-08-22 19:33:29 +00001045 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001046 BI != BE; ++BI) {
1047 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001048 // Remove incoming value from original preheader.
1049 PN->removeIncomingValue(Preheader);
1050
1051 // Add incoming value from A_ExitingBlock.
1052 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001053 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001054 else {
1055 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001056 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1057 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001058 }
1059 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001060 break;
1061 }
Devang Patela0ac7262007-08-22 19:33:29 +00001062 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1063 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001064
Devang Patela0ac7262007-08-22 19:33:29 +00001065 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1066 // block. Remove incoming PHINode values from ALoop's exiting block.
1067 // Add new incoming values from BLoop's incoming exiting value.
1068 // Update BLoop exit block's dominator info..
1069 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1070 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001071 BI != BE; ++BI) {
1072 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001073 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1074 B_ExitingBlock);
1075 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001076 } else
1077 break;
1078 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001079
Devang Patela0ac7262007-08-22 19:33:29 +00001080 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1081 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001082
Devang Patela0ac7262007-08-22 19:33:29 +00001083 //[*] Split ALoop's exit edge. This creates a new block which
1084 // serves two purposes. First one is to hold PHINode defnitions
1085 // to ensure that ALoop's LCSSA form. Second use it to act
1086 // as a preheader for BLoop.
1087 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001088
Devang Patela0ac7262007-08-22 19:33:29 +00001089 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1090 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1091 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001092 BI != BE; ++BI) {
1093 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001094 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001095 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001096 newPHI->addIncoming(V1, A_ExitingBlock);
1097 A_ExitBlock->getInstList().push_front(newPHI);
1098 PN->removeIncomingValue(A_ExitBlock);
1099 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001100 } else
1101 break;
1102 }
1103
Devang Patela0ac7262007-08-22 19:33:29 +00001104 //[*] Eliminate split condition's inactive branch from ALoop.
1105 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1106 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001107 BasicBlock *A_InactiveBranch = NULL;
1108 BasicBlock *A_ActiveBranch = NULL;
1109 if (SD.UseTrueBranchFirst) {
1110 A_ActiveBranch = A_BR->getSuccessor(0);
1111 A_InactiveBranch = A_BR->getSuccessor(1);
1112 } else {
1113 A_ActiveBranch = A_BR->getSuccessor(1);
1114 A_InactiveBranch = A_BR->getSuccessor(0);
1115 }
Devang Patel4e585c72007-08-24 19:32:26 +00001116 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001117 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1118
1119 //[*] Eliminate split condition's inactive branch in from BLoop.
1120 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1121 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001122 BasicBlock *B_InactiveBranch = NULL;
1123 BasicBlock *B_ActiveBranch = NULL;
1124 if (SD.UseTrueBranchFirst) {
1125 B_ActiveBranch = B_BR->getSuccessor(1);
1126 B_InactiveBranch = B_BR->getSuccessor(0);
1127 } else {
1128 B_ActiveBranch = B_BR->getSuccessor(0);
1129 B_InactiveBranch = B_BR->getSuccessor(1);
1130 }
Devang Patel4e585c72007-08-24 19:32:26 +00001131 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001132 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1133
Devang Patelcd71bed2007-08-25 02:39:24 +00001134 BasicBlock *A_Header = L->getHeader();
1135 if (A_ExitingBlock == A_Header)
1136 return true;
1137
1138 //[*] Move exit condition into split condition block to avoid
1139 // executing dead loop iteration.
1140 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1141 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1142 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1143
1144 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001145 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1146 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001147
1148 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1149 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1150
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001151 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001152}
Devang Patelcd71bed2007-08-25 02:39:24 +00001153
1154// moveExitCondition - Move exit condition EC into split condition block CondBB.
1155void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1156 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1157 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1158
1159 BasicBlock *ExitingBB = EC->getParent();
1160 Instruction *CurrentBR = CondBB->getTerminator();
1161
1162 // Move exit condition into split condition block.
1163 EC->moveBefore(CurrentBR);
1164 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1165
1166 // Move exiting block's branch into split condition block. Update its branch
1167 // destination.
1168 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1169 ExitingBR->moveBefore(CurrentBR);
1170 if (ExitingBR->getSuccessor(0) == ExitBB)
1171 ExitingBR->setSuccessor(1, ActiveBB);
1172 else
1173 ExitingBR->setSuccessor(0, ActiveBB);
1174
1175 // Remove split condition and current split condition branch.
1176 SC->eraseFromParent();
1177 CurrentBR->eraseFromParent();
1178
1179 // Connect exiting block to split condition block.
1180 new BranchInst(CondBB, ExitingBB);
1181
1182 // Update PHINodes
1183 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1184
1185 // Fix dominator info.
1186 // ExitBB is now dominated by CondBB
1187 DT->changeImmediateDominator(ExitBB, CondBB);
1188 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1189
1190 // Basicblocks dominated by ActiveBB may have ExitingBB or
1191 // a basic block outside the loop in their DF list. If so,
1192 // replace it with CondBB.
1193 DomTreeNode *Node = DT->getNode(ActiveBB);
1194 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1195 DI != DE; ++DI) {
1196 BasicBlock *BB = DI->getBlock();
1197 DominanceFrontier::iterator BBDF = DF->find(BB);
1198 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1199 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1200 while (DomSetI != DomSetE) {
1201 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1202 ++DomSetI;
1203 BasicBlock *DFBB = *CurrentItr;
1204 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1205 BBDF->second.erase(DFBB);
1206 BBDF->second.insert(CondBB);
1207 }
1208 }
1209 }
1210}
1211
1212/// updatePHINodes - CFG has been changed.
1213/// Before
1214/// - ExitBB's single predecessor was Latch
1215/// - Latch's second successor was Header
1216/// Now
1217/// - ExitBB's single predecessor was Header
1218/// - Latch's one and only successor was Header
1219///
1220/// Update ExitBB PHINodes' to reflect this change.
1221void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1222 BasicBlock *Header,
1223 PHINode *IV, Instruction *IVIncrement) {
1224
1225 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1226 BI != BE; ++BI) {
1227 PHINode *PN = dyn_cast<PHINode>(BI);
1228 if (!PN)
1229 break;
1230
1231 Value *V = PN->getIncomingValueForBlock(Latch);
1232 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1233 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1234 // (i.e. PN :)).
1235 // The second use is in Header and it is new incoming value for PN.
1236 PHINode *U1 = NULL;
1237 PHINode *U2 = NULL;
1238 Value *NewV = NULL;
1239 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1240 UI != E; ++UI) {
1241 if (!U1)
1242 U1 = cast<PHINode>(*UI);
1243 else if (!U2)
1244 U2 = cast<PHINode>(*UI);
1245 else
1246 assert ( 0 && "Unexpected third use of this PHINode");
1247 }
1248 assert (U1 && U2 && "Unable to find two uses");
1249
1250 if (U1->getParent() == Header)
1251 NewV = U1;
1252 else
1253 NewV = U2;
1254 PN->addIncoming(NewV, Header);
1255
1256 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1257 // If this instruction is IVIncrement then IV is new incoming value
1258 // from header otherwise this instruction must be incoming value from
1259 // header because loop is in LCSSA form.
1260 if (PHI == IVIncrement)
1261 PN->addIncoming(IV, Header);
1262 else
1263 PN->addIncoming(V, Header);
1264 } else
1265 // Otherwise this is an incoming value from header because loop is in
1266 // LCSSA form.
1267 PN->addIncoming(V, Header);
1268
1269 // Remove incoming value from Latch.
1270 PN->removeIncomingValue(Latch);
1271 }
1272}