blob: 5faec97a9711d1b52fcc1f2016712b340599db38 [file] [log] [blame]
Devang Patelfee76bd2007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelfee76bd2007-08-07 00:25:56 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelfee76bd2007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel787a7132007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-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 Patel423c8b22007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patel71554b82007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel4259fe32007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Patel4a69da92007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patelc9d123d2007-08-09 01:39:01 +000063
Devang Patel71554b82007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patel4f12c5f2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patel71554b82007-08-08 21:02:17 +000069
Devang Patel4259fe32007-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 Patel4a69da92007-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 Patel9021c702007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel9021c702007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel4259fe32007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Patel4a69da92007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000087 }
Devang Patelc9d123d2007-08-09 01:39:01 +000088
Devang Patel71554b82007-08-08 21:02:17 +000089 };
Devang Patelbacf5192007-08-10 00:33:50 +000090
Devang Patel71554b82007-08-08 21:02:17 +000091 private:
Devang Pateld35ed2c2007-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 Patelfee76bd2007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patelbacf5192007-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 Patelfee76bd2007-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 Patel423c8b22007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patel5279d062007-09-17 20:39:48 +0000114
115 void updateLoopBounds(ICmpInst *CI);
116 /// updateLoopIterationSpace - Current loop body is covered by an AND
117 /// instruction whose operands compares induction variables with loop
118 /// invariants. If possible, hoist this check outside the loop by
119 /// updating appropriate start and end values for induction variable.
120 bool updateLoopIterationSpace(SplitInfo &SD);
121
Devang Patel9704fcf2007-08-08 22:25:28 +0000122 /// If loop header includes loop variant instruction operands then
123 /// this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000124 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000125
Devang Patel1cc2ec82007-08-20 23:51:18 +0000126 /// If Exiting block includes loop variant instructions then this
Devang Patel9704fcf2007-08-08 22:25:28 +0000127 /// loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000128 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000129
Devang Patela6a86632007-08-14 18:35:57 +0000130 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131 /// This routine is used to remove split condition's dead branch, dominated by
132 /// DeadBB. LiveBB dominates split conidition's other branch.
133 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel98147a32007-08-12 07:02:51 +0000134
Devang Pateldc523952007-08-22 18:27:01 +0000135 /// safeSplitCondition - Return true if it is possible to
136 /// split loop using given split condition.
137 bool safeSplitCondition(SplitInfo &SD);
138
Devang Patel4a69da92007-08-25 00:56:38 +0000139 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140 /// based on split value.
141 void calculateLoopBounds(SplitInfo &SD);
142
Devang Pateld79faee2007-08-25 02:39:24 +0000143 /// updatePHINodes - CFG has been changed.
144 /// Before
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
147 /// Now
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
150 ///
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
153 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000155
156 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159 PHINode *IV, Instruction *IVAdd, Loop *LP);
160
Devang Pateldc523952007-08-22 18:27:01 +0000161 /// splitLoop - Split current loop L in two loops using split information
162 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patel71554b82007-08-08 21:02:17 +0000163 bool splitLoop(SplitInfo &SD);
Devang Patelfee76bd2007-08-07 00:25:56 +0000164
Devang Patelbacf5192007-08-10 00:33:50 +0000165 void initialize() {
166 IndVar = NULL;
167 IndVarIncrement = NULL;
168 ExitCondition = NULL;
Devang Patel98147a32007-08-12 07:02:51 +0000169 StartValue = NULL;
170 ExitValueNum = 0;
171 SplitData.clear();
Devang Patelbacf5192007-08-10 00:33:50 +0000172 }
173
Devang Patelfee76bd2007-08-07 00:25:56 +0000174 private:
175
176 // Current Loop.
177 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000178 LPPassManager *LPM;
179 LoopInfo *LI;
Devang Patelfee76bd2007-08-07 00:25:56 +0000180 ScalarEvolution *SE;
Devang Patel9704fcf2007-08-08 22:25:28 +0000181 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000182 DominanceFrontier *DF;
Devang Patel71554b82007-08-08 21:02:17 +0000183 SmallVector<SplitInfo, 4> SplitData;
Devang Patelbacf5192007-08-10 00:33:50 +0000184
185 // Induction variable whose range is being split by this transformation.
186 PHINode *IndVar;
187 Instruction *IndVarIncrement;
188
189 // Loop exit condition.
190 ICmpInst *ExitCondition;
191
192 // Induction variable's initial value.
193 Value *StartValue;
194
Devang Patel98147a32007-08-12 07:02:51 +0000195 // Induction variable's final loop exit value operand number in exit condition..
196 unsigned ExitValueNum;
Devang Patelfee76bd2007-08-07 00:25:56 +0000197 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000198}
199
Dan Gohman844731a2008-05-13 00:00:25 +0000200char LoopIndexSplit::ID = 0;
201static RegisterPass<LoopIndexSplit>
202X("loop-index-split", "Index Split Loops");
203
Devang Patelfee76bd2007-08-07 00:25:56 +0000204LoopPass *llvm::createLoopIndexSplitPass() {
205 return new LoopIndexSplit();
206}
207
208// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000209bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000210 bool Changed = false;
211 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000212 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000213
Devang Patel3fe4f212007-08-15 02:14:55 +0000214 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000215 if (!L->getSubLoops().empty())
216 return false;
217
Devang Patelfee76bd2007-08-07 00:25:56 +0000218 SE = &getAnalysis<ScalarEvolution>();
Devang Patel9704fcf2007-08-08 22:25:28 +0000219 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000220 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000221 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000222
Devang Patelbacf5192007-08-10 00:33:50 +0000223 initialize();
224
225 findLoopConditionals();
226
227 if (!ExitCondition)
228 return false;
229
Devang Patelfee76bd2007-08-07 00:25:56 +0000230 findSplitCondition();
231
Devang Patel71554b82007-08-08 21:02:17 +0000232 if (SplitData.empty())
Devang Patelfee76bd2007-08-07 00:25:56 +0000233 return false;
234
Devang Patel71554b82007-08-08 21:02:17 +0000235 // First see if it is possible to eliminate loop itself or not.
David Greenea022e3f2008-04-02 18:24:46 +0000236 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
237 SI != SplitData.end();) {
Devang Patel71554b82007-08-08 21:02:17 +0000238 SplitInfo &SD = *SI;
Devang Patel4f12c5f2007-09-11 00:12:56 +0000239 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
Devang Patel5279d062007-09-17 20:39:48 +0000240 if (SD.SplitCondition->getOpcode() == Instruction::And) {
241 Changed = updateLoopIterationSpace(SD);
242 if (Changed) {
243 ++NumIndexSplit;
244 // If is loop is eliminated then nothing else to do here.
245 return Changed;
246 } else {
247 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000248 SI = SplitData.erase(Delete_SI);
Devang Patel5279d062007-09-17 20:39:48 +0000249 }
250 }
251 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel423c8b22007-08-10 18:07:13 +0000252 Changed = processOneIterationLoop(SD);
Devang Patel71554b82007-08-08 21:02:17 +0000253 if (Changed) {
254 ++NumIndexSplit;
255 // If is loop is eliminated then nothing else to do here.
256 return Changed;
Devang Pateld651f652007-08-20 20:24:15 +0000257 } else {
258 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000259 SI = SplitData.erase(Delete_SI);
Devang Patel71554b82007-08-08 21:02:17 +0000260 }
Devang Pateld651f652007-08-20 20:24:15 +0000261 } else
262 ++SI;
Devang Patel71554b82007-08-08 21:02:17 +0000263 }
264
Devang Patel4259fe32007-08-24 06:17:19 +0000265 if (SplitData.empty())
266 return false;
267
Devang Patel9704fcf2007-08-08 22:25:28 +0000268 // Split most profitiable condition.
Devang Patel7237d112007-08-24 05:21:13 +0000269 // FIXME : Implement cost analysis.
270 unsigned MostProfitableSDIndex = 0;
271 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel9704fcf2007-08-08 22:25:28 +0000272
Devang Patelfee76bd2007-08-07 00:25:56 +0000273 if (Changed)
274 ++NumIndexSplit;
Devang Patel71554b82007-08-08 21:02:17 +0000275
Devang Patelfee76bd2007-08-07 00:25:56 +0000276 return Changed;
277}
278
Devang Patelc9d123d2007-08-09 01:39:01 +0000279/// Return true if V is a induction variable or induction variable's
280/// increment for loop L.
Devang Patelbacf5192007-08-10 00:33:50 +0000281void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000282
283 Instruction *I = dyn_cast<Instruction>(V);
284 if (!I)
Devang Patelbacf5192007-08-10 00:33:50 +0000285 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000286
287 // Check if I is a phi node from loop header or not.
288 if (PHINode *PN = dyn_cast<PHINode>(V)) {
289 if (PN->getParent() == L->getHeader()) {
Devang Patelbacf5192007-08-10 00:33:50 +0000290 IndVar = PN;
291 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000292 }
293 }
294
295 // Check if I is a add instruction whose one operand is
296 // phi node from loop header and second operand is constant.
297 if (I->getOpcode() != Instruction::Add)
Devang Patelbacf5192007-08-10 00:33:50 +0000298 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000299
300 Value *Op0 = I->getOperand(0);
301 Value *Op1 = I->getOperand(1);
302
Devang Patelc840da12008-01-29 02:20:41 +0000303 if (PHINode *PN = dyn_cast<PHINode>(Op0))
304 if (PN->getParent() == L->getHeader())
305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
306 if (CI->isOne()) {
307 IndVar = PN;
308 IndVarIncrement = I;
309 return;
310 }
311
312 if (PHINode *PN = dyn_cast<PHINode>(Op1))
313 if (PN->getParent() == L->getHeader())
314 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
315 if (CI->isOne()) {
316 IndVar = PN;
317 IndVarIncrement = I;
318 return;
319 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000320
Devang Patelbacf5192007-08-10 00:33:50 +0000321 return;
322}
323
324// Find loop's exit condition and associated induction variable.
325void LoopIndexSplit::findLoopConditionals() {
326
Devang Patel1cc2ec82007-08-20 23:51:18 +0000327 BasicBlock *ExitingBlock = NULL;
Devang Patelbacf5192007-08-10 00:33:50 +0000328
329 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
330 I != E; ++I) {
331 BasicBlock *BB = *I;
332 if (!L->isLoopExit(BB))
333 continue;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000334 if (ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000335 return;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000336 ExitingBlock = BB;
Devang Patelbacf5192007-08-10 00:33:50 +0000337 }
338
Devang Patel1cc2ec82007-08-20 23:51:18 +0000339 if (!ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000340 return;
Devang Patelb88e4202007-08-24 05:36:56 +0000341
342 // If exiting block is neither loop header nor loop latch then this loop is
343 // not suitable.
344 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
345 return;
346
Devang Patelbacf5192007-08-10 00:33:50 +0000347 // If exit block's terminator is conditional branch inst then we have found
348 // exit condition.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000349 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patelbacf5192007-08-10 00:33:50 +0000350 if (!BR || BR->isUnconditional())
351 return;
352
353 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
354 if (!CI)
355 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000356
Bill Wendlingc6849102007-09-14 01:13:55 +0000357 // FIXME
Devang Patelbabbe272007-09-19 00:28:47 +0000358 if (CI->getPredicate() == ICmpInst::ICMP_EQ
Bill Wendlingc6849102007-09-14 01:13:55 +0000359 || CI->getPredicate() == ICmpInst::ICMP_NE)
360 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000361
Devang Patelbacf5192007-08-10 00:33:50 +0000362 ExitCondition = CI;
363
364 // Exit condition's one operand is loop invariant exit value and second
365 // operand is SCEVAddRecExpr based on induction variable.
366 Value *V0 = CI->getOperand(0);
367 Value *V1 = CI->getOperand(1);
368
369 SCEVHandle SH0 = SE->getSCEV(V0);
370 SCEVHandle SH1 = SE->getSCEV(V1);
371
372 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel98147a32007-08-12 07:02:51 +0000373 ExitValueNum = 0;
Devang Patelbacf5192007-08-10 00:33:50 +0000374 findIndVar(V1, L);
375 }
376 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel98147a32007-08-12 07:02:51 +0000377 ExitValueNum = 1;
Devang Patelbacf5192007-08-10 00:33:50 +0000378 findIndVar(V0, L);
379 }
380
Devang Patel98147a32007-08-12 07:02:51 +0000381 if (!IndVar)
Devang Patelbacf5192007-08-10 00:33:50 +0000382 ExitCondition = NULL;
383 else if (IndVar) {
384 BasicBlock *Preheader = L->getLoopPreheader();
385 StartValue = IndVar->getIncomingValueForBlock(Preheader);
386 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000387}
388
Devang Patelfee76bd2007-08-07 00:25:56 +0000389/// Find condition inside a loop that is suitable candidate for index split.
390void LoopIndexSplit::findSplitCondition() {
391
Devang Patel71554b82007-08-08 21:02:17 +0000392 SplitInfo SD;
Devang Patelc9d123d2007-08-09 01:39:01 +0000393 // Check all basic block's terminators.
Devang Patelc9d123d2007-08-09 01:39:01 +0000394 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
395 I != E; ++I) {
Devang Patel964be452007-09-11 00:23:56 +0000396 SD.clear();
Devang Patelc9d123d2007-08-09 01:39:01 +0000397 BasicBlock *BB = *I;
Devang Patelfee76bd2007-08-07 00:25:56 +0000398
Devang Patelc9d123d2007-08-09 01:39:01 +0000399 // If this basic block does not terminate in a conditional branch
400 // then terminator is not a suitable split condition.
401 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
402 if (!BR)
403 continue;
404
405 if (BR->isUnconditional())
Devang Patelfee76bd2007-08-07 00:25:56 +0000406 continue;
407
Devang Patel5279d062007-09-17 20:39:48 +0000408 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
409 if (AndI->getOpcode() == Instruction::And) {
410 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
411 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
412
413 if (!Op0 || !Op1)
414 continue;
415
416 if (!safeICmpInst(Op0, SD))
417 continue;
418 SD.clear();
419 if (!safeICmpInst(Op1, SD))
420 continue;
421 SD.clear();
422 SD.SplitCondition = AndI;
423 SplitData.push_back(SD);
424 continue;
425 }
426 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000427 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patelbacf5192007-08-10 00:33:50 +0000428 if (!CI || CI == ExitCondition)
Devang Patelba32a5f2007-09-10 23:57:58 +0000429 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000430
Devang Patelc830aee2007-08-24 06:02:25 +0000431 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patelba32a5f2007-09-10 23:57:58 +0000432 continue;
Devang Patelc830aee2007-08-24 06:02:25 +0000433
Devang Patel4259fe32007-08-24 06:17:19 +0000434 // If split condition predicate is GT or GE then first execute
435 // false branch of split condition.
Devang Patelc3957d12007-09-11 01:10:45 +0000436 if (CI->getPredicate() == ICmpInst::ICMP_UGT
437 || CI->getPredicate() == ICmpInst::ICMP_SGT
438 || CI->getPredicate() == ICmpInst::ICMP_UGE
439 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel4259fe32007-08-24 06:17:19 +0000440 SD.UseTrueBranchFirst = false;
441
Devang Patelc9d123d2007-08-09 01:39:01 +0000442 // If one operand is loop invariant and second operand is SCEVAddRecExpr
443 // based on induction variable then CI is a candidate split condition.
Devang Pateld35ed2c2007-09-11 00:42:56 +0000444 if (safeICmpInst(CI, SD))
445 SplitData.push_back(SD);
446 }
447}
Devang Patelc9d123d2007-08-09 01:39:01 +0000448
Devang Pateld35ed2c2007-09-11 00:42:56 +0000449// safeIcmpInst - CI is considered safe instruction if one of the operand
450// is SCEVAddRecExpr based on induction variable and other operand is
451// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
452// and return true;
453bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000454
Devang Pateld35ed2c2007-09-11 00:42:56 +0000455 Value *V0 = CI->getOperand(0);
456 Value *V1 = CI->getOperand(1);
457
458 SCEVHandle SH0 = SE->getSCEV(V0);
459 SCEVHandle SH1 = SE->getSCEV(V1);
460
461 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
462 SD.SplitValue = V0;
463 SD.SplitCondition = CI;
464 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
465 if (PN == IndVar)
466 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000467 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000468 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
469 if (IndVarIncrement && IndVarIncrement == Insn)
470 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000471 }
472 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000473 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
474 SD.SplitValue = V1;
475 SD.SplitCondition = CI;
476 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
477 if (PN == IndVar)
478 return true;
479 }
480 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
481 if (IndVarIncrement && IndVarIncrement == Insn)
482 return true;
483 }
484 }
485
486 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000487}
488
489/// processOneIterationLoop - Current loop L contains compare instruction
490/// that compares induction variable, IndVar, against loop invariant. If
491/// entire (i.e. meaningful) loop body is dominated by this compare
492/// instruction then loop body is executed only once. In such case eliminate
493/// loop structure surrounding this loop body. For example,
494/// for (int i = start; i < end; ++i) {
495/// if ( i == somevalue) {
496/// loop_body
497/// }
498/// }
499/// can be transformed into
500/// if (somevalue >= start && somevalue < end) {
501/// i = somevalue;
502/// loop_body
503/// }
Devang Patel423c8b22007-08-10 18:07:13 +0000504bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000505
506 BasicBlock *Header = L->getHeader();
507
508 // First of all, check if SplitCondition dominates entire loop body
509 // or not.
510
511 // If SplitCondition is not in loop header then this loop is not suitable
512 // for this transformation.
Devang Patel71554b82007-08-08 21:02:17 +0000513 if (SD.SplitCondition->getParent() != Header)
Devang Patelfee76bd2007-08-07 00:25:56 +0000514 return false;
515
Devang Patelfee76bd2007-08-07 00:25:56 +0000516 // If loop header includes loop variant instruction operands then
517 // this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000518 if (!safeHeader(SD, Header))
Devang Patelfee76bd2007-08-07 00:25:56 +0000519 return false;
520
Devang Patel1cc2ec82007-08-20 23:51:18 +0000521 // If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000522 // loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000523 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelfee76bd2007-08-07 00:25:56 +0000524 return false;
525
Devang Patel968eee22007-09-19 00:15:16 +0000526 // Filter loops where split condition's false branch is not empty.
527 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
528 return false;
529
Devang Patel8893ca62007-09-17 21:01:05 +0000530 // If split condition is not safe then do not process this loop.
531 // For example,
532 // for(int i = 0; i < N; i++) {
533 // if ( i == XYZ) {
534 // A;
535 // else
536 // B;
537 // }
538 // C;
539 // D;
540 // }
541 if (!safeSplitCondition(SD))
542 return false;
543
Devang Patel84ef08b2007-09-19 00:11:01 +0000544 BasicBlock *Latch = L->getLoopLatch();
545 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
546 if (!BR)
547 return false;
548
Devang Patel6a2bfda2007-08-08 01:51:27 +0000549 // Update CFG.
550
Devang Patelebc5fea2007-08-20 20:49:01 +0000551 // Replace index variable with split value in loop body. Loop body is executed
552 // only when index variable is equal to split value.
553 IndVar->replaceAllUsesWith(SD.SplitValue);
554
555 // Remove Latch to Header edge.
Devang Patel6a2bfda2007-08-08 01:51:27 +0000556 BasicBlock *LatchSucc = NULL;
Devang Patel6a2bfda2007-08-08 01:51:27 +0000557 Header->removePredecessor(Latch);
558 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
559 SI != E; ++SI) {
560 if (Header != *SI)
561 LatchSucc = *SI;
562 }
563 BR->setUnconditionalDest(LatchSucc);
564
Devang Patelfee76bd2007-08-07 00:25:56 +0000565 Instruction *Terminator = Header->getTerminator();
Devang Patelada054a2007-08-14 01:30:57 +0000566 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelfee76bd2007-08-07 00:25:56 +0000567
Devang Patelfee76bd2007-08-07 00:25:56 +0000568 // Replace split condition in header.
569 // Transform
570 // SplitCondition : icmp eq i32 IndVar, SplitValue
571 // into
572 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000573 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000574 // and i32 c1, c2
Devang Patelbacf5192007-08-10 00:33:50 +0000575 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelfee76bd2007-08-07 00:25:56 +0000576 Instruction *C1 = new ICmpInst(SignedPredicate ?
577 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel71554b82007-08-08 21:02:17 +0000578 SD.SplitValue, StartValue, "lisplit",
579 Terminator);
Devang Patelfee76bd2007-08-07 00:25:56 +0000580 Instruction *C2 = new ICmpInst(SignedPredicate ?
581 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelada054a2007-08-14 01:30:57 +0000582 SD.SplitValue, ExitValue, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000583 Terminator);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000584 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000585 Terminator);
586 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
587 SD.SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000588
Devang Patelfee76bd2007-08-07 00:25:56 +0000589 // Now, clear latch block. Remove instructions that are responsible
590 // to increment induction variable.
591 Instruction *LTerminator = Latch->getTerminator();
592 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
593 LB != LE; ) {
594 Instruction *I = LB;
595 ++LB;
596 if (isa<PHINode>(I) || I == LTerminator)
597 continue;
598
Devang Patel52abbf52008-05-19 22:23:55 +0000599 if (I == IndVarIncrement) {
600 // Replace induction variable increment if it is not used outside
601 // the loop.
602 bool UsedOutsideLoop = false;
603 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
604 UI != E; ++UI) {
605 if (Instruction *Use = dyn_cast<Instruction>(UI))
606 if (!L->contains(Use->getParent())) {
607 UsedOutsideLoop = true;
608 break;
609 }
610 }
611 if (!UsedOutsideLoop) {
612 I->replaceAllUsesWith(ExitValue);
613 I->eraseFromParent();
614 }
615 }
616 else {
Devang Patelada054a2007-08-14 01:30:57 +0000617 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel52abbf52008-05-19 22:23:55 +0000618 I->eraseFromParent();
619 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000620 }
621
Devang Patel423c8b22007-08-10 18:07:13 +0000622 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000623
624 // Update Dominator Info.
625 // Only CFG change done is to remove Latch to Header edge. This
626 // does not change dominator tree because Latch did not dominate
627 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000628 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000629 DominanceFrontier::iterator HeaderDF = DF->find(Header);
630 if (HeaderDF != DF->end())
631 DF->removeFromFrontier(HeaderDF, Header);
632
633 DominanceFrontier::iterator LatchDF = DF->find(Latch);
634 if (LatchDF != DF->end())
635 DF->removeFromFrontier(LatchDF, Header);
636 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000637 return true;
638}
639
640// If loop header includes loop variant instruction operands then
641// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patel71554b82007-08-08 21:02:17 +0000642bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000643
644 Instruction *Terminator = Header->getTerminator();
645 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
646 BI != BE; ++BI) {
647 Instruction *I = BI;
648
Devang Patelada054a2007-08-14 01:30:57 +0000649 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000650 if (isa<PHINode>(I))
651 continue;
652
653 // SplitCondition itself is OK.
Devang Patel71554b82007-08-08 21:02:17 +0000654 if (I == SD.SplitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000655 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000656
Devang Patelc9d123d2007-08-09 01:39:01 +0000657 // Induction variable is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000658 if (I == IndVar)
Devang Patelc9d123d2007-08-09 01:39:01 +0000659 continue;
660
661 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000662 if (I == IndVarIncrement)
Devang Patelc9d123d2007-08-09 01:39:01 +0000663 continue;
664
Devang Patelfee76bd2007-08-07 00:25:56 +0000665 // Terminator is also harmless.
666 if (I == Terminator)
667 continue;
668
669 // Otherwise we have a instruction that may not be safe.
670 return false;
671 }
672
673 return true;
674}
675
Devang Patel1cc2ec82007-08-20 23:51:18 +0000676// If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000677// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel1cc2ec82007-08-20 23:51:18 +0000678bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
679 BasicBlock *ExitingBlock) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000680
Devang Patel1cc2ec82007-08-20 23:51:18 +0000681 for (BasicBlock::iterator BI = ExitingBlock->begin(),
682 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000683 Instruction *I = BI;
684
Devang Patelada054a2007-08-14 01:30:57 +0000685 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000686 if (isa<PHINode>(I))
687 continue;
688
Devang Patelc9d123d2007-08-09 01:39:01 +0000689 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000690 if (IndVarIncrement && IndVarIncrement == I)
Devang Patelc9d123d2007-08-09 01:39:01 +0000691 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000692
Devang Patelc9d123d2007-08-09 01:39:01 +0000693 // Check if I is induction variable increment instruction.
Devang Patela6dff2f2007-09-25 18:24:48 +0000694 if (I->getOpcode() == Instruction::Add) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000695
696 Value *Op0 = I->getOperand(0);
697 Value *Op1 = I->getOperand(1);
Devang Patelfee76bd2007-08-07 00:25:56 +0000698 PHINode *PN = NULL;
699 ConstantInt *CI = NULL;
700
701 if ((PN = dyn_cast<PHINode>(Op0))) {
702 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000703 if (CI->isOne()) {
704 if (!IndVarIncrement && PN == IndVar)
705 IndVarIncrement = I;
706 // else this is another loop induction variable
707 continue;
708 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000709 } else
710 if ((PN = dyn_cast<PHINode>(Op1))) {
711 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000712 if (CI->isOne()) {
713 if (!IndVarIncrement && PN == IndVar)
714 IndVarIncrement = I;
715 // else this is another loop induction variable
716 continue;
717 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000718 }
Devang Patela6dff2f2007-09-25 18:24:48 +0000719 }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000720
Devang Patelfee76bd2007-08-07 00:25:56 +0000721 // I is an Exit condition if next instruction is block terminator.
722 // Exit condition is OK if it compares loop invariant exit value,
723 // which is checked below.
Devang Patel002fe252007-08-07 23:17:52 +0000724 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbacf5192007-08-10 00:33:50 +0000725 if (EC == ExitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000726 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000727 }
728
Devang Patel1cc2ec82007-08-20 23:51:18 +0000729 if (I == ExitingBlock->getTerminator())
Devang Patelbacf5192007-08-10 00:33:50 +0000730 continue;
731
Devang Patelfee76bd2007-08-07 00:25:56 +0000732 // Otherwise we have instruction that may not be safe.
733 return false;
734 }
735
Devang Patel1cc2ec82007-08-20 23:51:18 +0000736 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelfee76bd2007-08-07 00:25:56 +0000737 return true;
738}
739
Devang Patel5279d062007-09-17 20:39:48 +0000740void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
741
742 Value *V0 = CI->getOperand(0);
743 Value *V1 = CI->getOperand(1);
744 Value *NV = NULL;
745
746 SCEVHandle SH0 = SE->getSCEV(V0);
747
748 if (SH0->isLoopInvariant(L))
749 NV = V0;
750 else
751 NV = V1;
752
Devang Patel453a8442007-09-25 17:31:19 +0000753 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
754 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
755 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
756 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
757 ExitCondition->swapOperands();
758 if (ExitValueNum)
759 ExitValueNum = 0;
760 else
761 ExitValueNum = 1;
762 }
763
764 Value *NUB = NULL;
765 Value *NLB = NULL;
766 Value *UB = ExitCondition->getOperand(ExitValueNum);
767 const Type *Ty = NV->getType();
768 bool Sign = ExitCondition->isSignedPredicate();
769 BasicBlock *Preheader = L->getLoopPreheader();
770 Instruction *PHTerminator = Preheader->getTerminator();
771
772 assert (NV && "Unexpected value");
773
Devang Patel5279d062007-09-17 20:39:48 +0000774 switch (CI->getPredicate()) {
775 case ICmpInst::ICMP_ULE:
776 case ICmpInst::ICMP_SLE:
777 // for (i = LB; i < UB; ++i)
778 // if (i <= NV && ...)
779 // LOOP_BODY
780 //
781 // is transformed into
782 // NUB = min (NV+1, UB)
783 // for (i = LB; i < NUB ; ++i)
784 // LOOP_BODY
785 //
Devang Patel453a8442007-09-25 17:31:19 +0000786 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
787 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000788 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000789 "lsplit.add", PHTerminator);
790 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
791 A, UB,"lsplit,c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000792 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000793 }
794
Devang Patel5279d062007-09-17 20:39:48 +0000795 // for (i = LB; i <= UB; ++i)
796 // if (i <= NV && ...)
797 // LOOP_BODY
798 //
799 // is transformed into
800 // NUB = min (NV, UB)
801 // for (i = LB; i <= NUB ; ++i)
802 // LOOP_BODY
803 //
Devang Patel453a8442007-09-25 17:31:19 +0000804 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
805 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
806 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
807 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000808 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000809 }
Devang Patel5279d062007-09-17 20:39:48 +0000810 break;
811 case ICmpInst::ICMP_ULT:
812 case ICmpInst::ICMP_SLT:
813 // for (i = LB; i < UB; ++i)
814 // if (i < NV && ...)
815 // LOOP_BODY
816 //
817 // is transformed into
818 // NUB = min (NV, UB)
819 // for (i = LB; i < NUB ; ++i)
820 // LOOP_BODY
821 //
Devang Patel453a8442007-09-25 17:31:19 +0000822 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
823 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
824 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
825 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000826 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000827 }
Devang Patel5279d062007-09-17 20:39:48 +0000828
829 // for (i = LB; i <= UB; ++i)
830 // if (i < NV && ...)
831 // LOOP_BODY
832 //
833 // is transformed into
834 // NUB = min (NV -1 , UB)
835 // for (i = LB; i <= NUB ; ++i)
836 // LOOP_BODY
837 //
Devang Patel453a8442007-09-25 17:31:19 +0000838 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
839 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000840 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000841 "lsplit.add", PHTerminator);
842 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
843 S, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000844 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000845 }
Devang Patel5279d062007-09-17 20:39:48 +0000846 break;
847 case ICmpInst::ICMP_UGE:
848 case ICmpInst::ICMP_SGE:
849 // for (i = LB; i (< or <=) UB; ++i)
850 // if (i >= NV && ...)
851 // LOOP_BODY
852 //
853 // is transformed into
854 // NLB = max (NV, LB)
855 // for (i = NLB; i (< or <=) UB ; ++i)
856 // LOOP_BODY
857 //
Devang Patel453a8442007-09-25 17:31:19 +0000858 {
859 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
860 NV, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000861 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000862 }
Devang Patel5279d062007-09-17 20:39:48 +0000863 break;
864 case ICmpInst::ICMP_UGT:
865 case ICmpInst::ICMP_SGT:
866 // for (i = LB; i (< or <=) UB; ++i)
867 // if (i > NV && ...)
868 // LOOP_BODY
869 //
870 // is transformed into
871 // NLB = max (NV+1, LB)
872 // for (i = NLB; i (< or <=) UB ; ++i)
873 // LOOP_BODY
874 //
Devang Patel453a8442007-09-25 17:31:19 +0000875 {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000876 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000877 "lsplit.add", PHTerminator);
878 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
879 A, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000880 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000881 }
Devang Patel5279d062007-09-17 20:39:48 +0000882 break;
883 default:
884 assert ( 0 && "Unexpected split condition predicate");
885 }
Devang Patel453a8442007-09-25 17:31:19 +0000886
887 if (NLB) {
888 unsigned i = IndVar->getBasicBlockIndex(Preheader);
889 IndVar->setIncomingValue(i, NLB);
890 }
891
892 if (NUB) {
893 ExitCondition->setOperand(ExitValueNum, NUB);
894 }
Devang Patel5279d062007-09-17 20:39:48 +0000895}
896/// updateLoopIterationSpace - Current loop body is covered by an AND
897/// instruction whose operands compares induction variables with loop
898/// invariants. If possible, hoist this check outside the loop by
899/// updating appropriate start and end values for induction variable.
900bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
901 BasicBlock *Header = L->getHeader();
Devang Patel453a8442007-09-25 17:31:19 +0000902 BasicBlock *ExitingBlock = ExitCondition->getParent();
903 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
904
Devang Patel5279d062007-09-17 20:39:48 +0000905 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
906 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
907
908 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
909 || Op0->getPredicate() == ICmpInst::ICMP_NE
910 || Op0->getPredicate() == ICmpInst::ICMP_EQ
911 || Op0->getPredicate() == ICmpInst::ICMP_NE)
912 return false;
913
914 // Check if SplitCondition dominates entire loop body
915 // or not.
916
917 // If SplitCondition is not in loop header then this loop is not suitable
918 // for this transformation.
919 if (SD.SplitCondition->getParent() != Header)
920 return false;
921
922 // If loop header includes loop variant instruction operands then
923 // this loop may not be eliminated.
924 Instruction *Terminator = Header->getTerminator();
925 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
926 BI != BE; ++BI) {
927 Instruction *I = BI;
928
929 // PHI Nodes are OK.
930 if (isa<PHINode>(I))
931 continue;
932
933 // SplitCondition itself is OK.
934 if (I == SD.SplitCondition)
935 continue;
936 if (I == Op0 || I == Op1)
937 continue;
938
939 // Induction variable is OK.
940 if (I == IndVar)
941 continue;
942
943 // Induction variable increment is OK.
944 if (I == IndVarIncrement)
945 continue;
946
947 // Terminator is also harmless.
948 if (I == Terminator)
949 continue;
950
951 // Otherwise we have a instruction that may not be safe.
952 return false;
953 }
954
955 // If Exiting block includes loop variant instructions then this
956 // loop may not be eliminated.
957 if (!safeExitingBlock(SD, ExitCondition->getParent()))
958 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000959
960 // Verify that loop exiting block has only two predecessor, where one predecessor
961 // is split condition block. The other predecessor will become exiting block's
962 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
963 // more then two predecessors. This requires extra work in updating dominator
964 // information.
965 BasicBlock *ExitingBBPred = NULL;
966 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
967 PI != PE; ++PI) {
968 BasicBlock *BB = *PI;
969 if (SplitCondBlock == BB)
970 continue;
971 if (ExitingBBPred)
972 return false;
973 else
974 ExitingBBPred = BB;
975 }
976
977 // Update loop bounds to absorb Op0 check.
Devang Patel5279d062007-09-17 20:39:48 +0000978 updateLoopBounds(Op0);
Devang Patel453a8442007-09-25 17:31:19 +0000979 // Update loop bounds to absorb Op1 check.
Devang Patel5279d062007-09-17 20:39:48 +0000980 updateLoopBounds(Op1);
Devang Patel453a8442007-09-25 17:31:19 +0000981
Devang Patel5279d062007-09-17 20:39:48 +0000982 // Update CFG
Devang Patel453a8442007-09-25 17:31:19 +0000983
984 // Unconditionally connect split block to its remaining successor.
985 BranchInst *SplitTerminator =
986 cast<BranchInst>(SplitCondBlock->getTerminator());
987 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
988 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
989 if (Succ0 == ExitCondition->getParent())
990 SplitTerminator->setUnconditionalDest(Succ1);
991 else
992 SplitTerminator->setUnconditionalDest(Succ0);
993
994 // Remove split condition.
995 SD.SplitCondition->eraseFromParent();
996 if (Op0->use_begin() == Op0->use_end())
997 Op0->eraseFromParent();
998 if (Op1->use_begin() == Op1->use_end())
999 Op1->eraseFromParent();
1000
1001 BranchInst *ExitInsn =
1002 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1003 assert (ExitInsn && "Unable to find suitable loop exit branch");
1004 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1005 if (L->contains(ExitBlock))
1006 ExitBlock = ExitInsn->getSuccessor(0);
1007
1008 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1009 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1010 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1011
1012 // If ExitingBlock is a member of loop BB's DF list then replace it with
1013 // loop header and exit block.
1014 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1015 I != E; ++I) {
1016 BasicBlock *BB = *I;
1017 if (BB == Header || BB == ExitingBlock)
1018 continue;
1019 DominanceFrontier::iterator BBDF = DF->find(BB);
1020 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1021 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1022 while (DomSetI != DomSetE) {
1023 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1024 ++DomSetI;
1025 BasicBlock *DFBB = *CurrentItr;
1026 if (DFBB == ExitingBlock) {
1027 BBDF->second.erase(DFBB);
1028 BBDF->second.insert(Header);
1029 if (Header != ExitingBlock)
1030 BBDF->second.insert(ExitBlock);
1031 }
1032 }
1033 }
1034
Devang Patel1c013502007-09-25 17:43:08 +00001035 return true;
Devang Patel5279d062007-09-17 20:39:48 +00001036}
1037
1038
Devang Patela6a86632007-08-14 18:35:57 +00001039/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1040/// This routine is used to remove split condition's dead branch, dominated by
1041/// DeadBB. LiveBB dominates split conidition's other branch.
1042void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1043 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +00001044
Devang Patel5b8ec612007-08-15 03:31:47 +00001045 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +00001046 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +00001047 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1048 if (DeadBBDF != DF->end()) {
1049 SmallVector<BasicBlock *, 8> PredBlocks;
1050
1051 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1052 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1053 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1054 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +00001055 FrontierBBs.push_back(FrontierBB);
1056
Devang Patel5b8ec612007-08-15 03:31:47 +00001057 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1058 PredBlocks.clear();
1059 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1060 PI != PE; ++PI) {
1061 BasicBlock *P = *PI;
1062 if (P == DeadBB || DT->dominates(DeadBB, P))
1063 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001064 }
Devang Patel96bf5242007-08-17 21:59:16 +00001065
Devang Patel5b8ec612007-08-15 03:31:47 +00001066 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1067 FBI != FBE; ++FBI) {
1068 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1069 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1070 PE = PredBlocks.end(); PI != PE; ++PI) {
1071 BasicBlock *P = *PI;
1072 PN->removeIncomingValue(P);
1073 }
1074 }
1075 else
1076 break;
Devang Patel96bf5242007-08-17 21:59:16 +00001077 }
Devang Patel98147a32007-08-12 07:02:51 +00001078 }
Devang Patel98147a32007-08-12 07:02:51 +00001079 }
Devang Patel5b8ec612007-08-15 03:31:47 +00001080
1081 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1082 SmallVector<BasicBlock *, 32> WorkList;
1083 DomTreeNode *DN = DT->getNode(DeadBB);
1084 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1085 E = df_end(DN); DI != E; ++DI) {
1086 BasicBlock *BB = DI->getBlock();
1087 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +00001088 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +00001089 }
1090
1091 while (!WorkList.empty()) {
1092 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1093 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +00001094 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +00001095 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +00001096 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +00001097 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1098 I->eraseFromParent();
1099 }
1100 LPM->deleteSimpleAnalysisValue(BB, LP);
1101 DT->eraseNode(BB);
1102 DF->removeBlock(BB);
1103 LI->removeBlock(BB);
1104 BB->eraseFromParent();
1105 }
Devang Patel96bf5242007-08-17 21:59:16 +00001106
1107 // Update Frontier BBs' dominator info.
1108 while (!FrontierBBs.empty()) {
1109 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1110 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1111 if (!NewDominator) {
1112 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1113 NewDominator = *PI;
1114 ++PI;
1115 if (NewDominator != LiveBB) {
1116 for(; PI != PE; ++PI) {
1117 BasicBlock *P = *PI;
1118 if (P == LiveBB) {
1119 NewDominator = LiveBB;
1120 break;
1121 }
1122 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1123 }
1124 }
1125 }
1126 assert (NewDominator && "Unable to fix dominator info.");
1127 DT->changeImmediateDominator(FBB, NewDominator);
1128 DF->changeImmediateDominator(FBB, NewDominator, DT);
1129 }
1130
Devang Patel98147a32007-08-12 07:02:51 +00001131}
1132
Devang Pateldc523952007-08-22 18:27:01 +00001133/// safeSplitCondition - Return true if it is possible to
1134/// split loop using given split condition.
1135bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patel23a19f82007-08-10 00:53:35 +00001136
Devang Pateldc523952007-08-22 18:27:01 +00001137 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel8893ca62007-09-17 21:01:05 +00001138 BasicBlock *Latch = L->getLoopLatch();
Devang Pateldc523952007-08-22 18:27:01 +00001139 BranchInst *SplitTerminator =
1140 cast<BranchInst>(SplitCondBlock->getTerminator());
1141 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1142 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel20d260a2007-08-18 00:00:32 +00001143
Bill Wendling643310d2008-05-02 00:43:20 +00001144 // If split block does not dominate the latch then this is not a diamond.
1145 // Such loop may not benefit from index split.
1146 if (!DT->dominates(SplitCondBlock, Latch))
1147 return false;
1148
Devang Patelb88e4202007-08-24 05:36:56 +00001149 // Finally this split condition is safe only if merge point for
1150 // split condition branch is loop latch. This check along with previous
1151 // check, to ensure that exit condition is in either loop latch or header,
1152 // filters all loops with non-empty loop body between merge point
1153 // and exit condition.
1154 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1155 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1156 if (Succ0DF->second.count(Latch))
1157 return true;
1158
1159 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1160 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1161 if (Succ1DF->second.count(Latch))
1162 return true;
1163
1164 return false;
Devang Pateldc523952007-08-22 18:27:01 +00001165}
1166
Devang Patel4a69da92007-08-25 00:56:38 +00001167/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1168/// based on split value.
1169void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1170
Devang Patel4f12c5f2007-09-11 00:12:56 +00001171 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1172 ICmpInst::Predicate SP = SC->getPredicate();
Devang Patel4a69da92007-08-25 00:56:38 +00001173 const Type *Ty = SD.SplitValue->getType();
1174 bool Sign = ExitCondition->isSignedPredicate();
1175 BasicBlock *Preheader = L->getLoopPreheader();
1176 Instruction *PHTerminator = Preheader->getTerminator();
1177
1178 // Initially use split value as upper loop bound for first loop and lower loop
1179 // bound for second loop.
1180 Value *AEV = SD.SplitValue;
1181 Value *BSV = SD.SplitValue;
1182
Devang Patelbabbe272007-09-19 00:28:47 +00001183 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1184 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1185 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel02c48362008-02-13 19:48:48 +00001186 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
Devang Patelbabbe272007-09-19 00:28:47 +00001187 ExitCondition->swapOperands();
Devang Patel02c48362008-02-13 19:48:48 +00001188 if (ExitValueNum)
1189 ExitValueNum = 0;
1190 else
1191 ExitValueNum = 1;
1192 }
Devang Patelbabbe272007-09-19 00:28:47 +00001193
Devang Patel4a69da92007-08-25 00:56:38 +00001194 switch (ExitCondition->getPredicate()) {
1195 case ICmpInst::ICMP_SGT:
1196 case ICmpInst::ICMP_UGT:
1197 case ICmpInst::ICMP_SGE:
1198 case ICmpInst::ICMP_UGE:
1199 default:
1200 assert (0 && "Unexpected exit condition predicate");
1201
1202 case ICmpInst::ICMP_SLT:
1203 case ICmpInst::ICMP_ULT:
1204 {
1205 switch (SP) {
1206 case ICmpInst::ICMP_SLT:
1207 case ICmpInst::ICMP_ULT:
1208 //
1209 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1210 //
1211 // is transformed into
1212 // AEV = BSV = SV
1213 // for (i = LB; i < min(UB, AEV); ++i)
1214 // A;
1215 // for (i = max(LB, BSV); i < UB; ++i);
1216 // B;
1217 break;
1218 case ICmpInst::ICMP_SLE:
1219 case ICmpInst::ICMP_ULE:
1220 {
1221 //
1222 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1223 //
1224 // is transformed into
1225 //
1226 // AEV = SV + 1
1227 // BSV = SV + 1
1228 // for (i = LB; i < min(UB, AEV); ++i)
1229 // A;
1230 // for (i = max(LB, BSV); i < UB; ++i)
1231 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001232 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001233 ConstantInt::get(Ty, 1, Sign),
1234 "lsplit.add", PHTerminator);
1235 AEV = BSV;
1236 }
1237 break;
1238 case ICmpInst::ICMP_SGE:
1239 case ICmpInst::ICMP_UGE:
1240 //
1241 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1242 //
1243 // is transformed into
1244 // AEV = BSV = SV
1245 // for (i = LB; i < min(UB, AEV); ++i)
1246 // B;
1247 // for (i = max(BSV, LB); i < UB; ++i)
1248 // A;
1249 break;
1250 case ICmpInst::ICMP_SGT:
1251 case ICmpInst::ICMP_UGT:
1252 {
1253 //
1254 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1255 //
1256 // is transformed into
1257 //
1258 // BSV = AEV = SV + 1
1259 // for (i = LB; i < min(UB, AEV); ++i)
1260 // B;
1261 // for (i = max(LB, BSV); i < UB; ++i)
1262 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001263 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001264 ConstantInt::get(Ty, 1, Sign),
1265 "lsplit.add", PHTerminator);
1266 AEV = BSV;
1267 }
1268 break;
1269 default:
1270 assert (0 && "Unexpected split condition predicate");
1271 break;
1272 } // end switch (SP)
1273 }
1274 break;
1275 case ICmpInst::ICMP_SLE:
1276 case ICmpInst::ICMP_ULE:
1277 {
1278 switch (SP) {
1279 case ICmpInst::ICMP_SLT:
1280 case ICmpInst::ICMP_ULT:
1281 //
1282 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1283 //
1284 // is transformed into
1285 // AEV = SV - 1;
1286 // BSV = SV;
1287 // for (i = LB; i <= min(UB, AEV); ++i)
1288 // A;
1289 // for (i = max(LB, BSV); i <= UB; ++i)
1290 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001291 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001292 ConstantInt::get(Ty, 1, Sign),
1293 "lsplit.sub", PHTerminator);
1294 break;
1295 case ICmpInst::ICMP_SLE:
1296 case ICmpInst::ICMP_ULE:
1297 //
1298 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1299 //
1300 // is transformed into
1301 // AEV = SV;
1302 // BSV = SV + 1;
1303 // for (i = LB; i <= min(UB, AEV); ++i)
1304 // A;
1305 // for (i = max(LB, BSV); i <= UB; ++i)
1306 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001307 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001308 ConstantInt::get(Ty, 1, Sign),
1309 "lsplit.add", PHTerminator);
1310 break;
1311 case ICmpInst::ICMP_SGT:
1312 case ICmpInst::ICMP_UGT:
1313 //
1314 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1315 //
1316 // is transformed into
1317 // AEV = SV;
1318 // BSV = SV + 1;
1319 // for (i = LB; i <= min(AEV, UB); ++i)
1320 // B;
1321 // for (i = max(LB, BSV); i <= UB; ++i)
1322 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001323 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001324 ConstantInt::get(Ty, 1, Sign),
1325 "lsplit.add", PHTerminator);
1326 break;
1327 case ICmpInst::ICMP_SGE:
1328 case ICmpInst::ICMP_UGE:
1329 // ** TODO **
1330 //
1331 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1332 //
1333 // is transformed into
1334 // AEV = SV - 1;
1335 // BSV = SV;
1336 // for (i = LB; i <= min(AEV, UB); ++i)
1337 // B;
1338 // for (i = max(LB, BSV); i <= UB; ++i)
1339 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001340 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001341 ConstantInt::get(Ty, 1, Sign),
1342 "lsplit.sub", PHTerminator);
1343 break;
1344 default:
1345 assert (0 && "Unexpected split condition predicate");
1346 break;
1347 } // end switch (SP)
1348 }
1349 break;
1350 }
1351
1352 // Calculate ALoop induction variable's new exiting value and
1353 // BLoop induction variable's new starting value. Calculuate these
1354 // values in original loop's preheader.
1355 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1356 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel3f65f022007-09-21 21:18:19 +00001357 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Patel5ffdc562007-12-03 19:17:21 +00001358
1359 // If ExitValue operand is also defined in Loop header then
1360 // insert new ExitValue after this operand definition.
1361 if (Instruction *EVN =
1362 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1363 if (!isa<PHINode>(EVN))
1364 if (InsertPt->getParent() == EVN->getParent()) {
1365 BasicBlock::iterator LHBI = L->getHeader()->begin();
1366 BasicBlock::iterator LHBE = L->getHeader()->end();
1367 for(;LHBI != LHBE; ++LHBI) {
1368 Instruction *I = LHBI;
1369 if (I == EVN)
1370 break;
1371 }
1372 InsertPt = ++LHBI;
1373 }
1374 }
Devang Patel4a69da92007-08-25 00:56:38 +00001375 Value *C1 = new ICmpInst(Sign ?
1376 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1377 AEV,
1378 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001379 "lsplit.ev", InsertPt);
1380
Gabor Greif051a9502008-04-06 20:25:17 +00001381 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1382 ExitCondition->getOperand(ExitValueNum),
1383 "lsplit.ev", InsertPt);
Devang Patel3f65f022007-09-21 21:18:19 +00001384
Devang Patel4a69da92007-08-25 00:56:38 +00001385 Value *C2 = new ICmpInst(Sign ?
1386 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1387 BSV, StartValue, "lsplit.sv",
1388 PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +00001389 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1390 "lsplit.sv", PHTerminator);
Devang Patel4a69da92007-08-25 00:56:38 +00001391}
1392
Devang Pateldc523952007-08-22 18:27:01 +00001393/// splitLoop - Split current loop L in two loops using split information
1394/// SD. Update dominator information. Maintain LCSSA form.
1395bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1396
1397 if (!safeSplitCondition(SD))
1398 return false;
1399
Devang Patel8893ca62007-09-17 21:01:05 +00001400 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1401
1402 // Unable to handle triange loops at the moment.
1403 // In triangle loop, split condition is in header and one of the
1404 // the split destination is loop latch. If split condition is EQ
1405 // then such loops are already handle in processOneIterationLoop().
1406 BasicBlock *Latch = L->getLoopLatch();
1407 BranchInst *SplitTerminator =
1408 cast<BranchInst>(SplitCondBlock->getTerminator());
1409 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1410 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1411 if (L->getHeader() == SplitCondBlock
1412 && (Latch == Succ0 || Latch == Succ1))
1413 return false;
1414
1415 // If split condition branches heads do not have single predecessor,
1416 // SplitCondBlock, then is not possible to remove inactive branch.
1417 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1418 return false;
1419
Devang Patel82ada542008-02-08 22:49:13 +00001420 // If Exiting block includes loop variant instructions then this
1421 // loop may not be split safely.
1422 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1423 return false;
1424
Devang Patela8644e32007-08-22 19:33:29 +00001425 // After loop is cloned there are two loops.
1426 //
1427 // First loop, referred as ALoop, executes first part of loop's iteration
1428 // space split. Second loop, referred as BLoop, executes remaining
1429 // part of loop's iteration space.
1430 //
1431 // ALoop's exit edge enters BLoop's header through a forwarding block which
1432 // acts as a BLoop's preheader.
Devang Patel4a69da92007-08-25 00:56:38 +00001433 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateldc523952007-08-22 18:27:01 +00001434
Devang Patel4a69da92007-08-25 00:56:38 +00001435 // Calculate ALoop induction variable's new exiting value and
1436 // BLoop induction variable's new starting value.
1437 calculateLoopBounds(SD);
Devang Patel423c8b22007-08-10 18:07:13 +00001438
Devang Patela8644e32007-08-22 19:33:29 +00001439 //[*] Clone loop.
Devang Patel98147a32007-08-12 07:02:51 +00001440 DenseMap<const Value *, Value *> ValueMap;
Devang Patela8644e32007-08-22 19:33:29 +00001441 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Pateld79faee2007-08-25 02:39:24 +00001442 Loop *ALoop = L;
Devang Patela8644e32007-08-22 19:33:29 +00001443 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel98147a32007-08-12 07:02:51 +00001444
Devang Patela8644e32007-08-22 19:33:29 +00001445 //[*] ALoop's exiting edge BLoop's header.
1446 // ALoop's original exit block becomes BLoop's exit block.
1447 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1448 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1449 BranchInst *A_ExitInsn =
1450 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1451 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1452 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1453 if (L->contains(B_ExitBlock)) {
1454 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1455 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patelada054a2007-08-14 01:30:57 +00001456 } else
Devang Patela8644e32007-08-22 19:33:29 +00001457 A_ExitInsn->setSuccessor(1, B_Header);
1458
1459 //[*] Update ALoop's exit value using new exit value.
Devang Patel4a69da92007-08-25 00:56:38 +00001460 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001461
Devang Patela8644e32007-08-22 19:33:29 +00001462 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1463 // original loop's preheader. Add incoming PHINode values from
1464 // ALoop's exiting block. Update BLoop header's domiantor info.
1465
Devang Patelada054a2007-08-14 01:30:57 +00001466 // Collect inverse map of Header PHINodes.
1467 DenseMap<Value *, Value *> InverseMap;
1468 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1469 BE = L->getHeader()->end(); BI != BE; ++BI) {
1470 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1471 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1472 InverseMap[PNClone] = PN;
1473 } else
1474 break;
1475 }
Devang Patel4a69da92007-08-25 00:56:38 +00001476
Devang Patela8644e32007-08-22 19:33:29 +00001477 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel98147a32007-08-12 07:02:51 +00001478 BI != BE; ++BI) {
1479 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001480 // Remove incoming value from original preheader.
1481 PN->removeIncomingValue(Preheader);
1482
1483 // Add incoming value from A_ExitingBlock.
1484 if (PN == B_IndVar)
Devang Patel4a69da92007-08-25 00:56:38 +00001485 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001486 else {
1487 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patel9b03daa2008-02-14 23:18:47 +00001488 Value *V2 = NULL;
1489 // If loop header is also loop exiting block then
1490 // OrigPN is incoming value for B loop header.
1491 if (A_ExitingBlock == L->getHeader())
1492 V2 = OrigPN;
1493 else
1494 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
Devang Patela8644e32007-08-22 19:33:29 +00001495 PN->addIncoming(V2, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001496 }
1497 } else
Devang Patel98147a32007-08-12 07:02:51 +00001498 break;
1499 }
Devang Patela8644e32007-08-22 19:33:29 +00001500 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1501 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001502
Devang Patela8644e32007-08-22 19:33:29 +00001503 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1504 // block. Remove incoming PHINode values from ALoop's exiting block.
1505 // Add new incoming values from BLoop's incoming exiting value.
1506 // Update BLoop exit block's dominator info..
1507 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1508 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patelada054a2007-08-14 01:30:57 +00001509 BI != BE; ++BI) {
1510 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001511 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1512 B_ExitingBlock);
1513 PN->removeIncomingValue(A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001514 } else
1515 break;
1516 }
Devang Patel98147a32007-08-12 07:02:51 +00001517
Devang Patela8644e32007-08-22 19:33:29 +00001518 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1519 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001520
Devang Patela8644e32007-08-22 19:33:29 +00001521 //[*] Split ALoop's exit edge. This creates a new block which
1522 // serves two purposes. First one is to hold PHINode defnitions
1523 // to ensure that ALoop's LCSSA form. Second use it to act
1524 // as a preheader for BLoop.
1525 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel423c8b22007-08-10 18:07:13 +00001526
Devang Patela8644e32007-08-22 19:33:29 +00001527 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1528 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1529 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel60cbab42007-08-21 19:47:46 +00001530 BI != BE; ++BI) {
1531 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001532 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001533 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
Devang Patela8644e32007-08-22 19:33:29 +00001534 newPHI->addIncoming(V1, A_ExitingBlock);
1535 A_ExitBlock->getInstList().push_front(newPHI);
1536 PN->removeIncomingValue(A_ExitBlock);
1537 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001538 } else
1539 break;
1540 }
1541
Devang Patela8644e32007-08-22 19:33:29 +00001542 //[*] Eliminate split condition's inactive branch from ALoop.
1543 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1544 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001545 BasicBlock *A_InactiveBranch = NULL;
1546 BasicBlock *A_ActiveBranch = NULL;
1547 if (SD.UseTrueBranchFirst) {
1548 A_ActiveBranch = A_BR->getSuccessor(0);
1549 A_InactiveBranch = A_BR->getSuccessor(1);
1550 } else {
1551 A_ActiveBranch = A_BR->getSuccessor(1);
1552 A_InactiveBranch = A_BR->getSuccessor(0);
1553 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001554 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001555 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1556
1557 //[*] Eliminate split condition's inactive branch in from BLoop.
1558 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1559 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001560 BasicBlock *B_InactiveBranch = NULL;
1561 BasicBlock *B_ActiveBranch = NULL;
1562 if (SD.UseTrueBranchFirst) {
1563 B_ActiveBranch = B_BR->getSuccessor(1);
1564 B_InactiveBranch = B_BR->getSuccessor(0);
1565 } else {
1566 B_ActiveBranch = B_BR->getSuccessor(0);
1567 B_InactiveBranch = B_BR->getSuccessor(1);
1568 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001569 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001570 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1571
Devang Pateld79faee2007-08-25 02:39:24 +00001572 BasicBlock *A_Header = L->getHeader();
1573 if (A_ExitingBlock == A_Header)
1574 return true;
1575
1576 //[*] Move exit condition into split condition block to avoid
1577 // executing dead loop iteration.
1578 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1579 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1580 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1581
1582 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel4f12c5f2007-09-11 00:12:56 +00001583 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1584 ALoop);
Devang Pateld79faee2007-08-25 02:39:24 +00001585
1586 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1587 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1588
Devang Patel98147a32007-08-12 07:02:51 +00001589 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +00001590}
Devang Pateld79faee2007-08-25 02:39:24 +00001591
1592// moveExitCondition - Move exit condition EC into split condition block CondBB.
1593void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1594 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1595 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1596
1597 BasicBlock *ExitingBB = EC->getParent();
1598 Instruction *CurrentBR = CondBB->getTerminator();
1599
1600 // Move exit condition into split condition block.
1601 EC->moveBefore(CurrentBR);
1602 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1603
1604 // Move exiting block's branch into split condition block. Update its branch
1605 // destination.
1606 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1607 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +00001608 BasicBlock *OrigDestBB = NULL;
1609 if (ExitingBR->getSuccessor(0) == ExitBB) {
1610 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +00001611 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001612 }
1613 else {
1614 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +00001615 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001616 }
Devang Pateld79faee2007-08-25 02:39:24 +00001617
1618 // Remove split condition and current split condition branch.
1619 SC->eraseFromParent();
1620 CurrentBR->eraseFromParent();
1621
Devang Patel23067df2008-02-13 22:06:36 +00001622 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +00001623 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +00001624
1625 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +00001626 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +00001627
1628 // Fix dominator info.
1629 // ExitBB is now dominated by CondBB
1630 DT->changeImmediateDominator(ExitBB, CondBB);
1631 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1632
1633 // Basicblocks dominated by ActiveBB may have ExitingBB or
1634 // a basic block outside the loop in their DF list. If so,
1635 // replace it with CondBB.
1636 DomTreeNode *Node = DT->getNode(ActiveBB);
1637 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1638 DI != DE; ++DI) {
1639 BasicBlock *BB = DI->getBlock();
1640 DominanceFrontier::iterator BBDF = DF->find(BB);
1641 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1642 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1643 while (DomSetI != DomSetE) {
1644 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1645 ++DomSetI;
1646 BasicBlock *DFBB = *CurrentItr;
1647 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1648 BBDF->second.erase(DFBB);
1649 BBDF->second.insert(CondBB);
1650 }
1651 }
1652 }
1653}
1654
1655/// updatePHINodes - CFG has been changed.
1656/// Before
1657/// - ExitBB's single predecessor was Latch
1658/// - Latch's second successor was Header
1659/// Now
Devang Patel82ada542008-02-08 22:49:13 +00001660/// - ExitBB's single predecessor is Header
1661/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +00001662///
1663/// Update ExitBB PHINodes' to reflect this change.
1664void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1665 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +00001666 PHINode *IV, Instruction *IVIncrement,
1667 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +00001668
1669 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001670 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +00001671 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001672 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +00001673 if (!PN)
1674 break;
1675
1676 Value *V = PN->getIncomingValueForBlock(Latch);
1677 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +00001678 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1679 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +00001680 Value *NewV = NULL;
1681 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +00001682 UI != E; ++UI)
1683 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +00001684 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +00001685 NewV = U;
1686 break;
1687 }
1688
Devang Patel60a12902008-03-24 20:16:14 +00001689 // Add incoming value from header only if PN has any use inside the loop.
1690 if (NewV)
1691 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +00001692
1693 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1694 // If this instruction is IVIncrement then IV is new incoming value
1695 // from header otherwise this instruction must be incoming value from
1696 // header because loop is in LCSSA form.
1697 if (PHI == IVIncrement)
1698 PN->addIncoming(IV, Header);
1699 else
1700 PN->addIncoming(V, Header);
1701 } else
1702 // Otherwise this is an incoming value from header because loop is in
1703 // LCSSA form.
1704 PN->addIncoming(V, Header);
1705
1706 // Remove incoming value from Latch.
1707 PN->removeIncomingValue(Latch);
1708 }
1709}