blob: 135ce33ee6f4918c9487ee12ede6f1f7f44047fb [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 Patela5e27f82008-07-09 00:12:01 +0000387
388 // If start value is more then exit value where induction variable
389 // increments by 1 then we are potentially dealing with an infinite loop.
390 // Do not index split this loop.
391 if (ExitCondition) {
392 ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
393 ConstantInt *EV =
394 dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
395 if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
396 ExitCondition = NULL;
397 else if (EV && EV->isZero())
398 ExitCondition = NULL;
399 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000400}
401
Devang Patelfee76bd2007-08-07 00:25:56 +0000402/// Find condition inside a loop that is suitable candidate for index split.
403void LoopIndexSplit::findSplitCondition() {
404
Devang Patel71554b82007-08-08 21:02:17 +0000405 SplitInfo SD;
Devang Patelc9d123d2007-08-09 01:39:01 +0000406 // Check all basic block's terminators.
Devang Patelc9d123d2007-08-09 01:39:01 +0000407 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
408 I != E; ++I) {
Devang Patel964be452007-09-11 00:23:56 +0000409 SD.clear();
Devang Patelc9d123d2007-08-09 01:39:01 +0000410 BasicBlock *BB = *I;
Devang Patelfee76bd2007-08-07 00:25:56 +0000411
Devang Patelc9d123d2007-08-09 01:39:01 +0000412 // If this basic block does not terminate in a conditional branch
413 // then terminator is not a suitable split condition.
414 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
415 if (!BR)
416 continue;
417
418 if (BR->isUnconditional())
Devang Patelfee76bd2007-08-07 00:25:56 +0000419 continue;
420
Devang Patel5279d062007-09-17 20:39:48 +0000421 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
422 if (AndI->getOpcode() == Instruction::And) {
423 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
424 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
425
426 if (!Op0 || !Op1)
427 continue;
428
429 if (!safeICmpInst(Op0, SD))
430 continue;
431 SD.clear();
432 if (!safeICmpInst(Op1, SD))
433 continue;
434 SD.clear();
435 SD.SplitCondition = AndI;
436 SplitData.push_back(SD);
437 continue;
438 }
439 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000440 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patelbacf5192007-08-10 00:33:50 +0000441 if (!CI || CI == ExitCondition)
Devang Patelba32a5f2007-09-10 23:57:58 +0000442 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000443
Devang Patelc830aee2007-08-24 06:02:25 +0000444 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patelba32a5f2007-09-10 23:57:58 +0000445 continue;
Devang Patelc830aee2007-08-24 06:02:25 +0000446
Devang Patel4259fe32007-08-24 06:17:19 +0000447 // If split condition predicate is GT or GE then first execute
448 // false branch of split condition.
Devang Patelc3957d12007-09-11 01:10:45 +0000449 if (CI->getPredicate() == ICmpInst::ICMP_UGT
450 || CI->getPredicate() == ICmpInst::ICMP_SGT
451 || CI->getPredicate() == ICmpInst::ICMP_UGE
452 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel4259fe32007-08-24 06:17:19 +0000453 SD.UseTrueBranchFirst = false;
454
Devang Patelc9d123d2007-08-09 01:39:01 +0000455 // If one operand is loop invariant and second operand is SCEVAddRecExpr
456 // based on induction variable then CI is a candidate split condition.
Devang Pateld35ed2c2007-09-11 00:42:56 +0000457 if (safeICmpInst(CI, SD))
458 SplitData.push_back(SD);
459 }
460}
Devang Patelc9d123d2007-08-09 01:39:01 +0000461
Devang Pateld35ed2c2007-09-11 00:42:56 +0000462// safeIcmpInst - CI is considered safe instruction if one of the operand
463// is SCEVAddRecExpr based on induction variable and other operand is
464// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
465// and return true;
466bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000467
Devang Pateld35ed2c2007-09-11 00:42:56 +0000468 Value *V0 = CI->getOperand(0);
469 Value *V1 = CI->getOperand(1);
470
471 SCEVHandle SH0 = SE->getSCEV(V0);
472 SCEVHandle SH1 = SE->getSCEV(V1);
473
474 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
475 SD.SplitValue = V0;
476 SD.SplitCondition = CI;
477 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
478 if (PN == IndVar)
479 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000480 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000481 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
482 if (IndVarIncrement && IndVarIncrement == Insn)
483 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000484 }
485 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000486 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
487 SD.SplitValue = V1;
488 SD.SplitCondition = CI;
489 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
490 if (PN == IndVar)
491 return true;
492 }
493 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
494 if (IndVarIncrement && IndVarIncrement == Insn)
495 return true;
496 }
497 }
498
499 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000500}
501
502/// processOneIterationLoop - Current loop L contains compare instruction
503/// that compares induction variable, IndVar, against loop invariant. If
504/// entire (i.e. meaningful) loop body is dominated by this compare
505/// instruction then loop body is executed only once. In such case eliminate
506/// loop structure surrounding this loop body. For example,
507/// for (int i = start; i < end; ++i) {
508/// if ( i == somevalue) {
509/// loop_body
510/// }
511/// }
512/// can be transformed into
513/// if (somevalue >= start && somevalue < end) {
514/// i = somevalue;
515/// loop_body
516/// }
Devang Patel423c8b22007-08-10 18:07:13 +0000517bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000518
519 BasicBlock *Header = L->getHeader();
520
521 // First of all, check if SplitCondition dominates entire loop body
522 // or not.
523
524 // If SplitCondition is not in loop header then this loop is not suitable
525 // for this transformation.
Devang Patel71554b82007-08-08 21:02:17 +0000526 if (SD.SplitCondition->getParent() != Header)
Devang Patelfee76bd2007-08-07 00:25:56 +0000527 return false;
528
Devang Patelfee76bd2007-08-07 00:25:56 +0000529 // If loop header includes loop variant instruction operands then
530 // this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000531 if (!safeHeader(SD, Header))
Devang Patelfee76bd2007-08-07 00:25:56 +0000532 return false;
533
Devang Patel1cc2ec82007-08-20 23:51:18 +0000534 // If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000535 // loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000536 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelfee76bd2007-08-07 00:25:56 +0000537 return false;
538
Devang Patel968eee22007-09-19 00:15:16 +0000539 // Filter loops where split condition's false branch is not empty.
540 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
541 return false;
542
Devang Patel8893ca62007-09-17 21:01:05 +0000543 // If split condition is not safe then do not process this loop.
544 // For example,
545 // for(int i = 0; i < N; i++) {
546 // if ( i == XYZ) {
547 // A;
548 // else
549 // B;
550 // }
551 // C;
552 // D;
553 // }
554 if (!safeSplitCondition(SD))
555 return false;
556
Devang Patel84ef08b2007-09-19 00:11:01 +0000557 BasicBlock *Latch = L->getLoopLatch();
558 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
559 if (!BR)
560 return false;
561
Devang Patel6a2bfda2007-08-08 01:51:27 +0000562 // Update CFG.
563
Devang Patelebc5fea2007-08-20 20:49:01 +0000564 // Replace index variable with split value in loop body. Loop body is executed
565 // only when index variable is equal to split value.
566 IndVar->replaceAllUsesWith(SD.SplitValue);
567
568 // Remove Latch to Header edge.
Devang Patel6a2bfda2007-08-08 01:51:27 +0000569 BasicBlock *LatchSucc = NULL;
Devang Patel6a2bfda2007-08-08 01:51:27 +0000570 Header->removePredecessor(Latch);
571 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
572 SI != E; ++SI) {
573 if (Header != *SI)
574 LatchSucc = *SI;
575 }
576 BR->setUnconditionalDest(LatchSucc);
577
Devang Patelfee76bd2007-08-07 00:25:56 +0000578 Instruction *Terminator = Header->getTerminator();
Devang Patelada054a2007-08-14 01:30:57 +0000579 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelfee76bd2007-08-07 00:25:56 +0000580
Devang Patelfee76bd2007-08-07 00:25:56 +0000581 // Replace split condition in header.
582 // Transform
583 // SplitCondition : icmp eq i32 IndVar, SplitValue
584 // into
585 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000586 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000587 // and i32 c1, c2
Devang Patelbacf5192007-08-10 00:33:50 +0000588 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelfee76bd2007-08-07 00:25:56 +0000589 Instruction *C1 = new ICmpInst(SignedPredicate ?
590 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel71554b82007-08-08 21:02:17 +0000591 SD.SplitValue, StartValue, "lisplit",
592 Terminator);
Devang Patelfee76bd2007-08-07 00:25:56 +0000593 Instruction *C2 = new ICmpInst(SignedPredicate ?
594 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelada054a2007-08-14 01:30:57 +0000595 SD.SplitValue, ExitValue, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000596 Terminator);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000597 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000598 Terminator);
599 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
600 SD.SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000601
Devang Patelfee76bd2007-08-07 00:25:56 +0000602 // Now, clear latch block. Remove instructions that are responsible
603 // to increment induction variable.
604 Instruction *LTerminator = Latch->getTerminator();
605 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
606 LB != LE; ) {
607 Instruction *I = LB;
608 ++LB;
609 if (isa<PHINode>(I) || I == LTerminator)
610 continue;
611
Devang Patel52abbf52008-05-19 22:23:55 +0000612 if (I == IndVarIncrement) {
613 // Replace induction variable increment if it is not used outside
614 // the loop.
615 bool UsedOutsideLoop = false;
616 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
617 UI != E; ++UI) {
618 if (Instruction *Use = dyn_cast<Instruction>(UI))
619 if (!L->contains(Use->getParent())) {
620 UsedOutsideLoop = true;
621 break;
622 }
623 }
624 if (!UsedOutsideLoop) {
625 I->replaceAllUsesWith(ExitValue);
626 I->eraseFromParent();
627 }
628 }
629 else {
Devang Patelada054a2007-08-14 01:30:57 +0000630 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel52abbf52008-05-19 22:23:55 +0000631 I->eraseFromParent();
632 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000633 }
634
Devang Patel423c8b22007-08-10 18:07:13 +0000635 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000636
637 // Update Dominator Info.
638 // Only CFG change done is to remove Latch to Header edge. This
639 // does not change dominator tree because Latch did not dominate
640 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000641 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000642 DominanceFrontier::iterator HeaderDF = DF->find(Header);
643 if (HeaderDF != DF->end())
644 DF->removeFromFrontier(HeaderDF, Header);
645
646 DominanceFrontier::iterator LatchDF = DF->find(Latch);
647 if (LatchDF != DF->end())
648 DF->removeFromFrontier(LatchDF, Header);
649 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000650 return true;
651}
652
653// If loop header includes loop variant instruction operands then
654// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patel71554b82007-08-08 21:02:17 +0000655bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000656
657 Instruction *Terminator = Header->getTerminator();
658 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
659 BI != BE; ++BI) {
660 Instruction *I = BI;
661
Devang Patelada054a2007-08-14 01:30:57 +0000662 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000663 if (isa<PHINode>(I))
664 continue;
665
666 // SplitCondition itself is OK.
Devang Patel71554b82007-08-08 21:02:17 +0000667 if (I == SD.SplitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000668 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000669
Devang Patelc9d123d2007-08-09 01:39:01 +0000670 // Induction variable is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000671 if (I == IndVar)
Devang Patelc9d123d2007-08-09 01:39:01 +0000672 continue;
673
674 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000675 if (I == IndVarIncrement)
Devang Patelc9d123d2007-08-09 01:39:01 +0000676 continue;
677
Devang Patelfee76bd2007-08-07 00:25:56 +0000678 // Terminator is also harmless.
679 if (I == Terminator)
680 continue;
681
682 // Otherwise we have a instruction that may not be safe.
683 return false;
684 }
685
686 return true;
687}
688
Devang Patel1cc2ec82007-08-20 23:51:18 +0000689// If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000690// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel1cc2ec82007-08-20 23:51:18 +0000691bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
692 BasicBlock *ExitingBlock) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000693
Devang Patel1cc2ec82007-08-20 23:51:18 +0000694 for (BasicBlock::iterator BI = ExitingBlock->begin(),
695 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000696 Instruction *I = BI;
697
Devang Patelada054a2007-08-14 01:30:57 +0000698 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000699 if (isa<PHINode>(I))
700 continue;
701
Devang Patelc9d123d2007-08-09 01:39:01 +0000702 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000703 if (IndVarIncrement && IndVarIncrement == I)
Devang Patelc9d123d2007-08-09 01:39:01 +0000704 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000705
Devang Patelc9d123d2007-08-09 01:39:01 +0000706 // Check if I is induction variable increment instruction.
Devang Patela6dff2f2007-09-25 18:24:48 +0000707 if (I->getOpcode() == Instruction::Add) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000708
709 Value *Op0 = I->getOperand(0);
710 Value *Op1 = I->getOperand(1);
Devang Patelfee76bd2007-08-07 00:25:56 +0000711 PHINode *PN = NULL;
712 ConstantInt *CI = NULL;
713
714 if ((PN = dyn_cast<PHINode>(Op0))) {
715 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000716 if (CI->isOne()) {
717 if (!IndVarIncrement && PN == IndVar)
718 IndVarIncrement = I;
719 // else this is another loop induction variable
720 continue;
721 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000722 } else
723 if ((PN = dyn_cast<PHINode>(Op1))) {
724 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000725 if (CI->isOne()) {
726 if (!IndVarIncrement && PN == IndVar)
727 IndVarIncrement = I;
728 // else this is another loop induction variable
729 continue;
730 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000731 }
Devang Patela6dff2f2007-09-25 18:24:48 +0000732 }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000733
Devang Patelfee76bd2007-08-07 00:25:56 +0000734 // I is an Exit condition if next instruction is block terminator.
735 // Exit condition is OK if it compares loop invariant exit value,
736 // which is checked below.
Devang Patel002fe252007-08-07 23:17:52 +0000737 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbacf5192007-08-10 00:33:50 +0000738 if (EC == ExitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000739 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000740 }
741
Devang Patel1cc2ec82007-08-20 23:51:18 +0000742 if (I == ExitingBlock->getTerminator())
Devang Patelbacf5192007-08-10 00:33:50 +0000743 continue;
744
Devang Patelfee76bd2007-08-07 00:25:56 +0000745 // Otherwise we have instruction that may not be safe.
746 return false;
747 }
748
Devang Patel1cc2ec82007-08-20 23:51:18 +0000749 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelfee76bd2007-08-07 00:25:56 +0000750 return true;
751}
752
Devang Patel5279d062007-09-17 20:39:48 +0000753void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
754
755 Value *V0 = CI->getOperand(0);
756 Value *V1 = CI->getOperand(1);
757 Value *NV = NULL;
758
759 SCEVHandle SH0 = SE->getSCEV(V0);
760
761 if (SH0->isLoopInvariant(L))
762 NV = V0;
763 else
764 NV = V1;
765
Devang Patel453a8442007-09-25 17:31:19 +0000766 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
767 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
768 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
769 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
770 ExitCondition->swapOperands();
771 if (ExitValueNum)
772 ExitValueNum = 0;
773 else
774 ExitValueNum = 1;
775 }
776
777 Value *NUB = NULL;
778 Value *NLB = NULL;
779 Value *UB = ExitCondition->getOperand(ExitValueNum);
780 const Type *Ty = NV->getType();
781 bool Sign = ExitCondition->isSignedPredicate();
782 BasicBlock *Preheader = L->getLoopPreheader();
783 Instruction *PHTerminator = Preheader->getTerminator();
784
785 assert (NV && "Unexpected value");
786
Devang Patel5279d062007-09-17 20:39:48 +0000787 switch (CI->getPredicate()) {
788 case ICmpInst::ICMP_ULE:
789 case ICmpInst::ICMP_SLE:
790 // for (i = LB; i < UB; ++i)
791 // if (i <= NV && ...)
792 // LOOP_BODY
793 //
794 // is transformed into
795 // NUB = min (NV+1, UB)
796 // for (i = LB; i < NUB ; ++i)
797 // LOOP_BODY
798 //
Devang Patel453a8442007-09-25 17:31:19 +0000799 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
800 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000801 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000802 "lsplit.add", PHTerminator);
803 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
804 A, UB,"lsplit,c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000805 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000806 }
807
Devang Patel5279d062007-09-17 20:39:48 +0000808 // for (i = LB; i <= UB; ++i)
809 // if (i <= NV && ...)
810 // LOOP_BODY
811 //
812 // is transformed into
813 // NUB = min (NV, UB)
814 // for (i = LB; i <= NUB ; ++i)
815 // LOOP_BODY
816 //
Devang Patel453a8442007-09-25 17:31:19 +0000817 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
818 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
819 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
820 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000821 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000822 }
Devang Patel5279d062007-09-17 20:39:48 +0000823 break;
824 case ICmpInst::ICMP_ULT:
825 case ICmpInst::ICMP_SLT:
826 // for (i = LB; i < UB; ++i)
827 // if (i < NV && ...)
828 // LOOP_BODY
829 //
830 // is transformed into
831 // NUB = min (NV, UB)
832 // for (i = LB; i < NUB ; ++i)
833 // LOOP_BODY
834 //
Devang Patel453a8442007-09-25 17:31:19 +0000835 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
836 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
837 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
838 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000839 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000840 }
Devang Patel5279d062007-09-17 20:39:48 +0000841
842 // for (i = LB; i <= UB; ++i)
843 // if (i < NV && ...)
844 // LOOP_BODY
845 //
846 // is transformed into
847 // NUB = min (NV -1 , UB)
848 // for (i = LB; i <= NUB ; ++i)
849 // LOOP_BODY
850 //
Devang Patel453a8442007-09-25 17:31:19 +0000851 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
852 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000853 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000854 "lsplit.add", PHTerminator);
855 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
856 S, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000857 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000858 }
Devang Patel5279d062007-09-17 20:39:48 +0000859 break;
860 case ICmpInst::ICMP_UGE:
861 case ICmpInst::ICMP_SGE:
862 // for (i = LB; i (< or <=) UB; ++i)
863 // if (i >= NV && ...)
864 // LOOP_BODY
865 //
866 // is transformed into
867 // NLB = max (NV, LB)
868 // for (i = NLB; i (< or <=) UB ; ++i)
869 // LOOP_BODY
870 //
Devang Patel453a8442007-09-25 17:31:19 +0000871 {
872 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
873 NV, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000874 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000875 }
Devang Patel5279d062007-09-17 20:39:48 +0000876 break;
877 case ICmpInst::ICMP_UGT:
878 case ICmpInst::ICMP_SGT:
879 // for (i = LB; i (< or <=) UB; ++i)
880 // if (i > NV && ...)
881 // LOOP_BODY
882 //
883 // is transformed into
884 // NLB = max (NV+1, LB)
885 // for (i = NLB; i (< or <=) UB ; ++i)
886 // LOOP_BODY
887 //
Devang Patel453a8442007-09-25 17:31:19 +0000888 {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000889 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
Devang Patel453a8442007-09-25 17:31:19 +0000890 "lsplit.add", PHTerminator);
891 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
892 A, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000893 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000894 }
Devang Patel5279d062007-09-17 20:39:48 +0000895 break;
896 default:
897 assert ( 0 && "Unexpected split condition predicate");
898 }
Devang Patel453a8442007-09-25 17:31:19 +0000899
900 if (NLB) {
901 unsigned i = IndVar->getBasicBlockIndex(Preheader);
902 IndVar->setIncomingValue(i, NLB);
903 }
904
905 if (NUB) {
906 ExitCondition->setOperand(ExitValueNum, NUB);
907 }
Devang Patel5279d062007-09-17 20:39:48 +0000908}
909/// updateLoopIterationSpace - Current loop body is covered by an AND
910/// instruction whose operands compares induction variables with loop
911/// invariants. If possible, hoist this check outside the loop by
912/// updating appropriate start and end values for induction variable.
913bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
914 BasicBlock *Header = L->getHeader();
Devang Patel453a8442007-09-25 17:31:19 +0000915 BasicBlock *ExitingBlock = ExitCondition->getParent();
916 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
917
Devang Patel5279d062007-09-17 20:39:48 +0000918 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
919 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
920
921 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
922 || Op0->getPredicate() == ICmpInst::ICMP_NE
923 || Op0->getPredicate() == ICmpInst::ICMP_EQ
924 || Op0->getPredicate() == ICmpInst::ICMP_NE)
925 return false;
926
927 // Check if SplitCondition dominates entire loop body
928 // or not.
929
930 // If SplitCondition is not in loop header then this loop is not suitable
931 // for this transformation.
932 if (SD.SplitCondition->getParent() != Header)
933 return false;
934
935 // If loop header includes loop variant instruction operands then
936 // this loop may not be eliminated.
937 Instruction *Terminator = Header->getTerminator();
938 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
939 BI != BE; ++BI) {
940 Instruction *I = BI;
941
942 // PHI Nodes are OK.
943 if (isa<PHINode>(I))
944 continue;
945
946 // SplitCondition itself is OK.
947 if (I == SD.SplitCondition)
948 continue;
949 if (I == Op0 || I == Op1)
950 continue;
951
952 // Induction variable is OK.
953 if (I == IndVar)
954 continue;
955
956 // Induction variable increment is OK.
957 if (I == IndVarIncrement)
958 continue;
959
960 // Terminator is also harmless.
961 if (I == Terminator)
962 continue;
963
964 // Otherwise we have a instruction that may not be safe.
965 return false;
966 }
967
968 // If Exiting block includes loop variant instructions then this
969 // loop may not be eliminated.
970 if (!safeExitingBlock(SD, ExitCondition->getParent()))
971 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000972
973 // Verify that loop exiting block has only two predecessor, where one predecessor
974 // is split condition block. The other predecessor will become exiting block's
975 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
976 // more then two predecessors. This requires extra work in updating dominator
977 // information.
978 BasicBlock *ExitingBBPred = NULL;
979 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
980 PI != PE; ++PI) {
981 BasicBlock *BB = *PI;
982 if (SplitCondBlock == BB)
983 continue;
984 if (ExitingBBPred)
985 return false;
986 else
987 ExitingBBPred = BB;
988 }
989
990 // Update loop bounds to absorb Op0 check.
Devang Patel5279d062007-09-17 20:39:48 +0000991 updateLoopBounds(Op0);
Devang Patel453a8442007-09-25 17:31:19 +0000992 // Update loop bounds to absorb Op1 check.
Devang Patel5279d062007-09-17 20:39:48 +0000993 updateLoopBounds(Op1);
Devang Patel453a8442007-09-25 17:31:19 +0000994
Devang Patel5279d062007-09-17 20:39:48 +0000995 // Update CFG
Devang Patel453a8442007-09-25 17:31:19 +0000996
997 // Unconditionally connect split block to its remaining successor.
998 BranchInst *SplitTerminator =
999 cast<BranchInst>(SplitCondBlock->getTerminator());
1000 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1001 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1002 if (Succ0 == ExitCondition->getParent())
1003 SplitTerminator->setUnconditionalDest(Succ1);
1004 else
1005 SplitTerminator->setUnconditionalDest(Succ0);
1006
1007 // Remove split condition.
1008 SD.SplitCondition->eraseFromParent();
1009 if (Op0->use_begin() == Op0->use_end())
1010 Op0->eraseFromParent();
1011 if (Op1->use_begin() == Op1->use_end())
1012 Op1->eraseFromParent();
1013
1014 BranchInst *ExitInsn =
1015 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1016 assert (ExitInsn && "Unable to find suitable loop exit branch");
1017 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1018 if (L->contains(ExitBlock))
1019 ExitBlock = ExitInsn->getSuccessor(0);
1020
1021 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1022 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1023 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1024
1025 // If ExitingBlock is a member of loop BB's DF list then replace it with
1026 // loop header and exit block.
1027 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1028 I != E; ++I) {
1029 BasicBlock *BB = *I;
1030 if (BB == Header || BB == ExitingBlock)
1031 continue;
1032 DominanceFrontier::iterator BBDF = DF->find(BB);
1033 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1034 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1035 while (DomSetI != DomSetE) {
1036 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1037 ++DomSetI;
1038 BasicBlock *DFBB = *CurrentItr;
1039 if (DFBB == ExitingBlock) {
1040 BBDF->second.erase(DFBB);
1041 BBDF->second.insert(Header);
1042 if (Header != ExitingBlock)
1043 BBDF->second.insert(ExitBlock);
1044 }
1045 }
1046 }
1047
Devang Patel1c013502007-09-25 17:43:08 +00001048 return true;
Devang Patel5279d062007-09-17 20:39:48 +00001049}
1050
1051
Devang Patela6a86632007-08-14 18:35:57 +00001052/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1053/// This routine is used to remove split condition's dead branch, dominated by
1054/// DeadBB. LiveBB dominates split conidition's other branch.
1055void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1056 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +00001057
Devang Patel5b8ec612007-08-15 03:31:47 +00001058 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +00001059 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +00001060 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1061 if (DeadBBDF != DF->end()) {
1062 SmallVector<BasicBlock *, 8> PredBlocks;
1063
1064 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1065 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1066 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1067 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +00001068 FrontierBBs.push_back(FrontierBB);
1069
Devang Patel5b8ec612007-08-15 03:31:47 +00001070 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1071 PredBlocks.clear();
1072 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1073 PI != PE; ++PI) {
1074 BasicBlock *P = *PI;
1075 if (P == DeadBB || DT->dominates(DeadBB, P))
1076 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001077 }
Devang Patel96bf5242007-08-17 21:59:16 +00001078
Devang Patel5b8ec612007-08-15 03:31:47 +00001079 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1080 FBI != FBE; ++FBI) {
1081 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1082 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1083 PE = PredBlocks.end(); PI != PE; ++PI) {
1084 BasicBlock *P = *PI;
1085 PN->removeIncomingValue(P);
1086 }
1087 }
1088 else
1089 break;
Devang Patel96bf5242007-08-17 21:59:16 +00001090 }
Devang Patel98147a32007-08-12 07:02:51 +00001091 }
Devang Patel98147a32007-08-12 07:02:51 +00001092 }
Devang Patel5b8ec612007-08-15 03:31:47 +00001093
1094 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1095 SmallVector<BasicBlock *, 32> WorkList;
1096 DomTreeNode *DN = DT->getNode(DeadBB);
1097 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1098 E = df_end(DN); DI != E; ++DI) {
1099 BasicBlock *BB = DI->getBlock();
1100 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +00001101 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +00001102 }
1103
1104 while (!WorkList.empty()) {
1105 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1106 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +00001107 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +00001108 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +00001109 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +00001110 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1111 I->eraseFromParent();
1112 }
1113 LPM->deleteSimpleAnalysisValue(BB, LP);
1114 DT->eraseNode(BB);
1115 DF->removeBlock(BB);
1116 LI->removeBlock(BB);
1117 BB->eraseFromParent();
1118 }
Devang Patel96bf5242007-08-17 21:59:16 +00001119
1120 // Update Frontier BBs' dominator info.
1121 while (!FrontierBBs.empty()) {
1122 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1123 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1124 if (!NewDominator) {
1125 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1126 NewDominator = *PI;
1127 ++PI;
1128 if (NewDominator != LiveBB) {
1129 for(; PI != PE; ++PI) {
1130 BasicBlock *P = *PI;
1131 if (P == LiveBB) {
1132 NewDominator = LiveBB;
1133 break;
1134 }
1135 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1136 }
1137 }
1138 }
1139 assert (NewDominator && "Unable to fix dominator info.");
1140 DT->changeImmediateDominator(FBB, NewDominator);
1141 DF->changeImmediateDominator(FBB, NewDominator, DT);
1142 }
1143
Devang Patel98147a32007-08-12 07:02:51 +00001144}
1145
Devang Pateldc523952007-08-22 18:27:01 +00001146/// safeSplitCondition - Return true if it is possible to
1147/// split loop using given split condition.
1148bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patel23a19f82007-08-10 00:53:35 +00001149
Devang Pateldc523952007-08-22 18:27:01 +00001150 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel8893ca62007-09-17 21:01:05 +00001151 BasicBlock *Latch = L->getLoopLatch();
Devang Pateldc523952007-08-22 18:27:01 +00001152 BranchInst *SplitTerminator =
1153 cast<BranchInst>(SplitCondBlock->getTerminator());
1154 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1155 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel20d260a2007-08-18 00:00:32 +00001156
Bill Wendling643310d2008-05-02 00:43:20 +00001157 // If split block does not dominate the latch then this is not a diamond.
1158 // Such loop may not benefit from index split.
1159 if (!DT->dominates(SplitCondBlock, Latch))
1160 return false;
1161
Devang Patelb88e4202007-08-24 05:36:56 +00001162 // Finally this split condition is safe only if merge point for
1163 // split condition branch is loop latch. This check along with previous
1164 // check, to ensure that exit condition is in either loop latch or header,
1165 // filters all loops with non-empty loop body between merge point
1166 // and exit condition.
1167 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1168 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1169 if (Succ0DF->second.count(Latch))
1170 return true;
1171
1172 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1173 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1174 if (Succ1DF->second.count(Latch))
1175 return true;
1176
1177 return false;
Devang Pateldc523952007-08-22 18:27:01 +00001178}
1179
Devang Patel4a69da92007-08-25 00:56:38 +00001180/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1181/// based on split value.
1182void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1183
Devang Patel4f12c5f2007-09-11 00:12:56 +00001184 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1185 ICmpInst::Predicate SP = SC->getPredicate();
Devang Patel4a69da92007-08-25 00:56:38 +00001186 const Type *Ty = SD.SplitValue->getType();
1187 bool Sign = ExitCondition->isSignedPredicate();
1188 BasicBlock *Preheader = L->getLoopPreheader();
1189 Instruction *PHTerminator = Preheader->getTerminator();
1190
1191 // Initially use split value as upper loop bound for first loop and lower loop
1192 // bound for second loop.
1193 Value *AEV = SD.SplitValue;
1194 Value *BSV = SD.SplitValue;
1195
Devang Patelbabbe272007-09-19 00:28:47 +00001196 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1197 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1198 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel02c48362008-02-13 19:48:48 +00001199 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
Devang Patelbabbe272007-09-19 00:28:47 +00001200 ExitCondition->swapOperands();
Devang Patel02c48362008-02-13 19:48:48 +00001201 if (ExitValueNum)
1202 ExitValueNum = 0;
1203 else
1204 ExitValueNum = 1;
1205 }
Devang Patelbabbe272007-09-19 00:28:47 +00001206
Devang Patel4a69da92007-08-25 00:56:38 +00001207 switch (ExitCondition->getPredicate()) {
1208 case ICmpInst::ICMP_SGT:
1209 case ICmpInst::ICMP_UGT:
1210 case ICmpInst::ICMP_SGE:
1211 case ICmpInst::ICMP_UGE:
1212 default:
1213 assert (0 && "Unexpected exit condition predicate");
1214
1215 case ICmpInst::ICMP_SLT:
1216 case ICmpInst::ICMP_ULT:
1217 {
1218 switch (SP) {
1219 case ICmpInst::ICMP_SLT:
1220 case ICmpInst::ICMP_ULT:
1221 //
1222 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1223 //
1224 // is transformed into
1225 // AEV = BSV = SV
1226 // for (i = LB; i < min(UB, AEV); ++i)
1227 // A;
1228 // for (i = max(LB, BSV); i < UB; ++i);
1229 // B;
1230 break;
1231 case ICmpInst::ICMP_SLE:
1232 case ICmpInst::ICMP_ULE:
1233 {
1234 //
1235 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1236 //
1237 // is transformed into
1238 //
1239 // AEV = SV + 1
1240 // BSV = SV + 1
1241 // for (i = LB; i < min(UB, AEV); ++i)
1242 // A;
1243 // for (i = max(LB, BSV); i < UB; ++i)
1244 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001245 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001246 ConstantInt::get(Ty, 1, Sign),
1247 "lsplit.add", PHTerminator);
1248 AEV = BSV;
1249 }
1250 break;
1251 case ICmpInst::ICMP_SGE:
1252 case ICmpInst::ICMP_UGE:
1253 //
1254 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1255 //
1256 // is transformed into
1257 // AEV = BSV = SV
1258 // for (i = LB; i < min(UB, AEV); ++i)
1259 // B;
1260 // for (i = max(BSV, LB); i < UB; ++i)
1261 // A;
1262 break;
1263 case ICmpInst::ICMP_SGT:
1264 case ICmpInst::ICMP_UGT:
1265 {
1266 //
1267 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1268 //
1269 // is transformed into
1270 //
1271 // BSV = AEV = SV + 1
1272 // for (i = LB; i < min(UB, AEV); ++i)
1273 // B;
1274 // for (i = max(LB, BSV); i < UB; ++i)
1275 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001276 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001277 ConstantInt::get(Ty, 1, Sign),
1278 "lsplit.add", PHTerminator);
1279 AEV = BSV;
1280 }
1281 break;
1282 default:
1283 assert (0 && "Unexpected split condition predicate");
1284 break;
1285 } // end switch (SP)
1286 }
1287 break;
1288 case ICmpInst::ICMP_SLE:
1289 case ICmpInst::ICMP_ULE:
1290 {
1291 switch (SP) {
1292 case ICmpInst::ICMP_SLT:
1293 case ICmpInst::ICMP_ULT:
1294 //
1295 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1296 //
1297 // is transformed into
1298 // AEV = SV - 1;
1299 // BSV = SV;
1300 // for (i = LB; i <= min(UB, AEV); ++i)
1301 // A;
1302 // for (i = max(LB, BSV); i <= UB; ++i)
1303 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001304 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001305 ConstantInt::get(Ty, 1, Sign),
1306 "lsplit.sub", PHTerminator);
1307 break;
1308 case ICmpInst::ICMP_SLE:
1309 case ICmpInst::ICMP_ULE:
1310 //
1311 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1312 //
1313 // is transformed into
1314 // AEV = SV;
1315 // BSV = SV + 1;
1316 // for (i = LB; i <= min(UB, AEV); ++i)
1317 // A;
1318 // for (i = max(LB, BSV); i <= UB; ++i)
1319 // B;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001320 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001321 ConstantInt::get(Ty, 1, Sign),
1322 "lsplit.add", PHTerminator);
1323 break;
1324 case ICmpInst::ICMP_SGT:
1325 case ICmpInst::ICMP_UGT:
1326 //
1327 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1328 //
1329 // is transformed into
1330 // AEV = SV;
1331 // BSV = SV + 1;
1332 // for (i = LB; i <= min(AEV, UB); ++i)
1333 // B;
1334 // for (i = max(LB, BSV); i <= UB; ++i)
1335 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001336 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001337 ConstantInt::get(Ty, 1, Sign),
1338 "lsplit.add", PHTerminator);
1339 break;
1340 case ICmpInst::ICMP_SGE:
1341 case ICmpInst::ICMP_UGE:
1342 // ** TODO **
1343 //
1344 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1345 //
1346 // is transformed into
1347 // AEV = SV - 1;
1348 // BSV = SV;
1349 // for (i = LB; i <= min(AEV, UB); ++i)
1350 // B;
1351 // for (i = max(LB, BSV); i <= UB; ++i)
1352 // A;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001353 AEV = BinaryOperator::CreateSub(SD.SplitValue,
Devang Patel4a69da92007-08-25 00:56:38 +00001354 ConstantInt::get(Ty, 1, Sign),
1355 "lsplit.sub", PHTerminator);
1356 break;
1357 default:
1358 assert (0 && "Unexpected split condition predicate");
1359 break;
1360 } // end switch (SP)
1361 }
1362 break;
1363 }
1364
1365 // Calculate ALoop induction variable's new exiting value and
1366 // BLoop induction variable's new starting value. Calculuate these
1367 // values in original loop's preheader.
1368 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1369 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel3f65f022007-09-21 21:18:19 +00001370 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Patel5ffdc562007-12-03 19:17:21 +00001371
1372 // If ExitValue operand is also defined in Loop header then
1373 // insert new ExitValue after this operand definition.
1374 if (Instruction *EVN =
1375 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1376 if (!isa<PHINode>(EVN))
1377 if (InsertPt->getParent() == EVN->getParent()) {
1378 BasicBlock::iterator LHBI = L->getHeader()->begin();
1379 BasicBlock::iterator LHBE = L->getHeader()->end();
1380 for(;LHBI != LHBE; ++LHBI) {
1381 Instruction *I = LHBI;
1382 if (I == EVN)
1383 break;
1384 }
1385 InsertPt = ++LHBI;
1386 }
1387 }
Devang Patel4a69da92007-08-25 00:56:38 +00001388 Value *C1 = new ICmpInst(Sign ?
1389 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1390 AEV,
1391 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001392 "lsplit.ev", InsertPt);
1393
Gabor Greif051a9502008-04-06 20:25:17 +00001394 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1395 ExitCondition->getOperand(ExitValueNum),
1396 "lsplit.ev", InsertPt);
Devang Patel3f65f022007-09-21 21:18:19 +00001397
Devang Patel4a69da92007-08-25 00:56:38 +00001398 Value *C2 = new ICmpInst(Sign ?
1399 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1400 BSV, StartValue, "lsplit.sv",
1401 PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +00001402 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1403 "lsplit.sv", PHTerminator);
Devang Patel4a69da92007-08-25 00:56:38 +00001404}
1405
Devang Pateldc523952007-08-22 18:27:01 +00001406/// splitLoop - Split current loop L in two loops using split information
1407/// SD. Update dominator information. Maintain LCSSA form.
1408bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1409
1410 if (!safeSplitCondition(SD))
1411 return false;
1412
Devang Patel8893ca62007-09-17 21:01:05 +00001413 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1414
Dan Gohman2864ce62008-06-24 18:00:21 +00001415 // Unable to handle triangle loops at the moment.
Devang Patel8893ca62007-09-17 21:01:05 +00001416 // In triangle loop, split condition is in header and one of the
1417 // the split destination is loop latch. If split condition is EQ
1418 // then such loops are already handle in processOneIterationLoop().
1419 BasicBlock *Latch = L->getLoopLatch();
1420 BranchInst *SplitTerminator =
1421 cast<BranchInst>(SplitCondBlock->getTerminator());
1422 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1423 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1424 if (L->getHeader() == SplitCondBlock
1425 && (Latch == Succ0 || Latch == Succ1))
1426 return false;
1427
1428 // If split condition branches heads do not have single predecessor,
1429 // SplitCondBlock, then is not possible to remove inactive branch.
1430 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1431 return false;
1432
Devang Patel82ada542008-02-08 22:49:13 +00001433 // If Exiting block includes loop variant instructions then this
1434 // loop may not be split safely.
1435 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1436 return false;
1437
Devang Patela8644e32007-08-22 19:33:29 +00001438 // After loop is cloned there are two loops.
1439 //
1440 // First loop, referred as ALoop, executes first part of loop's iteration
1441 // space split. Second loop, referred as BLoop, executes remaining
1442 // part of loop's iteration space.
1443 //
1444 // ALoop's exit edge enters BLoop's header through a forwarding block which
1445 // acts as a BLoop's preheader.
Devang Patel4a69da92007-08-25 00:56:38 +00001446 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateldc523952007-08-22 18:27:01 +00001447
Devang Patel4a69da92007-08-25 00:56:38 +00001448 // Calculate ALoop induction variable's new exiting value and
1449 // BLoop induction variable's new starting value.
1450 calculateLoopBounds(SD);
Devang Patel423c8b22007-08-10 18:07:13 +00001451
Devang Patela8644e32007-08-22 19:33:29 +00001452 //[*] Clone loop.
Devang Patel98147a32007-08-12 07:02:51 +00001453 DenseMap<const Value *, Value *> ValueMap;
Devang Patela8644e32007-08-22 19:33:29 +00001454 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Pateld79faee2007-08-25 02:39:24 +00001455 Loop *ALoop = L;
Devang Patela8644e32007-08-22 19:33:29 +00001456 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel98147a32007-08-12 07:02:51 +00001457
Devang Patela8644e32007-08-22 19:33:29 +00001458 //[*] ALoop's exiting edge BLoop's header.
1459 // ALoop's original exit block becomes BLoop's exit block.
1460 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1461 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1462 BranchInst *A_ExitInsn =
1463 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1464 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1465 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1466 if (L->contains(B_ExitBlock)) {
1467 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1468 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patelada054a2007-08-14 01:30:57 +00001469 } else
Devang Patela8644e32007-08-22 19:33:29 +00001470 A_ExitInsn->setSuccessor(1, B_Header);
1471
1472 //[*] Update ALoop's exit value using new exit value.
Devang Patel4a69da92007-08-25 00:56:38 +00001473 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001474
Devang Patela8644e32007-08-22 19:33:29 +00001475 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1476 // original loop's preheader. Add incoming PHINode values from
1477 // ALoop's exiting block. Update BLoop header's domiantor info.
1478
Devang Patelada054a2007-08-14 01:30:57 +00001479 // Collect inverse map of Header PHINodes.
1480 DenseMap<Value *, Value *> InverseMap;
1481 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1482 BE = L->getHeader()->end(); BI != BE; ++BI) {
1483 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1484 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1485 InverseMap[PNClone] = PN;
1486 } else
1487 break;
1488 }
Devang Patel4a69da92007-08-25 00:56:38 +00001489
Devang Patela8644e32007-08-22 19:33:29 +00001490 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel98147a32007-08-12 07:02:51 +00001491 BI != BE; ++BI) {
1492 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001493 // Remove incoming value from original preheader.
1494 PN->removeIncomingValue(Preheader);
1495
1496 // Add incoming value from A_ExitingBlock.
1497 if (PN == B_IndVar)
Devang Patel4a69da92007-08-25 00:56:38 +00001498 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001499 else {
1500 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patel9b03daa2008-02-14 23:18:47 +00001501 Value *V2 = NULL;
1502 // If loop header is also loop exiting block then
1503 // OrigPN is incoming value for B loop header.
1504 if (A_ExitingBlock == L->getHeader())
1505 V2 = OrigPN;
1506 else
1507 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
Devang Patela8644e32007-08-22 19:33:29 +00001508 PN->addIncoming(V2, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001509 }
1510 } else
Devang Patel98147a32007-08-12 07:02:51 +00001511 break;
1512 }
Devang Patela8644e32007-08-22 19:33:29 +00001513 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1514 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001515
Devang Patela8644e32007-08-22 19:33:29 +00001516 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1517 // block. Remove incoming PHINode values from ALoop's exiting block.
1518 // Add new incoming values from BLoop's incoming exiting value.
1519 // Update BLoop exit block's dominator info..
1520 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1521 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patelada054a2007-08-14 01:30:57 +00001522 BI != BE; ++BI) {
1523 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001524 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1525 B_ExitingBlock);
1526 PN->removeIncomingValue(A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001527 } else
1528 break;
1529 }
Devang Patel98147a32007-08-12 07:02:51 +00001530
Devang Patela8644e32007-08-22 19:33:29 +00001531 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1532 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001533
Devang Patela8644e32007-08-22 19:33:29 +00001534 //[*] Split ALoop's exit edge. This creates a new block which
1535 // serves two purposes. First one is to hold PHINode defnitions
1536 // to ensure that ALoop's LCSSA form. Second use it to act
1537 // as a preheader for BLoop.
1538 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel423c8b22007-08-10 18:07:13 +00001539
Devang Patela8644e32007-08-22 19:33:29 +00001540 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1541 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1542 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel60cbab42007-08-21 19:47:46 +00001543 BI != BE; ++BI) {
1544 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001545 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001546 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
Devang Patela8644e32007-08-22 19:33:29 +00001547 newPHI->addIncoming(V1, A_ExitingBlock);
1548 A_ExitBlock->getInstList().push_front(newPHI);
1549 PN->removeIncomingValue(A_ExitBlock);
1550 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001551 } else
1552 break;
1553 }
1554
Devang Patela8644e32007-08-22 19:33:29 +00001555 //[*] Eliminate split condition's inactive branch from ALoop.
1556 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1557 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001558 BasicBlock *A_InactiveBranch = NULL;
1559 BasicBlock *A_ActiveBranch = NULL;
1560 if (SD.UseTrueBranchFirst) {
1561 A_ActiveBranch = A_BR->getSuccessor(0);
1562 A_InactiveBranch = A_BR->getSuccessor(1);
1563 } else {
1564 A_ActiveBranch = A_BR->getSuccessor(1);
1565 A_InactiveBranch = A_BR->getSuccessor(0);
1566 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001567 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001568 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1569
1570 //[*] Eliminate split condition's inactive branch in from BLoop.
1571 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1572 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001573 BasicBlock *B_InactiveBranch = NULL;
1574 BasicBlock *B_ActiveBranch = NULL;
1575 if (SD.UseTrueBranchFirst) {
1576 B_ActiveBranch = B_BR->getSuccessor(1);
1577 B_InactiveBranch = B_BR->getSuccessor(0);
1578 } else {
1579 B_ActiveBranch = B_BR->getSuccessor(0);
1580 B_InactiveBranch = B_BR->getSuccessor(1);
1581 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001582 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001583 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1584
Devang Pateld79faee2007-08-25 02:39:24 +00001585 BasicBlock *A_Header = L->getHeader();
1586 if (A_ExitingBlock == A_Header)
1587 return true;
1588
1589 //[*] Move exit condition into split condition block to avoid
1590 // executing dead loop iteration.
1591 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1592 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1593 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1594
1595 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel4f12c5f2007-09-11 00:12:56 +00001596 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1597 ALoop);
Devang Pateld79faee2007-08-25 02:39:24 +00001598
1599 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1600 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1601
Devang Patel98147a32007-08-12 07:02:51 +00001602 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +00001603}
Devang Pateld79faee2007-08-25 02:39:24 +00001604
1605// moveExitCondition - Move exit condition EC into split condition block CondBB.
1606void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1607 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1608 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1609
1610 BasicBlock *ExitingBB = EC->getParent();
1611 Instruction *CurrentBR = CondBB->getTerminator();
1612
1613 // Move exit condition into split condition block.
1614 EC->moveBefore(CurrentBR);
1615 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1616
1617 // Move exiting block's branch into split condition block. Update its branch
1618 // destination.
1619 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1620 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +00001621 BasicBlock *OrigDestBB = NULL;
1622 if (ExitingBR->getSuccessor(0) == ExitBB) {
1623 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +00001624 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001625 }
1626 else {
1627 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +00001628 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001629 }
Devang Pateld79faee2007-08-25 02:39:24 +00001630
1631 // Remove split condition and current split condition branch.
1632 SC->eraseFromParent();
1633 CurrentBR->eraseFromParent();
1634
Devang Patel23067df2008-02-13 22:06:36 +00001635 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +00001636 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +00001637
1638 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +00001639 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +00001640
1641 // Fix dominator info.
1642 // ExitBB is now dominated by CondBB
1643 DT->changeImmediateDominator(ExitBB, CondBB);
1644 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1645
1646 // Basicblocks dominated by ActiveBB may have ExitingBB or
1647 // a basic block outside the loop in their DF list. If so,
1648 // replace it with CondBB.
1649 DomTreeNode *Node = DT->getNode(ActiveBB);
1650 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1651 DI != DE; ++DI) {
1652 BasicBlock *BB = DI->getBlock();
1653 DominanceFrontier::iterator BBDF = DF->find(BB);
1654 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1655 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1656 while (DomSetI != DomSetE) {
1657 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1658 ++DomSetI;
1659 BasicBlock *DFBB = *CurrentItr;
1660 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1661 BBDF->second.erase(DFBB);
1662 BBDF->second.insert(CondBB);
1663 }
1664 }
1665 }
1666}
1667
1668/// updatePHINodes - CFG has been changed.
1669/// Before
1670/// - ExitBB's single predecessor was Latch
1671/// - Latch's second successor was Header
1672/// Now
Devang Patel82ada542008-02-08 22:49:13 +00001673/// - ExitBB's single predecessor is Header
1674/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +00001675///
1676/// Update ExitBB PHINodes' to reflect this change.
1677void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1678 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +00001679 PHINode *IV, Instruction *IVIncrement,
1680 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +00001681
1682 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001683 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +00001684 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001685 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +00001686 if (!PN)
1687 break;
1688
1689 Value *V = PN->getIncomingValueForBlock(Latch);
1690 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +00001691 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1692 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +00001693 Value *NewV = NULL;
1694 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +00001695 UI != E; ++UI)
1696 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +00001697 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +00001698 NewV = U;
1699 break;
1700 }
1701
Devang Patel60a12902008-03-24 20:16:14 +00001702 // Add incoming value from header only if PN has any use inside the loop.
1703 if (NewV)
1704 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +00001705
1706 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1707 // If this instruction is IVIncrement then IV is new incoming value
1708 // from header otherwise this instruction must be incoming value from
1709 // header because loop is in LCSSA form.
1710 if (PHI == IVIncrement)
1711 PN->addIncoming(IV, Header);
1712 else
1713 PN->addIncoming(V, Header);
1714 } else
1715 // Otherwise this is an incoming value from header because loop is in
1716 // LCSSA form.
1717 PN->addIncoming(V, Header);
1718
1719 // Remove incoming value from Latch.
1720 PN->removeIncomingValue(Latch);
1721 }
1722}