blob: afb7339093a0ac13571273b833c2458dcdea8fc1 [file] [log] [blame]
Devang Patelbc5fe632007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelbc5fe632007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel95fd7172007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel901f67e2007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
Devang Patelf4277122007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000024#include "llvm/ADT/Statistic.h"
25
26using namespace llvm;
27
28STATISTIC(NumIndexSplit, "Number of loops index split");
29
30namespace {
31
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34 public:
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
40
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
Devang Patel901f67e2007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelbc5fe632007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel0aaeb172007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patelf4277122007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel95fd7172007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel7f526a82007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Pateledea5b32007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000063
Devang Patelc8dadbf2007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patel5bc8a2c2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patelc8dadbf2007-08-08 21:02:17 +000069
Devang Patel7f526a82007-08-24 06:17:19 +000070 // True if after loop index split, first loop will execute split condition's
71 // true branch.
72 bool UseTrueBranchFirst;
Devang Pateledea5b32007-08-25 00:56:38 +000073
74 // Exit value for first loop after loop split.
75 Value *A_ExitValue;
76
77 // Start value for second loop after loop split.
78 Value *B_StartValue;
79
Devang Patel31696332007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel7f526a82007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Pateledea5b32007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000087 }
Devang Patel2545f7b2007-08-09 01:39:01 +000088
Devang Patelc8dadbf2007-08-08 21:02:17 +000089 };
Devang Patel61571ca2007-08-10 00:33:50 +000090
Devang Patelc8dadbf2007-08-08 21:02:17 +000091 private:
Devang Patel12564292007-09-11 00:42:56 +000092
93 // safeIcmpInst - CI is considered safe instruction if one of the operand
94 // is SCEVAddRecExpr based on induction variable and other operand is
95 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96 // and return true;
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
Devang Patelbc5fe632007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patel61571ca2007-08-10 00:33:50 +0000102 /// Find loop's exit condition.
103 void findLoopConditionals();
104
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
107
Devang Patelbc5fe632007-08-07 00:25:56 +0000108 /// processOneIterationLoop - Current loop L contains compare instruction
109 /// that compares induction variable, IndVar, agains loop invariant. If
110 /// entire (i.e. meaningful) loop body is dominated by this compare
111 /// instruction then loop body is executed only for one iteration. In
112 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patel4a8e6c62007-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 Patel0aaeb172007-08-08 22:25:28 +0000122 /// If loop header includes loop variant instruction operands then
123 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000124 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000125
Devang Patel9263fc32007-08-20 23:51:18 +0000126 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +0000127 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000128 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000129
Devang Patel60a94c72007-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 Patel6a2d6ef2007-08-12 07:02:51 +0000134
Devang Pateld662ace2007-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 Pateledea5b32007-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 Patelcd71bed2007-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,
154 PHINode *IV, Instruction *IVIncrement);
155
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 Pateld662ace2007-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 Patelc8dadbf2007-08-08 21:02:17 +0000163 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000164
Devang Patel61571ca2007-08-10 00:33:50 +0000165 void initialize() {
166 IndVar = NULL;
167 IndVarIncrement = NULL;
168 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000169 StartValue = NULL;
170 ExitValueNum = 0;
171 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000172 }
173
Devang Patelbc5fe632007-08-07 00:25:56 +0000174 private:
175
176 // Current Loop.
177 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000178 LPPassManager *LPM;
179 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000180 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000181 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000182 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000183 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-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 Patel6a2d6ef2007-08-12 07:02:51 +0000195 // Induction variable's final loop exit value operand number in exit condition..
196 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000197 };
198
199 char LoopIndexSplit::ID = 0;
200 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
201}
202
203LoopPass *llvm::createLoopIndexSplitPass() {
204 return new LoopIndexSplit();
205}
206
207// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000208bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000209 bool Changed = false;
210 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000211 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000212
Devang Patel81fcdfb2007-08-15 02:14:55 +0000213 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000214 if (!L->getSubLoops().empty())
215 return false;
216
Devang Patelbc5fe632007-08-07 00:25:56 +0000217 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000218 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000219 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000220 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000221
Devang Patel61571ca2007-08-10 00:33:50 +0000222 initialize();
223
224 findLoopConditionals();
225
226 if (!ExitCondition)
227 return false;
228
Devang Patelbc5fe632007-08-07 00:25:56 +0000229 findSplitCondition();
230
Devang Patelc8dadbf2007-08-08 21:02:17 +0000231 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000232 return false;
233
Devang Patelc8dadbf2007-08-08 21:02:17 +0000234 // First see if it is possible to eliminate loop itself or not.
235 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000236 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000237 SplitInfo &SD = *SI;
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000238 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
Devang Patel4a8e6c62007-09-17 20:39:48 +0000239 if (SD.SplitCondition->getOpcode() == Instruction::And) {
240 Changed = updateLoopIterationSpace(SD);
241 if (Changed) {
242 ++NumIndexSplit;
243 // If is loop is eliminated then nothing else to do here.
244 return Changed;
245 } else {
246 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
247 ++SI;
248 SplitData.erase(Delete_SI);
249 }
250 }
251 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000252 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-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 Patel49fbf5a2007-08-20 20:24:15 +0000257 } else {
258 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
259 ++SI;
260 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000261 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000262 } else
263 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000264 }
265
Devang Patel7f526a82007-08-24 06:17:19 +0000266 if (SplitData.empty())
267 return false;
268
Devang Patel0aaeb172007-08-08 22:25:28 +0000269 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000270 // FIXME : Implement cost analysis.
271 unsigned MostProfitableSDIndex = 0;
272 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000273
Devang Patelbc5fe632007-08-07 00:25:56 +0000274 if (Changed)
275 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000276
Devang Patelbc5fe632007-08-07 00:25:56 +0000277 return Changed;
278}
279
Devang Patel2545f7b2007-08-09 01:39:01 +0000280/// Return true if V is a induction variable or induction variable's
281/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000282void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000283
284 Instruction *I = dyn_cast<Instruction>(V);
285 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000286 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000287
288 // Check if I is a phi node from loop header or not.
289 if (PHINode *PN = dyn_cast<PHINode>(V)) {
290 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000291 IndVar = PN;
292 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000293 }
294 }
295
296 // Check if I is a add instruction whose one operand is
297 // phi node from loop header and second operand is constant.
298 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000299 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000300
301 Value *Op0 = I->getOperand(0);
302 Value *Op1 = I->getOperand(1);
303
304 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
305 if (PN->getParent() == L->getHeader()
306 && isa<ConstantInt>(Op1)) {
307 IndVar = PN;
308 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000309 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000310 }
311 }
312
313 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
314 if (PN->getParent() == L->getHeader()
315 && isa<ConstantInt>(Op0)) {
316 IndVar = PN;
317 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000318 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000319 }
320 }
321
Devang Patel61571ca2007-08-10 00:33:50 +0000322 return;
323}
324
325// Find loop's exit condition and associated induction variable.
326void LoopIndexSplit::findLoopConditionals() {
327
Devang Patel9263fc32007-08-20 23:51:18 +0000328 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000329
330 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
331 I != E; ++I) {
332 BasicBlock *BB = *I;
333 if (!L->isLoopExit(BB))
334 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000335 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000336 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000337 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000338 }
339
Devang Patel9263fc32007-08-20 23:51:18 +0000340 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000341 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000342
343 // If exiting block is neither loop header nor loop latch then this loop is
344 // not suitable.
345 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
346 return;
347
Devang Patel61571ca2007-08-10 00:33:50 +0000348 // If exit block's terminator is conditional branch inst then we have found
349 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000350 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000351 if (!BR || BR->isUnconditional())
352 return;
353
354 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
355 if (!CI)
356 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000357
Bill Wendlingd7bce7b2007-09-14 01:13:55 +0000358 // FIXME
Devang Patel74b660a2007-09-19 00:28:47 +0000359 if (CI->getPredicate() == ICmpInst::ICMP_EQ
Bill Wendlingd7bce7b2007-09-14 01:13:55 +0000360 || CI->getPredicate() == ICmpInst::ICMP_NE)
361 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000362
Devang Patel61571ca2007-08-10 00:33:50 +0000363 ExitCondition = CI;
364
365 // Exit condition's one operand is loop invariant exit value and second
366 // operand is SCEVAddRecExpr based on induction variable.
367 Value *V0 = CI->getOperand(0);
368 Value *V1 = CI->getOperand(1);
369
370 SCEVHandle SH0 = SE->getSCEV(V0);
371 SCEVHandle SH1 = SE->getSCEV(V1);
372
373 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000374 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000375 findIndVar(V1, L);
376 }
377 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000378 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000379 findIndVar(V0, L);
380 }
381
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000382 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000383 ExitCondition = NULL;
384 else if (IndVar) {
385 BasicBlock *Preheader = L->getLoopPreheader();
386 StartValue = IndVar->getIncomingValueForBlock(Preheader);
387 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000388}
389
Devang Patelbc5fe632007-08-07 00:25:56 +0000390/// Find condition inside a loop that is suitable candidate for index split.
391void LoopIndexSplit::findSplitCondition() {
392
Devang Patelc8dadbf2007-08-08 21:02:17 +0000393 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000394 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000395 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
396 I != E; ++I) {
Devang Pateld18971d2007-09-11 00:23:56 +0000397 SD.clear();
Devang Patel2545f7b2007-08-09 01:39:01 +0000398 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000399
Devang Patel2545f7b2007-08-09 01:39:01 +0000400 // If this basic block does not terminate in a conditional branch
401 // then terminator is not a suitable split condition.
402 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
403 if (!BR)
404 continue;
405
406 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000407 continue;
408
Devang Patel4a8e6c62007-09-17 20:39:48 +0000409 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
410 if (AndI->getOpcode() == Instruction::And) {
411 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
412 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
413
414 if (!Op0 || !Op1)
415 continue;
416
417 if (!safeICmpInst(Op0, SD))
418 continue;
419 SD.clear();
420 if (!safeICmpInst(Op1, SD))
421 continue;
422 SD.clear();
423 SD.SplitCondition = AndI;
424 SplitData.push_back(SD);
425 continue;
426 }
427 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000428 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000429 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000430 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000431
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000432 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000433 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000434
Devang Patel7f526a82007-08-24 06:17:19 +0000435 // If split condition predicate is GT or GE then first execute
436 // false branch of split condition.
Devang Patela3a23f62007-09-11 01:10:45 +0000437 if (CI->getPredicate() == ICmpInst::ICMP_UGT
438 || CI->getPredicate() == ICmpInst::ICMP_SGT
439 || CI->getPredicate() == ICmpInst::ICMP_UGE
440 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel7f526a82007-08-24 06:17:19 +0000441 SD.UseTrueBranchFirst = false;
442
Devang Patel2545f7b2007-08-09 01:39:01 +0000443 // If one operand is loop invariant and second operand is SCEVAddRecExpr
444 // based on induction variable then CI is a candidate split condition.
Devang Patel12564292007-09-11 00:42:56 +0000445 if (safeICmpInst(CI, SD))
446 SplitData.push_back(SD);
447 }
448}
Devang Patel2545f7b2007-08-09 01:39:01 +0000449
Devang Patel12564292007-09-11 00:42:56 +0000450// safeIcmpInst - CI is considered safe instruction if one of the operand
451// is SCEVAddRecExpr based on induction variable and other operand is
452// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
453// and return true;
454bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000455
Devang Patel12564292007-09-11 00:42:56 +0000456 Value *V0 = CI->getOperand(0);
457 Value *V1 = CI->getOperand(1);
458
459 SCEVHandle SH0 = SE->getSCEV(V0);
460 SCEVHandle SH1 = SE->getSCEV(V1);
461
462 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
463 SD.SplitValue = V0;
464 SD.SplitCondition = CI;
465 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
466 if (PN == IndVar)
467 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000468 }
Devang Patel12564292007-09-11 00:42:56 +0000469 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
470 if (IndVarIncrement && IndVarIncrement == Insn)
471 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000472 }
473 }
Devang Patel12564292007-09-11 00:42:56 +0000474 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
475 SD.SplitValue = V1;
476 SD.SplitCondition = CI;
477 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
478 if (PN == IndVar)
479 return true;
480 }
481 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
482 if (IndVarIncrement && IndVarIncrement == Insn)
483 return true;
484 }
485 }
486
487 return false;
Devang Patelbc5fe632007-08-07 00:25:56 +0000488}
489
490/// processOneIterationLoop - Current loop L contains compare instruction
491/// that compares induction variable, IndVar, against loop invariant. If
492/// entire (i.e. meaningful) loop body is dominated by this compare
493/// instruction then loop body is executed only once. In such case eliminate
494/// loop structure surrounding this loop body. For example,
495/// for (int i = start; i < end; ++i) {
496/// if ( i == somevalue) {
497/// loop_body
498/// }
499/// }
500/// can be transformed into
501/// if (somevalue >= start && somevalue < end) {
502/// i = somevalue;
503/// loop_body
504/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000505bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000506
507 BasicBlock *Header = L->getHeader();
508
509 // First of all, check if SplitCondition dominates entire loop body
510 // or not.
511
512 // If SplitCondition is not in loop header then this loop is not suitable
513 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000514 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000515 return false;
516
Devang Patelbc5fe632007-08-07 00:25:56 +0000517 // If loop header includes loop variant instruction operands then
518 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000519 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000520 return false;
521
Devang Patel9263fc32007-08-20 23:51:18 +0000522 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000523 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000524 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000525 return false;
526
Devang Patela3057832007-09-19 00:15:16 +0000527 // Filter loops where split condition's false branch is not empty.
528 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
529 return false;
530
Devang Patel3ebf4422007-09-17 21:01:05 +0000531 // If split condition is not safe then do not process this loop.
532 // For example,
533 // for(int i = 0; i < N; i++) {
534 // if ( i == XYZ) {
535 // A;
536 // else
537 // B;
538 // }
539 // C;
540 // D;
541 // }
542 if (!safeSplitCondition(SD))
543 return false;
544
Devang Patel09531c22007-09-19 00:11:01 +0000545 BasicBlock *Latch = L->getLoopLatch();
546 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
547 if (!BR)
548 return false;
549
Devang Patel2bcb5012007-08-08 01:51:27 +0000550 // Update CFG.
551
Devang Patelc166b952007-08-20 20:49:01 +0000552 // Replace index variable with split value in loop body. Loop body is executed
553 // only when index variable is equal to split value.
554 IndVar->replaceAllUsesWith(SD.SplitValue);
555
556 // Remove Latch to Header edge.
Devang Patel2bcb5012007-08-08 01:51:27 +0000557 BasicBlock *LatchSucc = NULL;
Devang Patel2bcb5012007-08-08 01:51:27 +0000558 Header->removePredecessor(Latch);
559 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
560 SI != E; ++SI) {
561 if (Header != *SI)
562 LatchSucc = *SI;
563 }
564 BR->setUnconditionalDest(LatchSucc);
565
Devang Patelbc5fe632007-08-07 00:25:56 +0000566 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000567 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000568
Devang Patelbc5fe632007-08-07 00:25:56 +0000569 // Replace split condition in header.
570 // Transform
571 // SplitCondition : icmp eq i32 IndVar, SplitValue
572 // into
573 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000574 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000575 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000576 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000577 Instruction *C1 = new ICmpInst(SignedPredicate ?
578 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000579 SD.SplitValue, StartValue, "lisplit",
580 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000581 Instruction *C2 = new ICmpInst(SignedPredicate ?
582 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000583 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000584 Terminator);
585 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
586 Terminator);
587 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
588 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000589
Devang Patelbc5fe632007-08-07 00:25:56 +0000590 // Now, clear latch block. Remove instructions that are responsible
591 // to increment induction variable.
592 Instruction *LTerminator = Latch->getTerminator();
593 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
594 LB != LE; ) {
595 Instruction *I = LB;
596 ++LB;
597 if (isa<PHINode>(I) || I == LTerminator)
598 continue;
599
Devang Patel59e0c062007-08-14 01:30:57 +0000600 if (I == IndVarIncrement)
601 I->replaceAllUsesWith(ExitValue);
602 else
603 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000604 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000605 }
606
Devang Patel901f67e2007-08-10 18:07:13 +0000607 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000608
609 // Update Dominator Info.
610 // Only CFG change done is to remove Latch to Header edge. This
611 // does not change dominator tree because Latch did not dominate
612 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000613 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000614 DominanceFrontier::iterator HeaderDF = DF->find(Header);
615 if (HeaderDF != DF->end())
616 DF->removeFromFrontier(HeaderDF, Header);
617
618 DominanceFrontier::iterator LatchDF = DF->find(Latch);
619 if (LatchDF != DF->end())
620 DF->removeFromFrontier(LatchDF, Header);
621 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000622 return true;
623}
624
625// If loop header includes loop variant instruction operands then
626// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000627bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000628
629 Instruction *Terminator = Header->getTerminator();
630 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
631 BI != BE; ++BI) {
632 Instruction *I = BI;
633
Devang Patel59e0c062007-08-14 01:30:57 +0000634 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000635 if (isa<PHINode>(I))
636 continue;
637
638 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000639 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000640 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000641
Devang Patel2545f7b2007-08-09 01:39:01 +0000642 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000643 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000644 continue;
645
646 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000647 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000648 continue;
649
Devang Patelbc5fe632007-08-07 00:25:56 +0000650 // Terminator is also harmless.
651 if (I == Terminator)
652 continue;
653
654 // Otherwise we have a instruction that may not be safe.
655 return false;
656 }
657
658 return true;
659}
660
Devang Patel9263fc32007-08-20 23:51:18 +0000661// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000662// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000663bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
664 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000665
Devang Patel9263fc32007-08-20 23:51:18 +0000666 for (BasicBlock::iterator BI = ExitingBlock->begin(),
667 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000668 Instruction *I = BI;
669
Devang Patel59e0c062007-08-14 01:30:57 +0000670 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000671 if (isa<PHINode>(I))
672 continue;
673
Devang Patel2545f7b2007-08-09 01:39:01 +0000674 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000675 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000676 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000677
Devang Patel2545f7b2007-08-09 01:39:01 +0000678 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000679 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000680
681 Value *Op0 = I->getOperand(0);
682 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000683 PHINode *PN = NULL;
684 ConstantInt *CI = NULL;
685
686 if ((PN = dyn_cast<PHINode>(Op0))) {
687 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000688 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000689 } else
690 if ((PN = dyn_cast<PHINode>(Op1))) {
691 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000692 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000693 }
694
Devang Patel61571ca2007-08-10 00:33:50 +0000695 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000696 continue;
697 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000698
Devang Patelbc5fe632007-08-07 00:25:56 +0000699 // I is an Exit condition if next instruction is block terminator.
700 // Exit condition is OK if it compares loop invariant exit value,
701 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000702 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000703 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000704 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000705 }
706
Devang Patel9263fc32007-08-20 23:51:18 +0000707 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000708 continue;
709
Devang Patelbc5fe632007-08-07 00:25:56 +0000710 // Otherwise we have instruction that may not be safe.
711 return false;
712 }
713
Devang Patel9263fc32007-08-20 23:51:18 +0000714 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000715 return true;
716}
717
Devang Patel4a8e6c62007-09-17 20:39:48 +0000718void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
719
720 Value *V0 = CI->getOperand(0);
721 Value *V1 = CI->getOperand(1);
722 Value *NV = NULL;
723
724 SCEVHandle SH0 = SE->getSCEV(V0);
725
726 if (SH0->isLoopInvariant(L))
727 NV = V0;
728 else
729 NV = V1;
730
731 switch (CI->getPredicate()) {
732 case ICmpInst::ICMP_ULE:
733 case ICmpInst::ICMP_SLE:
734 // for (i = LB; i < UB; ++i)
735 // if (i <= NV && ...)
736 // LOOP_BODY
737 //
738 // is transformed into
739 // NUB = min (NV+1, UB)
740 // for (i = LB; i < NUB ; ++i)
741 // LOOP_BODY
742 //
743
744
745
746 // for (i = LB; i <= UB; ++i)
747 // if (i <= NV && ...)
748 // LOOP_BODY
749 //
750 // is transformed into
751 // NUB = min (NV, UB)
752 // for (i = LB; i <= NUB ; ++i)
753 // LOOP_BODY
754 //
755 break;
756 case ICmpInst::ICMP_ULT:
757 case ICmpInst::ICMP_SLT:
758 // for (i = LB; i < UB; ++i)
759 // if (i < NV && ...)
760 // LOOP_BODY
761 //
762 // is transformed into
763 // NUB = min (NV, UB)
764 // for (i = LB; i < NUB ; ++i)
765 // LOOP_BODY
766 //
767
768
769
770 // for (i = LB; i <= UB; ++i)
771 // if (i < NV && ...)
772 // LOOP_BODY
773 //
774 // is transformed into
775 // NUB = min (NV -1 , UB)
776 // for (i = LB; i <= NUB ; ++i)
777 // LOOP_BODY
778 //
779 break;
780 case ICmpInst::ICMP_UGE:
781 case ICmpInst::ICMP_SGE:
782 // for (i = LB; i (< or <=) UB; ++i)
783 // if (i >= NV && ...)
784 // LOOP_BODY
785 //
786 // is transformed into
787 // NLB = max (NV, LB)
788 // for (i = NLB; i (< or <=) UB ; ++i)
789 // LOOP_BODY
790 //
791 break;
792 case ICmpInst::ICMP_UGT:
793 case ICmpInst::ICMP_SGT:
794 // for (i = LB; i (< or <=) UB; ++i)
795 // if (i > NV && ...)
796 // LOOP_BODY
797 //
798 // is transformed into
799 // NLB = max (NV+1, LB)
800 // for (i = NLB; i (< or <=) UB ; ++i)
801 // LOOP_BODY
802 //
803 break;
804 default:
805 assert ( 0 && "Unexpected split condition predicate");
806 }
807}
808/// updateLoopIterationSpace - Current loop body is covered by an AND
809/// instruction whose operands compares induction variables with loop
810/// invariants. If possible, hoist this check outside the loop by
811/// updating appropriate start and end values for induction variable.
812bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
813 BasicBlock *Header = L->getHeader();
814 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
815 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
816
817 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
818 || Op0->getPredicate() == ICmpInst::ICMP_NE
819 || Op0->getPredicate() == ICmpInst::ICMP_EQ
820 || Op0->getPredicate() == ICmpInst::ICMP_NE)
821 return false;
822
823 // Check if SplitCondition dominates entire loop body
824 // or not.
825
826 // If SplitCondition is not in loop header then this loop is not suitable
827 // for this transformation.
828 if (SD.SplitCondition->getParent() != Header)
829 return false;
830
831 // If loop header includes loop variant instruction operands then
832 // this loop may not be eliminated.
833 Instruction *Terminator = Header->getTerminator();
834 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
835 BI != BE; ++BI) {
836 Instruction *I = BI;
837
838 // PHI Nodes are OK.
839 if (isa<PHINode>(I))
840 continue;
841
842 // SplitCondition itself is OK.
843 if (I == SD.SplitCondition)
844 continue;
845 if (I == Op0 || I == Op1)
846 continue;
847
848 // Induction variable is OK.
849 if (I == IndVar)
850 continue;
851
852 // Induction variable increment is OK.
853 if (I == IndVarIncrement)
854 continue;
855
856 // Terminator is also harmless.
857 if (I == Terminator)
858 continue;
859
860 // Otherwise we have a instruction that may not be safe.
861 return false;
862 }
863
864 // If Exiting block includes loop variant instructions then this
865 // loop may not be eliminated.
866 if (!safeExitingBlock(SD, ExitCondition->getParent()))
867 return false;
868
869 updateLoopBounds(Op0);
870 updateLoopBounds(Op1);
871 // Update CFG
Devang Patelc8f83932007-09-19 00:08:13 +0000872 return false;
Devang Patel4a8e6c62007-09-17 20:39:48 +0000873}
874
875
Devang Patel60a94c72007-08-14 18:35:57 +0000876/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
877/// This routine is used to remove split condition's dead branch, dominated by
878/// DeadBB. LiveBB dominates split conidition's other branch.
879void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
880 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000881
Devang Patelf4277122007-08-15 03:31:47 +0000882 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000883 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000884 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
885 if (DeadBBDF != DF->end()) {
886 SmallVector<BasicBlock *, 8> PredBlocks;
887
888 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
889 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
890 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
891 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000892 FrontierBBs.push_back(FrontierBB);
893
Devang Patelf4277122007-08-15 03:31:47 +0000894 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
895 PredBlocks.clear();
896 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
897 PI != PE; ++PI) {
898 BasicBlock *P = *PI;
899 if (P == DeadBB || DT->dominates(DeadBB, P))
900 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000901 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000902
Devang Patelf4277122007-08-15 03:31:47 +0000903 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
904 FBI != FBE; ++FBI) {
905 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
906 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
907 PE = PredBlocks.end(); PI != PE; ++PI) {
908 BasicBlock *P = *PI;
909 PN->removeIncomingValue(P);
910 }
911 }
912 else
913 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000914 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000915 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000916 }
Devang Patelf4277122007-08-15 03:31:47 +0000917
918 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
919 SmallVector<BasicBlock *, 32> WorkList;
920 DomTreeNode *DN = DT->getNode(DeadBB);
921 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
922 E = df_end(DN); DI != E; ++DI) {
923 BasicBlock *BB = DI->getBlock();
924 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000925 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000926 }
927
928 while (!WorkList.empty()) {
929 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
930 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Patel577a61f2007-09-20 23:01:50 +0000931 BBI != BBE; ) {
Devang Patelf4277122007-08-15 03:31:47 +0000932 Instruction *I = BBI;
Devang Patel577a61f2007-09-20 23:01:50 +0000933 ++BBI;
Devang Patelf4277122007-08-15 03:31:47 +0000934 I->replaceAllUsesWith(UndefValue::get(I->getType()));
935 I->eraseFromParent();
936 }
937 LPM->deleteSimpleAnalysisValue(BB, LP);
938 DT->eraseNode(BB);
939 DF->removeBlock(BB);
940 LI->removeBlock(BB);
941 BB->eraseFromParent();
942 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000943
944 // Update Frontier BBs' dominator info.
945 while (!FrontierBBs.empty()) {
946 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
947 BasicBlock *NewDominator = FBB->getSinglePredecessor();
948 if (!NewDominator) {
949 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
950 NewDominator = *PI;
951 ++PI;
952 if (NewDominator != LiveBB) {
953 for(; PI != PE; ++PI) {
954 BasicBlock *P = *PI;
955 if (P == LiveBB) {
956 NewDominator = LiveBB;
957 break;
958 }
959 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
960 }
961 }
962 }
963 assert (NewDominator && "Unable to fix dominator info.");
964 DT->changeImmediateDominator(FBB, NewDominator);
965 DF->changeImmediateDominator(FBB, NewDominator, DT);
966 }
967
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000968}
969
Devang Pateld662ace2007-08-22 18:27:01 +0000970/// safeSplitCondition - Return true if it is possible to
971/// split loop using given split condition.
972bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000973
Devang Pateld662ace2007-08-22 18:27:01 +0000974 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel3ebf4422007-09-17 21:01:05 +0000975 BasicBlock *Latch = L->getLoopLatch();
Devang Pateld662ace2007-08-22 18:27:01 +0000976 BranchInst *SplitTerminator =
977 cast<BranchInst>(SplitCondBlock->getTerminator());
978 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
979 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel9cba64e2007-08-18 00:00:32 +0000980
Devang Patel4e2075d2007-08-24 05:36:56 +0000981 // Finally this split condition is safe only if merge point for
982 // split condition branch is loop latch. This check along with previous
983 // check, to ensure that exit condition is in either loop latch or header,
984 // filters all loops with non-empty loop body between merge point
985 // and exit condition.
986 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
987 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
988 if (Succ0DF->second.count(Latch))
989 return true;
990
991 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
992 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
993 if (Succ1DF->second.count(Latch))
994 return true;
995
996 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000997}
998
Devang Pateledea5b32007-08-25 00:56:38 +0000999/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1000/// based on split value.
1001void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1002
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001003 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1004 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +00001005 const Type *Ty = SD.SplitValue->getType();
1006 bool Sign = ExitCondition->isSignedPredicate();
1007 BasicBlock *Preheader = L->getLoopPreheader();
1008 Instruction *PHTerminator = Preheader->getTerminator();
1009
1010 // Initially use split value as upper loop bound for first loop and lower loop
1011 // bound for second loop.
1012 Value *AEV = SD.SplitValue;
1013 Value *BSV = SD.SplitValue;
1014
Devang Patel74b660a2007-09-19 00:28:47 +00001015 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1016 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1017 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1018 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)
1019 ExitCondition->swapOperands();
1020
Devang Pateledea5b32007-08-25 00:56:38 +00001021 switch (ExitCondition->getPredicate()) {
1022 case ICmpInst::ICMP_SGT:
1023 case ICmpInst::ICMP_UGT:
1024 case ICmpInst::ICMP_SGE:
1025 case ICmpInst::ICMP_UGE:
1026 default:
1027 assert (0 && "Unexpected exit condition predicate");
1028
1029 case ICmpInst::ICMP_SLT:
1030 case ICmpInst::ICMP_ULT:
1031 {
1032 switch (SP) {
1033 case ICmpInst::ICMP_SLT:
1034 case ICmpInst::ICMP_ULT:
1035 //
1036 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1037 //
1038 // is transformed into
1039 // AEV = BSV = SV
1040 // for (i = LB; i < min(UB, AEV); ++i)
1041 // A;
1042 // for (i = max(LB, BSV); i < UB; ++i);
1043 // B;
1044 break;
1045 case ICmpInst::ICMP_SLE:
1046 case ICmpInst::ICMP_ULE:
1047 {
1048 //
1049 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1050 //
1051 // is transformed into
1052 //
1053 // AEV = SV + 1
1054 // BSV = SV + 1
1055 // for (i = LB; i < min(UB, AEV); ++i)
1056 // A;
1057 // for (i = max(LB, BSV); i < UB; ++i)
1058 // B;
1059 BSV = BinaryOperator::createAdd(SD.SplitValue,
1060 ConstantInt::get(Ty, 1, Sign),
1061 "lsplit.add", PHTerminator);
1062 AEV = BSV;
1063 }
1064 break;
1065 case ICmpInst::ICMP_SGE:
1066 case ICmpInst::ICMP_UGE:
1067 //
1068 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1069 //
1070 // is transformed into
1071 // AEV = BSV = SV
1072 // for (i = LB; i < min(UB, AEV); ++i)
1073 // B;
1074 // for (i = max(BSV, LB); i < UB; ++i)
1075 // A;
1076 break;
1077 case ICmpInst::ICMP_SGT:
1078 case ICmpInst::ICMP_UGT:
1079 {
1080 //
1081 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1082 //
1083 // is transformed into
1084 //
1085 // BSV = AEV = SV + 1
1086 // for (i = LB; i < min(UB, AEV); ++i)
1087 // B;
1088 // for (i = max(LB, BSV); i < UB; ++i)
1089 // A;
1090 BSV = BinaryOperator::createAdd(SD.SplitValue,
1091 ConstantInt::get(Ty, 1, Sign),
1092 "lsplit.add", PHTerminator);
1093 AEV = BSV;
1094 }
1095 break;
1096 default:
1097 assert (0 && "Unexpected split condition predicate");
1098 break;
1099 } // end switch (SP)
1100 }
1101 break;
1102 case ICmpInst::ICMP_SLE:
1103 case ICmpInst::ICMP_ULE:
1104 {
1105 switch (SP) {
1106 case ICmpInst::ICMP_SLT:
1107 case ICmpInst::ICMP_ULT:
1108 //
1109 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1110 //
1111 // is transformed into
1112 // AEV = SV - 1;
1113 // BSV = SV;
1114 // for (i = LB; i <= min(UB, AEV); ++i)
1115 // A;
1116 // for (i = max(LB, BSV); i <= UB; ++i)
1117 // B;
1118 AEV = BinaryOperator::createSub(SD.SplitValue,
1119 ConstantInt::get(Ty, 1, Sign),
1120 "lsplit.sub", PHTerminator);
1121 break;
1122 case ICmpInst::ICMP_SLE:
1123 case ICmpInst::ICMP_ULE:
1124 //
1125 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1126 //
1127 // is transformed into
1128 // AEV = SV;
1129 // BSV = SV + 1;
1130 // for (i = LB; i <= min(UB, AEV); ++i)
1131 // A;
1132 // for (i = max(LB, BSV); i <= UB; ++i)
1133 // B;
1134 BSV = BinaryOperator::createAdd(SD.SplitValue,
1135 ConstantInt::get(Ty, 1, Sign),
1136 "lsplit.add", PHTerminator);
1137 break;
1138 case ICmpInst::ICMP_SGT:
1139 case ICmpInst::ICMP_UGT:
1140 //
1141 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1142 //
1143 // is transformed into
1144 // AEV = SV;
1145 // BSV = SV + 1;
1146 // for (i = LB; i <= min(AEV, UB); ++i)
1147 // B;
1148 // for (i = max(LB, BSV); i <= UB; ++i)
1149 // A;
1150 BSV = BinaryOperator::createAdd(SD.SplitValue,
1151 ConstantInt::get(Ty, 1, Sign),
1152 "lsplit.add", PHTerminator);
1153 break;
1154 case ICmpInst::ICMP_SGE:
1155 case ICmpInst::ICMP_UGE:
1156 // ** TODO **
1157 //
1158 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1159 //
1160 // is transformed into
1161 // AEV = SV - 1;
1162 // BSV = SV;
1163 // for (i = LB; i <= min(AEV, UB); ++i)
1164 // B;
1165 // for (i = max(LB, BSV); i <= UB; ++i)
1166 // A;
1167 AEV = BinaryOperator::createSub(SD.SplitValue,
1168 ConstantInt::get(Ty, 1, Sign),
1169 "lsplit.sub", PHTerminator);
1170 break;
1171 default:
1172 assert (0 && "Unexpected split condition predicate");
1173 break;
1174 } // end switch (SP)
1175 }
1176 break;
1177 }
1178
1179 // Calculate ALoop induction variable's new exiting value and
1180 // BLoop induction variable's new starting value. Calculuate these
1181 // values in original loop's preheader.
1182 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1183 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel058c67a2007-09-21 21:18:19 +00001184 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Pateledea5b32007-08-25 00:56:38 +00001185 Value *C1 = new ICmpInst(Sign ?
1186 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1187 AEV,
1188 ExitCondition->getOperand(ExitValueNum),
Devang Patel058c67a2007-09-21 21:18:19 +00001189 "lsplit.ev", InsertPt);
1190
Devang Pateledea5b32007-08-25 00:56:38 +00001191 SD.A_ExitValue = new SelectInst(C1, AEV,
1192 ExitCondition->getOperand(ExitValueNum),
Devang Patel058c67a2007-09-21 21:18:19 +00001193 "lsplit.ev", InsertPt);
1194
Devang Pateledea5b32007-08-25 00:56:38 +00001195 Value *C2 = new ICmpInst(Sign ?
1196 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1197 BSV, StartValue, "lsplit.sv",
1198 PHTerminator);
1199 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1200 "lsplit.sv", PHTerminator);
1201}
1202
Devang Pateld662ace2007-08-22 18:27:01 +00001203/// splitLoop - Split current loop L in two loops using split information
1204/// SD. Update dominator information. Maintain LCSSA form.
1205bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1206
1207 if (!safeSplitCondition(SD))
1208 return false;
1209
Devang Patel3ebf4422007-09-17 21:01:05 +00001210 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1211
1212 // Unable to handle triange loops at the moment.
1213 // In triangle loop, split condition is in header and one of the
1214 // the split destination is loop latch. If split condition is EQ
1215 // then such loops are already handle in processOneIterationLoop().
1216 BasicBlock *Latch = L->getLoopLatch();
1217 BranchInst *SplitTerminator =
1218 cast<BranchInst>(SplitCondBlock->getTerminator());
1219 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1220 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1221 if (L->getHeader() == SplitCondBlock
1222 && (Latch == Succ0 || Latch == Succ1))
1223 return false;
1224
1225 // If split condition branches heads do not have single predecessor,
1226 // SplitCondBlock, then is not possible to remove inactive branch.
1227 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1228 return false;
1229
Devang Patela0ac7262007-08-22 19:33:29 +00001230 // After loop is cloned there are two loops.
1231 //
1232 // First loop, referred as ALoop, executes first part of loop's iteration
1233 // space split. Second loop, referred as BLoop, executes remaining
1234 // part of loop's iteration space.
1235 //
1236 // ALoop's exit edge enters BLoop's header through a forwarding block which
1237 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001238 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001239
Devang Pateledea5b32007-08-25 00:56:38 +00001240 // Calculate ALoop induction variable's new exiting value and
1241 // BLoop induction variable's new starting value.
1242 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001243
Devang Patela0ac7262007-08-22 19:33:29 +00001244 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001245 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001246 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001247 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001248 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001249
Devang Patela0ac7262007-08-22 19:33:29 +00001250 //[*] ALoop's exiting edge BLoop's header.
1251 // ALoop's original exit block becomes BLoop's exit block.
1252 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1253 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1254 BranchInst *A_ExitInsn =
1255 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1256 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1257 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1258 if (L->contains(B_ExitBlock)) {
1259 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1260 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001261 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001262 A_ExitInsn->setSuccessor(1, B_Header);
1263
1264 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001265 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001266
Devang Patela0ac7262007-08-22 19:33:29 +00001267 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1268 // original loop's preheader. Add incoming PHINode values from
1269 // ALoop's exiting block. Update BLoop header's domiantor info.
1270
Devang Patel59e0c062007-08-14 01:30:57 +00001271 // Collect inverse map of Header PHINodes.
1272 DenseMap<Value *, Value *> InverseMap;
1273 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1274 BE = L->getHeader()->end(); BI != BE; ++BI) {
1275 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1276 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1277 InverseMap[PNClone] = PN;
1278 } else
1279 break;
1280 }
Devang Pateledea5b32007-08-25 00:56:38 +00001281
Devang Patela0ac7262007-08-22 19:33:29 +00001282 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001283 BI != BE; ++BI) {
1284 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001285 // Remove incoming value from original preheader.
1286 PN->removeIncomingValue(Preheader);
1287
1288 // Add incoming value from A_ExitingBlock.
1289 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001290 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001291 else {
1292 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001293 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1294 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001295 }
1296 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001297 break;
1298 }
Devang Patela0ac7262007-08-22 19:33:29 +00001299 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1300 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001301
Devang Patela0ac7262007-08-22 19:33:29 +00001302 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1303 // block. Remove incoming PHINode values from ALoop's exiting block.
1304 // Add new incoming values from BLoop's incoming exiting value.
1305 // Update BLoop exit block's dominator info..
1306 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1307 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001308 BI != BE; ++BI) {
1309 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001310 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1311 B_ExitingBlock);
1312 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001313 } else
1314 break;
1315 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001316
Devang Patela0ac7262007-08-22 19:33:29 +00001317 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1318 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001319
Devang Patela0ac7262007-08-22 19:33:29 +00001320 //[*] Split ALoop's exit edge. This creates a new block which
1321 // serves two purposes. First one is to hold PHINode defnitions
1322 // to ensure that ALoop's LCSSA form. Second use it to act
1323 // as a preheader for BLoop.
1324 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001325
Devang Patela0ac7262007-08-22 19:33:29 +00001326 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1327 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1328 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001329 BI != BE; ++BI) {
1330 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001331 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001332 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001333 newPHI->addIncoming(V1, A_ExitingBlock);
1334 A_ExitBlock->getInstList().push_front(newPHI);
1335 PN->removeIncomingValue(A_ExitBlock);
1336 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001337 } else
1338 break;
1339 }
1340
Devang Patela0ac7262007-08-22 19:33:29 +00001341 //[*] Eliminate split condition's inactive branch from ALoop.
1342 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1343 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001344 BasicBlock *A_InactiveBranch = NULL;
1345 BasicBlock *A_ActiveBranch = NULL;
1346 if (SD.UseTrueBranchFirst) {
1347 A_ActiveBranch = A_BR->getSuccessor(0);
1348 A_InactiveBranch = A_BR->getSuccessor(1);
1349 } else {
1350 A_ActiveBranch = A_BR->getSuccessor(1);
1351 A_InactiveBranch = A_BR->getSuccessor(0);
1352 }
Devang Patel4e585c72007-08-24 19:32:26 +00001353 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001354 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1355
1356 //[*] Eliminate split condition's inactive branch in from BLoop.
1357 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1358 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001359 BasicBlock *B_InactiveBranch = NULL;
1360 BasicBlock *B_ActiveBranch = NULL;
1361 if (SD.UseTrueBranchFirst) {
1362 B_ActiveBranch = B_BR->getSuccessor(1);
1363 B_InactiveBranch = B_BR->getSuccessor(0);
1364 } else {
1365 B_ActiveBranch = B_BR->getSuccessor(0);
1366 B_InactiveBranch = B_BR->getSuccessor(1);
1367 }
Devang Patel4e585c72007-08-24 19:32:26 +00001368 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001369 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1370
Devang Patelcd71bed2007-08-25 02:39:24 +00001371 BasicBlock *A_Header = L->getHeader();
1372 if (A_ExitingBlock == A_Header)
1373 return true;
1374
1375 //[*] Move exit condition into split condition block to avoid
1376 // executing dead loop iteration.
1377 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1378 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1379 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1380
1381 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001382 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1383 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001384
1385 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1386 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1387
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001388 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001389}
Devang Patelcd71bed2007-08-25 02:39:24 +00001390
1391// moveExitCondition - Move exit condition EC into split condition block CondBB.
1392void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1393 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1394 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1395
1396 BasicBlock *ExitingBB = EC->getParent();
1397 Instruction *CurrentBR = CondBB->getTerminator();
1398
1399 // Move exit condition into split condition block.
1400 EC->moveBefore(CurrentBR);
1401 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1402
1403 // Move exiting block's branch into split condition block. Update its branch
1404 // destination.
1405 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1406 ExitingBR->moveBefore(CurrentBR);
1407 if (ExitingBR->getSuccessor(0) == ExitBB)
1408 ExitingBR->setSuccessor(1, ActiveBB);
1409 else
1410 ExitingBR->setSuccessor(0, ActiveBB);
1411
1412 // Remove split condition and current split condition branch.
1413 SC->eraseFromParent();
1414 CurrentBR->eraseFromParent();
1415
1416 // Connect exiting block to split condition block.
1417 new BranchInst(CondBB, ExitingBB);
1418
1419 // Update PHINodes
1420 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1421
1422 // Fix dominator info.
1423 // ExitBB is now dominated by CondBB
1424 DT->changeImmediateDominator(ExitBB, CondBB);
1425 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1426
1427 // Basicblocks dominated by ActiveBB may have ExitingBB or
1428 // a basic block outside the loop in their DF list. If so,
1429 // replace it with CondBB.
1430 DomTreeNode *Node = DT->getNode(ActiveBB);
1431 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1432 DI != DE; ++DI) {
1433 BasicBlock *BB = DI->getBlock();
1434 DominanceFrontier::iterator BBDF = DF->find(BB);
1435 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1436 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1437 while (DomSetI != DomSetE) {
1438 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1439 ++DomSetI;
1440 BasicBlock *DFBB = *CurrentItr;
1441 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1442 BBDF->second.erase(DFBB);
1443 BBDF->second.insert(CondBB);
1444 }
1445 }
1446 }
1447}
1448
1449/// updatePHINodes - CFG has been changed.
1450/// Before
1451/// - ExitBB's single predecessor was Latch
1452/// - Latch's second successor was Header
1453/// Now
1454/// - ExitBB's single predecessor was Header
1455/// - Latch's one and only successor was Header
1456///
1457/// Update ExitBB PHINodes' to reflect this change.
1458void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1459 BasicBlock *Header,
1460 PHINode *IV, Instruction *IVIncrement) {
1461
1462 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1463 BI != BE; ++BI) {
1464 PHINode *PN = dyn_cast<PHINode>(BI);
1465 if (!PN)
1466 break;
1467
1468 Value *V = PN->getIncomingValueForBlock(Latch);
1469 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1470 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1471 // (i.e. PN :)).
1472 // The second use is in Header and it is new incoming value for PN.
1473 PHINode *U1 = NULL;
1474 PHINode *U2 = NULL;
1475 Value *NewV = NULL;
1476 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1477 UI != E; ++UI) {
1478 if (!U1)
1479 U1 = cast<PHINode>(*UI);
1480 else if (!U2)
1481 U2 = cast<PHINode>(*UI);
1482 else
1483 assert ( 0 && "Unexpected third use of this PHINode");
1484 }
1485 assert (U1 && U2 && "Unable to find two uses");
1486
1487 if (U1->getParent() == Header)
1488 NewV = U1;
1489 else
1490 NewV = U2;
1491 PN->addIncoming(NewV, Header);
1492
1493 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1494 // If this instruction is IVIncrement then IV is new incoming value
1495 // from header otherwise this instruction must be incoming value from
1496 // header because loop is in LCSSA form.
1497 if (PHI == IVIncrement)
1498 PN->addIncoming(IV, Header);
1499 else
1500 PN->addIncoming(V, Header);
1501 } else
1502 // Otherwise this is an incoming value from header because loop is in
1503 // LCSSA form.
1504 PN->addIncoming(V, Header);
1505
1506 // Remove incoming value from Latch.
1507 PN->removeIncomingValue(Latch);
1508 }
1509}