blob: b40dd04c82dd240d42e9d084f386a9827684c565 [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 Patel12564292007-09-11 00:42:56 +000092
93 // safeIcmpInst - CI is considered safe instruction if one of the operand
94 // is SCEVAddRecExpr based on induction variable and other operand is
95 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96 // and return true;
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
Devang Patelbc5fe632007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patel61571ca2007-08-10 00:33:50 +0000102 /// Find loop's exit condition.
103 void findLoopConditionals();
104
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
107
Devang Patelbc5fe632007-08-07 00:25:56 +0000108 /// processOneIterationLoop - Current loop L contains compare instruction
109 /// that compares induction variable, IndVar, agains loop invariant. If
110 /// entire (i.e. meaningful) loop body is dominated by this compare
111 /// instruction then loop body is executed only for one iteration. In
112 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000114
Devang Patel0aaeb172007-08-08 22:25:28 +0000115 /// If loop header includes loop variant instruction operands then
116 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000117 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000118
Devang Patel9263fc32007-08-20 23:51:18 +0000119 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +0000120 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000121 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000122
Devang Patel60a94c72007-08-14 18:35:57 +0000123 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
124 /// This routine is used to remove split condition's dead branch, dominated by
125 /// DeadBB. LiveBB dominates split conidition's other branch.
126 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000127
Devang Pateld662ace2007-08-22 18:27:01 +0000128 /// safeSplitCondition - Return true if it is possible to
129 /// split loop using given split condition.
130 bool safeSplitCondition(SplitInfo &SD);
131
Devang Pateledea5b32007-08-25 00:56:38 +0000132 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
133 /// based on split value.
134 void calculateLoopBounds(SplitInfo &SD);
135
Devang Patelcd71bed2007-08-25 02:39:24 +0000136 /// updatePHINodes - CFG has been changed.
137 /// Before
138 /// - ExitBB's single predecessor was Latch
139 /// - Latch's second successor was Header
140 /// Now
141 /// - ExitBB's single predecessor was Header
142 /// - Latch's one and only successor was Header
143 ///
144 /// Update ExitBB PHINodes' to reflect this change.
145 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
146 BasicBlock *Header,
147 PHINode *IV, Instruction *IVIncrement);
148
149 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
150 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
151 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
152 PHINode *IV, Instruction *IVAdd, Loop *LP);
153
Devang Pateld662ace2007-08-22 18:27:01 +0000154 /// splitLoop - Split current loop L in two loops using split information
155 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000156 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000157
Devang Patel61571ca2007-08-10 00:33:50 +0000158 void initialize() {
159 IndVar = NULL;
160 IndVarIncrement = NULL;
161 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000162 StartValue = NULL;
163 ExitValueNum = 0;
164 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000165 }
166
Devang Patelbc5fe632007-08-07 00:25:56 +0000167 private:
168
169 // Current Loop.
170 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000171 LPPassManager *LPM;
172 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000173 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000174 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000175 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000176 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000177
178 // Induction variable whose range is being split by this transformation.
179 PHINode *IndVar;
180 Instruction *IndVarIncrement;
181
182 // Loop exit condition.
183 ICmpInst *ExitCondition;
184
185 // Induction variable's initial value.
186 Value *StartValue;
187
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000188 // Induction variable's final loop exit value operand number in exit condition..
189 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000190 };
191
192 char LoopIndexSplit::ID = 0;
193 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
194}
195
196LoopPass *llvm::createLoopIndexSplitPass() {
197 return new LoopIndexSplit();
198}
199
200// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000201bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000202 bool Changed = false;
203 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000204 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000205
Devang Patel81fcdfb2007-08-15 02:14:55 +0000206 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000207 if (!L->getSubLoops().empty())
208 return false;
209
Devang Patelbc5fe632007-08-07 00:25:56 +0000210 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000211 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000212 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000213 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000214
Devang Patel61571ca2007-08-10 00:33:50 +0000215 initialize();
216
217 findLoopConditionals();
218
219 if (!ExitCondition)
220 return false;
221
Devang Patelbc5fe632007-08-07 00:25:56 +0000222 findSplitCondition();
223
Devang Patelc8dadbf2007-08-08 21:02:17 +0000224 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000225 return false;
226
Devang Patelc8dadbf2007-08-08 21:02:17 +0000227 // First see if it is possible to eliminate loop itself or not.
228 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000229 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000230 SplitInfo &SD = *SI;
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000231 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
232 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000233 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000234 if (Changed) {
235 ++NumIndexSplit;
236 // If is loop is eliminated then nothing else to do here.
237 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000238 } else {
239 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
240 ++SI;
241 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000242 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000243 } else
244 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000245 }
246
Devang Patel7f526a82007-08-24 06:17:19 +0000247 if (SplitData.empty())
248 return false;
249
Devang Patel0aaeb172007-08-08 22:25:28 +0000250 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000251 // FIXME : Implement cost analysis.
252 unsigned MostProfitableSDIndex = 0;
253 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000254
Devang Patelbc5fe632007-08-07 00:25:56 +0000255 if (Changed)
256 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000257
Devang Patelbc5fe632007-08-07 00:25:56 +0000258 return Changed;
259}
260
Devang Patel2545f7b2007-08-09 01:39:01 +0000261/// Return true if V is a induction variable or induction variable's
262/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000263void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000264
265 Instruction *I = dyn_cast<Instruction>(V);
266 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000267 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000268
269 // Check if I is a phi node from loop header or not.
270 if (PHINode *PN = dyn_cast<PHINode>(V)) {
271 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000272 IndVar = PN;
273 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000274 }
275 }
276
277 // Check if I is a add instruction whose one operand is
278 // phi node from loop header and second operand is constant.
279 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000280 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000281
282 Value *Op0 = I->getOperand(0);
283 Value *Op1 = I->getOperand(1);
284
285 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
286 if (PN->getParent() == L->getHeader()
287 && isa<ConstantInt>(Op1)) {
288 IndVar = PN;
289 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000290 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000291 }
292 }
293
294 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
295 if (PN->getParent() == L->getHeader()
296 && isa<ConstantInt>(Op0)) {
297 IndVar = PN;
298 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000299 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000300 }
301 }
302
Devang Patel61571ca2007-08-10 00:33:50 +0000303 return;
304}
305
306// Find loop's exit condition and associated induction variable.
307void LoopIndexSplit::findLoopConditionals() {
308
Devang Patel9263fc32007-08-20 23:51:18 +0000309 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000310
311 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
312 I != E; ++I) {
313 BasicBlock *BB = *I;
314 if (!L->isLoopExit(BB))
315 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000316 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000317 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000318 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000319 }
320
Devang Patel9263fc32007-08-20 23:51:18 +0000321 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000322 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000323
324 // If exiting block is neither loop header nor loop latch then this loop is
325 // not suitable.
326 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
327 return;
328
Devang Patel61571ca2007-08-10 00:33:50 +0000329 // If exit block's terminator is conditional branch inst then we have found
330 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000331 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000332 if (!BR || BR->isUnconditional())
333 return;
334
335 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
336 if (!CI)
337 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000338
Bill Wendlingd7bce7b2007-09-14 01:13:55 +0000339 // FIXME
Devang Pateledea5b32007-08-25 00:56:38 +0000340 if (CI->getPredicate() == ICmpInst::ICMP_SGT
341 || CI->getPredicate() == ICmpInst::ICMP_UGT
342 || CI->getPredicate() == ICmpInst::ICMP_SGE
Bill Wendlingd7bce7b2007-09-14 01:13:55 +0000343 || CI->getPredicate() == ICmpInst::ICMP_UGE
344 || CI->getPredicate() == ICmpInst::ICMP_EQ
345 || CI->getPredicate() == ICmpInst::ICMP_NE)
346 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000347
Devang Patel61571ca2007-08-10 00:33:50 +0000348 ExitCondition = CI;
349
350 // Exit condition's one operand is loop invariant exit value and second
351 // operand is SCEVAddRecExpr based on induction variable.
352 Value *V0 = CI->getOperand(0);
353 Value *V1 = CI->getOperand(1);
354
355 SCEVHandle SH0 = SE->getSCEV(V0);
356 SCEVHandle SH1 = SE->getSCEV(V1);
357
358 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000359 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000360 findIndVar(V1, L);
361 }
362 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000363 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000364 findIndVar(V0, L);
365 }
366
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000367 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000368 ExitCondition = NULL;
369 else if (IndVar) {
370 BasicBlock *Preheader = L->getLoopPreheader();
371 StartValue = IndVar->getIncomingValueForBlock(Preheader);
372 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000373}
374
Devang Patelbc5fe632007-08-07 00:25:56 +0000375/// Find condition inside a loop that is suitable candidate for index split.
376void LoopIndexSplit::findSplitCondition() {
377
Devang Patelc8dadbf2007-08-08 21:02:17 +0000378 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000379 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000380 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
381 I != E; ++I) {
Devang Pateld18971d2007-09-11 00:23:56 +0000382 SD.clear();
Devang Patel2545f7b2007-08-09 01:39:01 +0000383 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000384
Devang Patel2545f7b2007-08-09 01:39:01 +0000385 // If this basic block does not terminate in a conditional branch
386 // then terminator is not a suitable split condition.
387 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
388 if (!BR)
389 continue;
390
391 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000392 continue;
393
Devang Patel2545f7b2007-08-09 01:39:01 +0000394 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000395 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000396 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000397
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000398 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000399 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000400
Devang Patel7f526a82007-08-24 06:17:19 +0000401 // If split condition predicate is GT or GE then first execute
402 // false branch of split condition.
Devang Patela3a23f62007-09-11 01:10:45 +0000403 if (CI->getPredicate() == ICmpInst::ICMP_UGT
404 || CI->getPredicate() == ICmpInst::ICMP_SGT
405 || CI->getPredicate() == ICmpInst::ICMP_UGE
406 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel7f526a82007-08-24 06:17:19 +0000407 SD.UseTrueBranchFirst = false;
408
Devang Patel2545f7b2007-08-09 01:39:01 +0000409 // If one operand is loop invariant and second operand is SCEVAddRecExpr
410 // based on induction variable then CI is a candidate split condition.
Devang Patel12564292007-09-11 00:42:56 +0000411 if (safeICmpInst(CI, SD))
412 SplitData.push_back(SD);
413 }
414}
Devang Patel2545f7b2007-08-09 01:39:01 +0000415
Devang Patel12564292007-09-11 00:42:56 +0000416// safeIcmpInst - CI is considered safe instruction if one of the operand
417// is SCEVAddRecExpr based on induction variable and other operand is
418// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
419// and return true;
420bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000421
Devang Patel12564292007-09-11 00:42:56 +0000422 Value *V0 = CI->getOperand(0);
423 Value *V1 = CI->getOperand(1);
424
425 SCEVHandle SH0 = SE->getSCEV(V0);
426 SCEVHandle SH1 = SE->getSCEV(V1);
427
428 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
429 SD.SplitValue = V0;
430 SD.SplitCondition = CI;
431 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
432 if (PN == IndVar)
433 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000434 }
Devang Patel12564292007-09-11 00:42:56 +0000435 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
436 if (IndVarIncrement && IndVarIncrement == Insn)
437 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000438 }
439 }
Devang Patel12564292007-09-11 00:42:56 +0000440 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
441 SD.SplitValue = V1;
442 SD.SplitCondition = CI;
443 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
444 if (PN == IndVar)
445 return true;
446 }
447 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
448 if (IndVarIncrement && IndVarIncrement == Insn)
449 return true;
450 }
451 }
452
453 return false;
Devang Patelbc5fe632007-08-07 00:25:56 +0000454}
455
456/// processOneIterationLoop - Current loop L contains compare instruction
457/// that compares induction variable, IndVar, against loop invariant. If
458/// entire (i.e. meaningful) loop body is dominated by this compare
459/// instruction then loop body is executed only once. In such case eliminate
460/// loop structure surrounding this loop body. For example,
461/// for (int i = start; i < end; ++i) {
462/// if ( i == somevalue) {
463/// loop_body
464/// }
465/// }
466/// can be transformed into
467/// if (somevalue >= start && somevalue < end) {
468/// i = somevalue;
469/// loop_body
470/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000471bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000472
473 BasicBlock *Header = L->getHeader();
474
475 // First of all, check if SplitCondition dominates entire loop body
476 // or not.
477
478 // If SplitCondition is not in loop header then this loop is not suitable
479 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000480 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000481 return false;
482
Devang Patelbc5fe632007-08-07 00:25:56 +0000483 // If loop header includes loop variant instruction operands then
484 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000485 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000486 return false;
487
Devang Patel9263fc32007-08-20 23:51:18 +0000488 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000489 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000490 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000491 return false;
492
Devang Patel2bcb5012007-08-08 01:51:27 +0000493 // Update CFG.
494
Devang Patelc166b952007-08-20 20:49:01 +0000495 // Replace index variable with split value in loop body. Loop body is executed
496 // only when index variable is equal to split value.
497 IndVar->replaceAllUsesWith(SD.SplitValue);
498
499 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000500 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000501 BasicBlock *LatchSucc = NULL;
502 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
503 if (!BR)
504 return false;
505 Header->removePredecessor(Latch);
506 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
507 SI != E; ++SI) {
508 if (Header != *SI)
509 LatchSucc = *SI;
510 }
511 BR->setUnconditionalDest(LatchSucc);
512
Devang Patelbc5fe632007-08-07 00:25:56 +0000513 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000514 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000515
Devang Patelbc5fe632007-08-07 00:25:56 +0000516 // Replace split condition in header.
517 // Transform
518 // SplitCondition : icmp eq i32 IndVar, SplitValue
519 // into
520 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000521 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000522 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000523 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000524 Instruction *C1 = new ICmpInst(SignedPredicate ?
525 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000526 SD.SplitValue, StartValue, "lisplit",
527 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000528 Instruction *C2 = new ICmpInst(SignedPredicate ?
529 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000530 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000531 Terminator);
532 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
533 Terminator);
534 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
535 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000536
Devang Patelbc5fe632007-08-07 00:25:56 +0000537 // Now, clear latch block. Remove instructions that are responsible
538 // to increment induction variable.
539 Instruction *LTerminator = Latch->getTerminator();
540 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
541 LB != LE; ) {
542 Instruction *I = LB;
543 ++LB;
544 if (isa<PHINode>(I) || I == LTerminator)
545 continue;
546
Devang Patel59e0c062007-08-14 01:30:57 +0000547 if (I == IndVarIncrement)
548 I->replaceAllUsesWith(ExitValue);
549 else
550 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000551 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000552 }
553
Devang Patel901f67e2007-08-10 18:07:13 +0000554 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000555
556 // Update Dominator Info.
557 // Only CFG change done is to remove Latch to Header edge. This
558 // does not change dominator tree because Latch did not dominate
559 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000560 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000561 DominanceFrontier::iterator HeaderDF = DF->find(Header);
562 if (HeaderDF != DF->end())
563 DF->removeFromFrontier(HeaderDF, Header);
564
565 DominanceFrontier::iterator LatchDF = DF->find(Latch);
566 if (LatchDF != DF->end())
567 DF->removeFromFrontier(LatchDF, Header);
568 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000569 return true;
570}
571
572// If loop header includes loop variant instruction operands then
573// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000574bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000575
576 Instruction *Terminator = Header->getTerminator();
577 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
578 BI != BE; ++BI) {
579 Instruction *I = BI;
580
Devang Patel59e0c062007-08-14 01:30:57 +0000581 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000582 if (isa<PHINode>(I))
583 continue;
584
585 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000586 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000587 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000588
Devang Patel2545f7b2007-08-09 01:39:01 +0000589 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000590 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000591 continue;
592
593 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000594 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000595 continue;
596
Devang Patelbc5fe632007-08-07 00:25:56 +0000597 // Terminator is also harmless.
598 if (I == Terminator)
599 continue;
600
601 // Otherwise we have a instruction that may not be safe.
602 return false;
603 }
604
605 return true;
606}
607
Devang Patel9263fc32007-08-20 23:51:18 +0000608// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000609// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000610bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
611 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000612
Devang Patel9263fc32007-08-20 23:51:18 +0000613 for (BasicBlock::iterator BI = ExitingBlock->begin(),
614 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000615 Instruction *I = BI;
616
Devang Patel59e0c062007-08-14 01:30:57 +0000617 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000618 if (isa<PHINode>(I))
619 continue;
620
Devang Patel2545f7b2007-08-09 01:39:01 +0000621 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000622 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000623 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000624
Devang Patel2545f7b2007-08-09 01:39:01 +0000625 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000626 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000627
628 Value *Op0 = I->getOperand(0);
629 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000630 PHINode *PN = NULL;
631 ConstantInt *CI = NULL;
632
633 if ((PN = dyn_cast<PHINode>(Op0))) {
634 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000635 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000636 } else
637 if ((PN = dyn_cast<PHINode>(Op1))) {
638 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000639 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000640 }
641
Devang Patel61571ca2007-08-10 00:33:50 +0000642 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000643 continue;
644 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000645
Devang Patelbc5fe632007-08-07 00:25:56 +0000646 // I is an Exit condition if next instruction is block terminator.
647 // Exit condition is OK if it compares loop invariant exit value,
648 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000649 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000650 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000651 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000652 }
653
Devang Patel9263fc32007-08-20 23:51:18 +0000654 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000655 continue;
656
Devang Patelbc5fe632007-08-07 00:25:56 +0000657 // Otherwise we have instruction that may not be safe.
658 return false;
659 }
660
Devang Patel9263fc32007-08-20 23:51:18 +0000661 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000662 return true;
663}
664
Devang Patel60a94c72007-08-14 18:35:57 +0000665/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
666/// This routine is used to remove split condition's dead branch, dominated by
667/// DeadBB. LiveBB dominates split conidition's other branch.
668void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
669 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000670
Devang Patelf4277122007-08-15 03:31:47 +0000671 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000672 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000673 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
674 if (DeadBBDF != DF->end()) {
675 SmallVector<BasicBlock *, 8> PredBlocks;
676
677 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
678 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
679 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
680 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000681 FrontierBBs.push_back(FrontierBB);
682
Devang Patelf4277122007-08-15 03:31:47 +0000683 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
684 PredBlocks.clear();
685 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
686 PI != PE; ++PI) {
687 BasicBlock *P = *PI;
688 if (P == DeadBB || DT->dominates(DeadBB, P))
689 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000690 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000691
Devang Patelf4277122007-08-15 03:31:47 +0000692 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
693 FBI != FBE; ++FBI) {
694 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
695 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
696 PE = PredBlocks.end(); PI != PE; ++PI) {
697 BasicBlock *P = *PI;
698 PN->removeIncomingValue(P);
699 }
700 }
701 else
702 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000703 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000704 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000705 }
Devang Patelf4277122007-08-15 03:31:47 +0000706
707 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
708 SmallVector<BasicBlock *, 32> WorkList;
709 DomTreeNode *DN = DT->getNode(DeadBB);
710 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
711 E = df_end(DN); DI != E; ++DI) {
712 BasicBlock *BB = DI->getBlock();
713 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000714 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000715 }
716
717 while (!WorkList.empty()) {
718 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
719 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
720 BBI != BBE; ++BBI) {
721 Instruction *I = BBI;
722 I->replaceAllUsesWith(UndefValue::get(I->getType()));
723 I->eraseFromParent();
724 }
725 LPM->deleteSimpleAnalysisValue(BB, LP);
726 DT->eraseNode(BB);
727 DF->removeBlock(BB);
728 LI->removeBlock(BB);
729 BB->eraseFromParent();
730 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000731
732 // Update Frontier BBs' dominator info.
733 while (!FrontierBBs.empty()) {
734 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
735 BasicBlock *NewDominator = FBB->getSinglePredecessor();
736 if (!NewDominator) {
737 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
738 NewDominator = *PI;
739 ++PI;
740 if (NewDominator != LiveBB) {
741 for(; PI != PE; ++PI) {
742 BasicBlock *P = *PI;
743 if (P == LiveBB) {
744 NewDominator = LiveBB;
745 break;
746 }
747 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
748 }
749 }
750 }
751 assert (NewDominator && "Unable to fix dominator info.");
752 DT->changeImmediateDominator(FBB, NewDominator);
753 DF->changeImmediateDominator(FBB, NewDominator, DT);
754 }
755
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000756}
757
Devang Pateld662ace2007-08-22 18:27:01 +0000758/// safeSplitCondition - Return true if it is possible to
759/// split loop using given split condition.
760bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000761
Devang Pateld662ace2007-08-22 18:27:01 +0000762 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000763
Devang Pateld662ace2007-08-22 18:27:01 +0000764 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000765 // In triangle loop, split condition is in header and one of the
766 // the split destination is loop latch. If split condition is EQ
767 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000768 BasicBlock *Latch = L->getLoopLatch();
769 BranchInst *SplitTerminator =
770 cast<BranchInst>(SplitCondBlock->getTerminator());
771 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
772 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
773 if (L->getHeader() == SplitCondBlock
774 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000775 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000776
Devang Patelac7c7c22007-08-27 21:34:31 +0000777 // If split condition branches heads do not have single predecessor,
778 // SplitCondBlock, then is not possible to remove inactive branch.
779 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000780 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000781
Devang Patel4e2075d2007-08-24 05:36:56 +0000782 // Finally this split condition is safe only if merge point for
783 // split condition branch is loop latch. This check along with previous
784 // check, to ensure that exit condition is in either loop latch or header,
785 // filters all loops with non-empty loop body between merge point
786 // and exit condition.
787 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
788 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
789 if (Succ0DF->second.count(Latch))
790 return true;
791
792 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
793 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
794 if (Succ1DF->second.count(Latch))
795 return true;
796
797 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000798}
799
Devang Pateledea5b32007-08-25 00:56:38 +0000800/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
801/// based on split value.
802void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
803
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000804 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
805 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +0000806 const Type *Ty = SD.SplitValue->getType();
807 bool Sign = ExitCondition->isSignedPredicate();
808 BasicBlock *Preheader = L->getLoopPreheader();
809 Instruction *PHTerminator = Preheader->getTerminator();
810
811 // Initially use split value as upper loop bound for first loop and lower loop
812 // bound for second loop.
813 Value *AEV = SD.SplitValue;
814 Value *BSV = SD.SplitValue;
815
816 switch (ExitCondition->getPredicate()) {
817 case ICmpInst::ICMP_SGT:
818 case ICmpInst::ICMP_UGT:
819 case ICmpInst::ICMP_SGE:
820 case ICmpInst::ICMP_UGE:
821 default:
822 assert (0 && "Unexpected exit condition predicate");
823
824 case ICmpInst::ICMP_SLT:
825 case ICmpInst::ICMP_ULT:
826 {
827 switch (SP) {
828 case ICmpInst::ICMP_SLT:
829 case ICmpInst::ICMP_ULT:
830 //
831 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
832 //
833 // is transformed into
834 // AEV = BSV = SV
835 // for (i = LB; i < min(UB, AEV); ++i)
836 // A;
837 // for (i = max(LB, BSV); i < UB; ++i);
838 // B;
839 break;
840 case ICmpInst::ICMP_SLE:
841 case ICmpInst::ICMP_ULE:
842 {
843 //
844 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
845 //
846 // is transformed into
847 //
848 // AEV = SV + 1
849 // BSV = SV + 1
850 // for (i = LB; i < min(UB, AEV); ++i)
851 // A;
852 // for (i = max(LB, BSV); i < UB; ++i)
853 // B;
854 BSV = BinaryOperator::createAdd(SD.SplitValue,
855 ConstantInt::get(Ty, 1, Sign),
856 "lsplit.add", PHTerminator);
857 AEV = BSV;
858 }
859 break;
860 case ICmpInst::ICMP_SGE:
861 case ICmpInst::ICMP_UGE:
862 //
863 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
864 //
865 // is transformed into
866 // AEV = BSV = SV
867 // for (i = LB; i < min(UB, AEV); ++i)
868 // B;
869 // for (i = max(BSV, LB); i < UB; ++i)
870 // A;
871 break;
872 case ICmpInst::ICMP_SGT:
873 case ICmpInst::ICMP_UGT:
874 {
875 //
876 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
877 //
878 // is transformed into
879 //
880 // BSV = AEV = SV + 1
881 // for (i = LB; i < min(UB, AEV); ++i)
882 // B;
883 // for (i = max(LB, BSV); i < UB; ++i)
884 // A;
885 BSV = BinaryOperator::createAdd(SD.SplitValue,
886 ConstantInt::get(Ty, 1, Sign),
887 "lsplit.add", PHTerminator);
888 AEV = BSV;
889 }
890 break;
891 default:
892 assert (0 && "Unexpected split condition predicate");
893 break;
894 } // end switch (SP)
895 }
896 break;
897 case ICmpInst::ICMP_SLE:
898 case ICmpInst::ICMP_ULE:
899 {
900 switch (SP) {
901 case ICmpInst::ICMP_SLT:
902 case ICmpInst::ICMP_ULT:
903 //
904 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
905 //
906 // is transformed into
907 // AEV = SV - 1;
908 // BSV = SV;
909 // for (i = LB; i <= min(UB, AEV); ++i)
910 // A;
911 // for (i = max(LB, BSV); i <= UB; ++i)
912 // B;
913 AEV = BinaryOperator::createSub(SD.SplitValue,
914 ConstantInt::get(Ty, 1, Sign),
915 "lsplit.sub", PHTerminator);
916 break;
917 case ICmpInst::ICMP_SLE:
918 case ICmpInst::ICMP_ULE:
919 //
920 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
921 //
922 // is transformed into
923 // AEV = SV;
924 // BSV = SV + 1;
925 // for (i = LB; i <= min(UB, AEV); ++i)
926 // A;
927 // for (i = max(LB, BSV); i <= UB; ++i)
928 // B;
929 BSV = BinaryOperator::createAdd(SD.SplitValue,
930 ConstantInt::get(Ty, 1, Sign),
931 "lsplit.add", PHTerminator);
932 break;
933 case ICmpInst::ICMP_SGT:
934 case ICmpInst::ICMP_UGT:
935 //
936 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
937 //
938 // is transformed into
939 // AEV = SV;
940 // BSV = SV + 1;
941 // for (i = LB; i <= min(AEV, UB); ++i)
942 // B;
943 // for (i = max(LB, BSV); i <= UB; ++i)
944 // A;
945 BSV = BinaryOperator::createAdd(SD.SplitValue,
946 ConstantInt::get(Ty, 1, Sign),
947 "lsplit.add", PHTerminator);
948 break;
949 case ICmpInst::ICMP_SGE:
950 case ICmpInst::ICMP_UGE:
951 // ** TODO **
952 //
953 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
954 //
955 // is transformed into
956 // AEV = SV - 1;
957 // BSV = SV;
958 // for (i = LB; i <= min(AEV, UB); ++i)
959 // B;
960 // for (i = max(LB, BSV); i <= UB; ++i)
961 // A;
962 AEV = BinaryOperator::createSub(SD.SplitValue,
963 ConstantInt::get(Ty, 1, Sign),
964 "lsplit.sub", PHTerminator);
965 break;
966 default:
967 assert (0 && "Unexpected split condition predicate");
968 break;
969 } // end switch (SP)
970 }
971 break;
972 }
973
974 // Calculate ALoop induction variable's new exiting value and
975 // BLoop induction variable's new starting value. Calculuate these
976 // values in original loop's preheader.
977 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
978 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000979 Value *C1 = new ICmpInst(Sign ?
980 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
981 AEV,
982 ExitCondition->getOperand(ExitValueNum),
983 "lsplit.ev", PHTerminator);
984 SD.A_ExitValue = new SelectInst(C1, AEV,
985 ExitCondition->getOperand(ExitValueNum),
986 "lsplit.ev", PHTerminator);
987
988 Value *C2 = new ICmpInst(Sign ?
989 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
990 BSV, StartValue, "lsplit.sv",
991 PHTerminator);
992 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
993 "lsplit.sv", PHTerminator);
994}
995
Devang Pateld662ace2007-08-22 18:27:01 +0000996/// splitLoop - Split current loop L in two loops using split information
997/// SD. Update dominator information. Maintain LCSSA form.
998bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
999
1000 if (!safeSplitCondition(SD))
1001 return false;
1002
Devang Patela0ac7262007-08-22 19:33:29 +00001003 // After loop is cloned there are two loops.
1004 //
1005 // First loop, referred as ALoop, executes first part of loop's iteration
1006 // space split. Second loop, referred as BLoop, executes remaining
1007 // part of loop's iteration space.
1008 //
1009 // ALoop's exit edge enters BLoop's header through a forwarding block which
1010 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001011 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001012
Devang Pateledea5b32007-08-25 00:56:38 +00001013 // Calculate ALoop induction variable's new exiting value and
1014 // BLoop induction variable's new starting value.
1015 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001016
Devang Patela0ac7262007-08-22 19:33:29 +00001017 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001018 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001019 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001020 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001021 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001022
Devang Patela0ac7262007-08-22 19:33:29 +00001023 //[*] ALoop's exiting edge BLoop's header.
1024 // ALoop's original exit block becomes BLoop's exit block.
1025 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1026 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1027 BranchInst *A_ExitInsn =
1028 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1029 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1030 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1031 if (L->contains(B_ExitBlock)) {
1032 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1033 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001034 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001035 A_ExitInsn->setSuccessor(1, B_Header);
1036
1037 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001038 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001039
Devang Patela0ac7262007-08-22 19:33:29 +00001040 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1041 // original loop's preheader. Add incoming PHINode values from
1042 // ALoop's exiting block. Update BLoop header's domiantor info.
1043
Devang Patel59e0c062007-08-14 01:30:57 +00001044 // Collect inverse map of Header PHINodes.
1045 DenseMap<Value *, Value *> InverseMap;
1046 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1047 BE = L->getHeader()->end(); BI != BE; ++BI) {
1048 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1049 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1050 InverseMap[PNClone] = PN;
1051 } else
1052 break;
1053 }
Devang Pateledea5b32007-08-25 00:56:38 +00001054
Devang Patela0ac7262007-08-22 19:33:29 +00001055 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001056 BI != BE; ++BI) {
1057 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001058 // Remove incoming value from original preheader.
1059 PN->removeIncomingValue(Preheader);
1060
1061 // Add incoming value from A_ExitingBlock.
1062 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001063 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001064 else {
1065 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001066 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1067 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001068 }
1069 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001070 break;
1071 }
Devang Patela0ac7262007-08-22 19:33:29 +00001072 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1073 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001074
Devang Patela0ac7262007-08-22 19:33:29 +00001075 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1076 // block. Remove incoming PHINode values from ALoop's exiting block.
1077 // Add new incoming values from BLoop's incoming exiting value.
1078 // Update BLoop exit block's dominator info..
1079 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1080 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001081 BI != BE; ++BI) {
1082 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001083 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1084 B_ExitingBlock);
1085 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001086 } else
1087 break;
1088 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001089
Devang Patela0ac7262007-08-22 19:33:29 +00001090 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1091 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001092
Devang Patela0ac7262007-08-22 19:33:29 +00001093 //[*] Split ALoop's exit edge. This creates a new block which
1094 // serves two purposes. First one is to hold PHINode defnitions
1095 // to ensure that ALoop's LCSSA form. Second use it to act
1096 // as a preheader for BLoop.
1097 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001098
Devang Patela0ac7262007-08-22 19:33:29 +00001099 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1100 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1101 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001102 BI != BE; ++BI) {
1103 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001104 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001105 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001106 newPHI->addIncoming(V1, A_ExitingBlock);
1107 A_ExitBlock->getInstList().push_front(newPHI);
1108 PN->removeIncomingValue(A_ExitBlock);
1109 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001110 } else
1111 break;
1112 }
1113
Devang Patela0ac7262007-08-22 19:33:29 +00001114 //[*] Eliminate split condition's inactive branch from ALoop.
1115 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1116 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001117 BasicBlock *A_InactiveBranch = NULL;
1118 BasicBlock *A_ActiveBranch = NULL;
1119 if (SD.UseTrueBranchFirst) {
1120 A_ActiveBranch = A_BR->getSuccessor(0);
1121 A_InactiveBranch = A_BR->getSuccessor(1);
1122 } else {
1123 A_ActiveBranch = A_BR->getSuccessor(1);
1124 A_InactiveBranch = A_BR->getSuccessor(0);
1125 }
Devang Patel4e585c72007-08-24 19:32:26 +00001126 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001127 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1128
1129 //[*] Eliminate split condition's inactive branch in from BLoop.
1130 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1131 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001132 BasicBlock *B_InactiveBranch = NULL;
1133 BasicBlock *B_ActiveBranch = NULL;
1134 if (SD.UseTrueBranchFirst) {
1135 B_ActiveBranch = B_BR->getSuccessor(1);
1136 B_InactiveBranch = B_BR->getSuccessor(0);
1137 } else {
1138 B_ActiveBranch = B_BR->getSuccessor(0);
1139 B_InactiveBranch = B_BR->getSuccessor(1);
1140 }
Devang Patel4e585c72007-08-24 19:32:26 +00001141 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001142 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1143
Devang Patelcd71bed2007-08-25 02:39:24 +00001144 BasicBlock *A_Header = L->getHeader();
1145 if (A_ExitingBlock == A_Header)
1146 return true;
1147
1148 //[*] Move exit condition into split condition block to avoid
1149 // executing dead loop iteration.
1150 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1151 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1152 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1153
1154 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001155 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1156 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001157
1158 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1159 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1160
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001161 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001162}
Devang Patelcd71bed2007-08-25 02:39:24 +00001163
1164// moveExitCondition - Move exit condition EC into split condition block CondBB.
1165void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1166 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1167 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1168
1169 BasicBlock *ExitingBB = EC->getParent();
1170 Instruction *CurrentBR = CondBB->getTerminator();
1171
1172 // Move exit condition into split condition block.
1173 EC->moveBefore(CurrentBR);
1174 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1175
1176 // Move exiting block's branch into split condition block. Update its branch
1177 // destination.
1178 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1179 ExitingBR->moveBefore(CurrentBR);
1180 if (ExitingBR->getSuccessor(0) == ExitBB)
1181 ExitingBR->setSuccessor(1, ActiveBB);
1182 else
1183 ExitingBR->setSuccessor(0, ActiveBB);
1184
1185 // Remove split condition and current split condition branch.
1186 SC->eraseFromParent();
1187 CurrentBR->eraseFromParent();
1188
1189 // Connect exiting block to split condition block.
1190 new BranchInst(CondBB, ExitingBB);
1191
1192 // Update PHINodes
1193 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1194
1195 // Fix dominator info.
1196 // ExitBB is now dominated by CondBB
1197 DT->changeImmediateDominator(ExitBB, CondBB);
1198 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1199
1200 // Basicblocks dominated by ActiveBB may have ExitingBB or
1201 // a basic block outside the loop in their DF list. If so,
1202 // replace it with CondBB.
1203 DomTreeNode *Node = DT->getNode(ActiveBB);
1204 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1205 DI != DE; ++DI) {
1206 BasicBlock *BB = DI->getBlock();
1207 DominanceFrontier::iterator BBDF = DF->find(BB);
1208 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1209 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1210 while (DomSetI != DomSetE) {
1211 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1212 ++DomSetI;
1213 BasicBlock *DFBB = *CurrentItr;
1214 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1215 BBDF->second.erase(DFBB);
1216 BBDF->second.insert(CondBB);
1217 }
1218 }
1219 }
1220}
1221
1222/// updatePHINodes - CFG has been changed.
1223/// Before
1224/// - ExitBB's single predecessor was Latch
1225/// - Latch's second successor was Header
1226/// Now
1227/// - ExitBB's single predecessor was Header
1228/// - Latch's one and only successor was Header
1229///
1230/// Update ExitBB PHINodes' to reflect this change.
1231void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1232 BasicBlock *Header,
1233 PHINode *IV, Instruction *IVIncrement) {
1234
1235 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1236 BI != BE; ++BI) {
1237 PHINode *PN = dyn_cast<PHINode>(BI);
1238 if (!PN)
1239 break;
1240
1241 Value *V = PN->getIncomingValueForBlock(Latch);
1242 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1243 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1244 // (i.e. PN :)).
1245 // The second use is in Header and it is new incoming value for PN.
1246 PHINode *U1 = NULL;
1247 PHINode *U2 = NULL;
1248 Value *NewV = NULL;
1249 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1250 UI != E; ++UI) {
1251 if (!U1)
1252 U1 = cast<PHINode>(*UI);
1253 else if (!U2)
1254 U2 = cast<PHINode>(*UI);
1255 else
1256 assert ( 0 && "Unexpected third use of this PHINode");
1257 }
1258 assert (U1 && U2 && "Unable to find two uses");
1259
1260 if (U1->getParent() == Header)
1261 NewV = U1;
1262 else
1263 NewV = U2;
1264 PN->addIncoming(NewV, Header);
1265
1266 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1267 // If this instruction is IVIncrement then IV is new incoming value
1268 // from header otherwise this instruction must be incoming value from
1269 // header because loop is in LCSSA form.
1270 if (PHI == IVIncrement)
1271 PN->addIncoming(IV, Header);
1272 else
1273 PN->addIncoming(V, Header);
1274 } else
1275 // Otherwise this is an incoming value from header because loop is in
1276 // LCSSA form.
1277 PN->addIncoming(V, Header);
1278
1279 // Remove incoming value from Latch.
1280 PN->removeIncomingValue(Latch);
1281 }
1282}