blob: cb5060a676540f82e425587acd83914552c660da [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 Pateledea5b32007-08-25 00:56:38 +0000359 if (CI->getPredicate() == ICmpInst::ICMP_SGT
360 || CI->getPredicate() == ICmpInst::ICMP_UGT
361 || CI->getPredicate() == ICmpInst::ICMP_SGE
Bill Wendlingd7bce7b2007-09-14 01:13:55 +0000362 || CI->getPredicate() == ICmpInst::ICMP_UGE
363 || CI->getPredicate() == ICmpInst::ICMP_EQ
364 || CI->getPredicate() == ICmpInst::ICMP_NE)
365 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000366
Devang Patel61571ca2007-08-10 00:33:50 +0000367 ExitCondition = CI;
368
369 // Exit condition's one operand is loop invariant exit value and second
370 // operand is SCEVAddRecExpr based on induction variable.
371 Value *V0 = CI->getOperand(0);
372 Value *V1 = CI->getOperand(1);
373
374 SCEVHandle SH0 = SE->getSCEV(V0);
375 SCEVHandle SH1 = SE->getSCEV(V1);
376
377 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000378 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000379 findIndVar(V1, L);
380 }
381 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000382 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000383 findIndVar(V0, L);
384 }
385
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000386 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000387 ExitCondition = NULL;
388 else if (IndVar) {
389 BasicBlock *Preheader = L->getLoopPreheader();
390 StartValue = IndVar->getIncomingValueForBlock(Preheader);
391 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000392}
393
Devang Patelbc5fe632007-08-07 00:25:56 +0000394/// Find condition inside a loop that is suitable candidate for index split.
395void LoopIndexSplit::findSplitCondition() {
396
Devang Patelc8dadbf2007-08-08 21:02:17 +0000397 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000398 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000399 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
400 I != E; ++I) {
Devang Pateld18971d2007-09-11 00:23:56 +0000401 SD.clear();
Devang Patel2545f7b2007-08-09 01:39:01 +0000402 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000403
Devang Patel2545f7b2007-08-09 01:39:01 +0000404 // If this basic block does not terminate in a conditional branch
405 // then terminator is not a suitable split condition.
406 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
407 if (!BR)
408 continue;
409
410 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000411 continue;
412
Devang Patel4a8e6c62007-09-17 20:39:48 +0000413 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
414 if (AndI->getOpcode() == Instruction::And) {
415 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
416 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
417
418 if (!Op0 || !Op1)
419 continue;
420
421 if (!safeICmpInst(Op0, SD))
422 continue;
423 SD.clear();
424 if (!safeICmpInst(Op1, SD))
425 continue;
426 SD.clear();
427 SD.SplitCondition = AndI;
428 SplitData.push_back(SD);
429 continue;
430 }
431 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000432 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000433 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000434 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000435
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000436 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000437 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000438
Devang Patel7f526a82007-08-24 06:17:19 +0000439 // If split condition predicate is GT or GE then first execute
440 // false branch of split condition.
Devang Patela3a23f62007-09-11 01:10:45 +0000441 if (CI->getPredicate() == ICmpInst::ICMP_UGT
442 || CI->getPredicate() == ICmpInst::ICMP_SGT
443 || CI->getPredicate() == ICmpInst::ICMP_UGE
444 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel7f526a82007-08-24 06:17:19 +0000445 SD.UseTrueBranchFirst = false;
446
Devang Patel2545f7b2007-08-09 01:39:01 +0000447 // If one operand is loop invariant and second operand is SCEVAddRecExpr
448 // based on induction variable then CI is a candidate split condition.
Devang Patel12564292007-09-11 00:42:56 +0000449 if (safeICmpInst(CI, SD))
450 SplitData.push_back(SD);
451 }
452}
Devang Patel2545f7b2007-08-09 01:39:01 +0000453
Devang Patel12564292007-09-11 00:42:56 +0000454// safeIcmpInst - CI is considered safe instruction if one of the operand
455// is SCEVAddRecExpr based on induction variable and other operand is
456// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
457// and return true;
458bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000459
Devang Patel12564292007-09-11 00:42:56 +0000460 Value *V0 = CI->getOperand(0);
461 Value *V1 = CI->getOperand(1);
462
463 SCEVHandle SH0 = SE->getSCEV(V0);
464 SCEVHandle SH1 = SE->getSCEV(V1);
465
466 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
467 SD.SplitValue = V0;
468 SD.SplitCondition = CI;
469 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
470 if (PN == IndVar)
471 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000472 }
Devang Patel12564292007-09-11 00:42:56 +0000473 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
474 if (IndVarIncrement && IndVarIncrement == Insn)
475 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000476 }
477 }
Devang Patel12564292007-09-11 00:42:56 +0000478 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
479 SD.SplitValue = V1;
480 SD.SplitCondition = CI;
481 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
482 if (PN == IndVar)
483 return true;
484 }
485 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
486 if (IndVarIncrement && IndVarIncrement == Insn)
487 return true;
488 }
489 }
490
491 return false;
Devang Patelbc5fe632007-08-07 00:25:56 +0000492}
493
494/// processOneIterationLoop - Current loop L contains compare instruction
495/// that compares induction variable, IndVar, against loop invariant. If
496/// entire (i.e. meaningful) loop body is dominated by this compare
497/// instruction then loop body is executed only once. In such case eliminate
498/// loop structure surrounding this loop body. For example,
499/// for (int i = start; i < end; ++i) {
500/// if ( i == somevalue) {
501/// loop_body
502/// }
503/// }
504/// can be transformed into
505/// if (somevalue >= start && somevalue < end) {
506/// i = somevalue;
507/// loop_body
508/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000509bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000510
511 BasicBlock *Header = L->getHeader();
512
513 // First of all, check if SplitCondition dominates entire loop body
514 // or not.
515
516 // If SplitCondition is not in loop header then this loop is not suitable
517 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000518 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000519 return false;
520
Devang Patelbc5fe632007-08-07 00:25:56 +0000521 // If loop header includes loop variant instruction operands then
522 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000523 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000524 return false;
525
Devang Patel9263fc32007-08-20 23:51:18 +0000526 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000527 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000528 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000529 return false;
530
Devang Patela3057832007-09-19 00:15:16 +0000531 // Filter loops where split condition's false branch is not empty.
532 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
533 return false;
534
Devang Patel3ebf4422007-09-17 21:01:05 +0000535 // If split condition is not safe then do not process this loop.
536 // For example,
537 // for(int i = 0; i < N; i++) {
538 // if ( i == XYZ) {
539 // A;
540 // else
541 // B;
542 // }
543 // C;
544 // D;
545 // }
546 if (!safeSplitCondition(SD))
547 return false;
548
Devang Patel09531c22007-09-19 00:11:01 +0000549 BasicBlock *Latch = L->getLoopLatch();
550 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
551 if (!BR)
552 return false;
553
Devang Patel2bcb5012007-08-08 01:51:27 +0000554 // Update CFG.
555
Devang Patelc166b952007-08-20 20:49:01 +0000556 // Replace index variable with split value in loop body. Loop body is executed
557 // only when index variable is equal to split value.
558 IndVar->replaceAllUsesWith(SD.SplitValue);
559
560 // Remove Latch to Header edge.
Devang Patel2bcb5012007-08-08 01:51:27 +0000561 BasicBlock *LatchSucc = NULL;
Devang Patel2bcb5012007-08-08 01:51:27 +0000562 Header->removePredecessor(Latch);
563 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
564 SI != E; ++SI) {
565 if (Header != *SI)
566 LatchSucc = *SI;
567 }
568 BR->setUnconditionalDest(LatchSucc);
569
Devang Patelbc5fe632007-08-07 00:25:56 +0000570 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000571 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000572
Devang Patelbc5fe632007-08-07 00:25:56 +0000573 // Replace split condition in header.
574 // Transform
575 // SplitCondition : icmp eq i32 IndVar, SplitValue
576 // into
577 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000578 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000579 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000580 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000581 Instruction *C1 = new ICmpInst(SignedPredicate ?
582 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000583 SD.SplitValue, StartValue, "lisplit",
584 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000585 Instruction *C2 = new ICmpInst(SignedPredicate ?
586 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000587 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000588 Terminator);
589 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
590 Terminator);
591 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
592 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000593
Devang Patelbc5fe632007-08-07 00:25:56 +0000594 // Now, clear latch block. Remove instructions that are responsible
595 // to increment induction variable.
596 Instruction *LTerminator = Latch->getTerminator();
597 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
598 LB != LE; ) {
599 Instruction *I = LB;
600 ++LB;
601 if (isa<PHINode>(I) || I == LTerminator)
602 continue;
603
Devang Patel59e0c062007-08-14 01:30:57 +0000604 if (I == IndVarIncrement)
605 I->replaceAllUsesWith(ExitValue);
606 else
607 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000608 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000609 }
610
Devang Patel901f67e2007-08-10 18:07:13 +0000611 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000612
613 // Update Dominator Info.
614 // Only CFG change done is to remove Latch to Header edge. This
615 // does not change dominator tree because Latch did not dominate
616 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000617 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000618 DominanceFrontier::iterator HeaderDF = DF->find(Header);
619 if (HeaderDF != DF->end())
620 DF->removeFromFrontier(HeaderDF, Header);
621
622 DominanceFrontier::iterator LatchDF = DF->find(Latch);
623 if (LatchDF != DF->end())
624 DF->removeFromFrontier(LatchDF, Header);
625 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000626 return true;
627}
628
629// If loop header includes loop variant instruction operands then
630// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000631bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000632
633 Instruction *Terminator = Header->getTerminator();
634 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
635 BI != BE; ++BI) {
636 Instruction *I = BI;
637
Devang Patel59e0c062007-08-14 01:30:57 +0000638 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000639 if (isa<PHINode>(I))
640 continue;
641
642 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000643 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000644 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000645
Devang Patel2545f7b2007-08-09 01:39:01 +0000646 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000647 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000648 continue;
649
650 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000651 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000652 continue;
653
Devang Patelbc5fe632007-08-07 00:25:56 +0000654 // Terminator is also harmless.
655 if (I == Terminator)
656 continue;
657
658 // Otherwise we have a instruction that may not be safe.
659 return false;
660 }
661
662 return true;
663}
664
Devang Patel9263fc32007-08-20 23:51:18 +0000665// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000666// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000667bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
668 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000669
Devang Patel9263fc32007-08-20 23:51:18 +0000670 for (BasicBlock::iterator BI = ExitingBlock->begin(),
671 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000672 Instruction *I = BI;
673
Devang Patel59e0c062007-08-14 01:30:57 +0000674 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000675 if (isa<PHINode>(I))
676 continue;
677
Devang Patel2545f7b2007-08-09 01:39:01 +0000678 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000679 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000680 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000681
Devang Patel2545f7b2007-08-09 01:39:01 +0000682 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000683 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000684
685 Value *Op0 = I->getOperand(0);
686 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000687 PHINode *PN = NULL;
688 ConstantInt *CI = NULL;
689
690 if ((PN = dyn_cast<PHINode>(Op0))) {
691 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000692 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000693 } else
694 if ((PN = dyn_cast<PHINode>(Op1))) {
695 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000696 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000697 }
698
Devang Patel61571ca2007-08-10 00:33:50 +0000699 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000700 continue;
701 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000702
Devang Patelbc5fe632007-08-07 00:25:56 +0000703 // I is an Exit condition if next instruction is block terminator.
704 // Exit condition is OK if it compares loop invariant exit value,
705 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000706 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000707 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000708 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000709 }
710
Devang Patel9263fc32007-08-20 23:51:18 +0000711 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000712 continue;
713
Devang Patelbc5fe632007-08-07 00:25:56 +0000714 // Otherwise we have instruction that may not be safe.
715 return false;
716 }
717
Devang Patel9263fc32007-08-20 23:51:18 +0000718 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000719 return true;
720}
721
Devang Patel4a8e6c62007-09-17 20:39:48 +0000722void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
723
724 Value *V0 = CI->getOperand(0);
725 Value *V1 = CI->getOperand(1);
726 Value *NV = NULL;
727
728 SCEVHandle SH0 = SE->getSCEV(V0);
729
730 if (SH0->isLoopInvariant(L))
731 NV = V0;
732 else
733 NV = V1;
734
735 switch (CI->getPredicate()) {
736 case ICmpInst::ICMP_ULE:
737 case ICmpInst::ICMP_SLE:
738 // for (i = LB; i < UB; ++i)
739 // if (i <= NV && ...)
740 // LOOP_BODY
741 //
742 // is transformed into
743 // NUB = min (NV+1, UB)
744 // for (i = LB; i < NUB ; ++i)
745 // LOOP_BODY
746 //
747
748
749
750 // for (i = LB; i <= UB; ++i)
751 // if (i <= NV && ...)
752 // LOOP_BODY
753 //
754 // is transformed into
755 // NUB = min (NV, UB)
756 // for (i = LB; i <= NUB ; ++i)
757 // LOOP_BODY
758 //
759 break;
760 case ICmpInst::ICMP_ULT:
761 case ICmpInst::ICMP_SLT:
762 // for (i = LB; i < UB; ++i)
763 // if (i < NV && ...)
764 // LOOP_BODY
765 //
766 // is transformed into
767 // NUB = min (NV, UB)
768 // for (i = LB; i < NUB ; ++i)
769 // LOOP_BODY
770 //
771
772
773
774 // for (i = LB; i <= UB; ++i)
775 // if (i < NV && ...)
776 // LOOP_BODY
777 //
778 // is transformed into
779 // NUB = min (NV -1 , UB)
780 // for (i = LB; i <= NUB ; ++i)
781 // LOOP_BODY
782 //
783 break;
784 case ICmpInst::ICMP_UGE:
785 case ICmpInst::ICMP_SGE:
786 // for (i = LB; i (< or <=) UB; ++i)
787 // if (i >= NV && ...)
788 // LOOP_BODY
789 //
790 // is transformed into
791 // NLB = max (NV, LB)
792 // for (i = NLB; i (< or <=) UB ; ++i)
793 // LOOP_BODY
794 //
795 break;
796 case ICmpInst::ICMP_UGT:
797 case ICmpInst::ICMP_SGT:
798 // for (i = LB; i (< or <=) UB; ++i)
799 // if (i > NV && ...)
800 // LOOP_BODY
801 //
802 // is transformed into
803 // NLB = max (NV+1, LB)
804 // for (i = NLB; i (< or <=) UB ; ++i)
805 // LOOP_BODY
806 //
807 break;
808 default:
809 assert ( 0 && "Unexpected split condition predicate");
810 }
811}
812/// updateLoopIterationSpace - Current loop body is covered by an AND
813/// instruction whose operands compares induction variables with loop
814/// invariants. If possible, hoist this check outside the loop by
815/// updating appropriate start and end values for induction variable.
816bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
817 BasicBlock *Header = L->getHeader();
818 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
819 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
820
821 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
822 || Op0->getPredicate() == ICmpInst::ICMP_NE
823 || Op0->getPredicate() == ICmpInst::ICMP_EQ
824 || Op0->getPredicate() == ICmpInst::ICMP_NE)
825 return false;
826
827 // Check if SplitCondition dominates entire loop body
828 // or not.
829
830 // If SplitCondition is not in loop header then this loop is not suitable
831 // for this transformation.
832 if (SD.SplitCondition->getParent() != Header)
833 return false;
834
835 // If loop header includes loop variant instruction operands then
836 // this loop may not be eliminated.
837 Instruction *Terminator = Header->getTerminator();
838 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
839 BI != BE; ++BI) {
840 Instruction *I = BI;
841
842 // PHI Nodes are OK.
843 if (isa<PHINode>(I))
844 continue;
845
846 // SplitCondition itself is OK.
847 if (I == SD.SplitCondition)
848 continue;
849 if (I == Op0 || I == Op1)
850 continue;
851
852 // Induction variable is OK.
853 if (I == IndVar)
854 continue;
855
856 // Induction variable increment is OK.
857 if (I == IndVarIncrement)
858 continue;
859
860 // Terminator is also harmless.
861 if (I == Terminator)
862 continue;
863
864 // Otherwise we have a instruction that may not be safe.
865 return false;
866 }
867
868 // If Exiting block includes loop variant instructions then this
869 // loop may not be eliminated.
870 if (!safeExitingBlock(SD, ExitCondition->getParent()))
871 return false;
872
873 updateLoopBounds(Op0);
874 updateLoopBounds(Op1);
875 // Update CFG
Devang Patelc8f83932007-09-19 00:08:13 +0000876 return false;
Devang Patel4a8e6c62007-09-17 20:39:48 +0000877}
878
879
Devang Patel60a94c72007-08-14 18:35:57 +0000880/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
881/// This routine is used to remove split condition's dead branch, dominated by
882/// DeadBB. LiveBB dominates split conidition's other branch.
883void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
884 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000885
Devang Patelf4277122007-08-15 03:31:47 +0000886 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000887 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000888 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
889 if (DeadBBDF != DF->end()) {
890 SmallVector<BasicBlock *, 8> PredBlocks;
891
892 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
893 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
894 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
895 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000896 FrontierBBs.push_back(FrontierBB);
897
Devang Patelf4277122007-08-15 03:31:47 +0000898 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
899 PredBlocks.clear();
900 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
901 PI != PE; ++PI) {
902 BasicBlock *P = *PI;
903 if (P == DeadBB || DT->dominates(DeadBB, P))
904 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000905 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000906
Devang Patelf4277122007-08-15 03:31:47 +0000907 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
908 FBI != FBE; ++FBI) {
909 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
910 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
911 PE = PredBlocks.end(); PI != PE; ++PI) {
912 BasicBlock *P = *PI;
913 PN->removeIncomingValue(P);
914 }
915 }
916 else
917 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000918 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000919 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000920 }
Devang Patelf4277122007-08-15 03:31:47 +0000921
922 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
923 SmallVector<BasicBlock *, 32> WorkList;
924 DomTreeNode *DN = DT->getNode(DeadBB);
925 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
926 E = df_end(DN); DI != E; ++DI) {
927 BasicBlock *BB = DI->getBlock();
928 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000929 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000930 }
931
932 while (!WorkList.empty()) {
933 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
934 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
935 BBI != BBE; ++BBI) {
936 Instruction *I = BBI;
937 I->replaceAllUsesWith(UndefValue::get(I->getType()));
938 I->eraseFromParent();
939 }
940 LPM->deleteSimpleAnalysisValue(BB, LP);
941 DT->eraseNode(BB);
942 DF->removeBlock(BB);
943 LI->removeBlock(BB);
944 BB->eraseFromParent();
945 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000946
947 // Update Frontier BBs' dominator info.
948 while (!FrontierBBs.empty()) {
949 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
950 BasicBlock *NewDominator = FBB->getSinglePredecessor();
951 if (!NewDominator) {
952 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
953 NewDominator = *PI;
954 ++PI;
955 if (NewDominator != LiveBB) {
956 for(; PI != PE; ++PI) {
957 BasicBlock *P = *PI;
958 if (P == LiveBB) {
959 NewDominator = LiveBB;
960 break;
961 }
962 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
963 }
964 }
965 }
966 assert (NewDominator && "Unable to fix dominator info.");
967 DT->changeImmediateDominator(FBB, NewDominator);
968 DF->changeImmediateDominator(FBB, NewDominator, DT);
969 }
970
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000971}
972
Devang Pateld662ace2007-08-22 18:27:01 +0000973/// safeSplitCondition - Return true if it is possible to
974/// split loop using given split condition.
975bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000976
Devang Pateld662ace2007-08-22 18:27:01 +0000977 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel3ebf4422007-09-17 21:01:05 +0000978 BasicBlock *Latch = L->getLoopLatch();
Devang Pateld662ace2007-08-22 18:27:01 +0000979 BranchInst *SplitTerminator =
980 cast<BranchInst>(SplitCondBlock->getTerminator());
981 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
982 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel9cba64e2007-08-18 00:00:32 +0000983
Devang Patel4e2075d2007-08-24 05:36:56 +0000984 // Finally this split condition is safe only if merge point for
985 // split condition branch is loop latch. This check along with previous
986 // check, to ensure that exit condition is in either loop latch or header,
987 // filters all loops with non-empty loop body between merge point
988 // and exit condition.
989 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
990 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
991 if (Succ0DF->second.count(Latch))
992 return true;
993
994 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
995 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
996 if (Succ1DF->second.count(Latch))
997 return true;
998
999 return false;
Devang Pateld662ace2007-08-22 18:27:01 +00001000}
1001
Devang Pateledea5b32007-08-25 00:56:38 +00001002/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1003/// based on split value.
1004void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1005
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001006 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1007 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +00001008 const Type *Ty = SD.SplitValue->getType();
1009 bool Sign = ExitCondition->isSignedPredicate();
1010 BasicBlock *Preheader = L->getLoopPreheader();
1011 Instruction *PHTerminator = Preheader->getTerminator();
1012
1013 // Initially use split value as upper loop bound for first loop and lower loop
1014 // bound for second loop.
1015 Value *AEV = SD.SplitValue;
1016 Value *BSV = SD.SplitValue;
1017
1018 switch (ExitCondition->getPredicate()) {
1019 case ICmpInst::ICMP_SGT:
1020 case ICmpInst::ICMP_UGT:
1021 case ICmpInst::ICMP_SGE:
1022 case ICmpInst::ICMP_UGE:
1023 default:
1024 assert (0 && "Unexpected exit condition predicate");
1025
1026 case ICmpInst::ICMP_SLT:
1027 case ICmpInst::ICMP_ULT:
1028 {
1029 switch (SP) {
1030 case ICmpInst::ICMP_SLT:
1031 case ICmpInst::ICMP_ULT:
1032 //
1033 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1034 //
1035 // is transformed into
1036 // AEV = BSV = SV
1037 // for (i = LB; i < min(UB, AEV); ++i)
1038 // A;
1039 // for (i = max(LB, BSV); i < UB; ++i);
1040 // B;
1041 break;
1042 case ICmpInst::ICMP_SLE:
1043 case ICmpInst::ICMP_ULE:
1044 {
1045 //
1046 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1047 //
1048 // is transformed into
1049 //
1050 // AEV = SV + 1
1051 // BSV = SV + 1
1052 // for (i = LB; i < min(UB, AEV); ++i)
1053 // A;
1054 // for (i = max(LB, BSV); i < UB; ++i)
1055 // B;
1056 BSV = BinaryOperator::createAdd(SD.SplitValue,
1057 ConstantInt::get(Ty, 1, Sign),
1058 "lsplit.add", PHTerminator);
1059 AEV = BSV;
1060 }
1061 break;
1062 case ICmpInst::ICMP_SGE:
1063 case ICmpInst::ICMP_UGE:
1064 //
1065 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1066 //
1067 // is transformed into
1068 // AEV = BSV = SV
1069 // for (i = LB; i < min(UB, AEV); ++i)
1070 // B;
1071 // for (i = max(BSV, LB); i < UB; ++i)
1072 // A;
1073 break;
1074 case ICmpInst::ICMP_SGT:
1075 case ICmpInst::ICMP_UGT:
1076 {
1077 //
1078 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1079 //
1080 // is transformed into
1081 //
1082 // BSV = AEV = SV + 1
1083 // for (i = LB; i < min(UB, AEV); ++i)
1084 // B;
1085 // for (i = max(LB, BSV); i < UB; ++i)
1086 // A;
1087 BSV = BinaryOperator::createAdd(SD.SplitValue,
1088 ConstantInt::get(Ty, 1, Sign),
1089 "lsplit.add", PHTerminator);
1090 AEV = BSV;
1091 }
1092 break;
1093 default:
1094 assert (0 && "Unexpected split condition predicate");
1095 break;
1096 } // end switch (SP)
1097 }
1098 break;
1099 case ICmpInst::ICMP_SLE:
1100 case ICmpInst::ICMP_ULE:
1101 {
1102 switch (SP) {
1103 case ICmpInst::ICMP_SLT:
1104 case ICmpInst::ICMP_ULT:
1105 //
1106 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1107 //
1108 // is transformed into
1109 // AEV = SV - 1;
1110 // BSV = SV;
1111 // for (i = LB; i <= min(UB, AEV); ++i)
1112 // A;
1113 // for (i = max(LB, BSV); i <= UB; ++i)
1114 // B;
1115 AEV = BinaryOperator::createSub(SD.SplitValue,
1116 ConstantInt::get(Ty, 1, Sign),
1117 "lsplit.sub", PHTerminator);
1118 break;
1119 case ICmpInst::ICMP_SLE:
1120 case ICmpInst::ICMP_ULE:
1121 //
1122 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1123 //
1124 // is transformed into
1125 // AEV = SV;
1126 // BSV = SV + 1;
1127 // for (i = LB; i <= min(UB, AEV); ++i)
1128 // A;
1129 // for (i = max(LB, BSV); i <= UB; ++i)
1130 // B;
1131 BSV = BinaryOperator::createAdd(SD.SplitValue,
1132 ConstantInt::get(Ty, 1, Sign),
1133 "lsplit.add", PHTerminator);
1134 break;
1135 case ICmpInst::ICMP_SGT:
1136 case ICmpInst::ICMP_UGT:
1137 //
1138 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1139 //
1140 // is transformed into
1141 // AEV = SV;
1142 // BSV = SV + 1;
1143 // for (i = LB; i <= min(AEV, UB); ++i)
1144 // B;
1145 // for (i = max(LB, BSV); i <= UB; ++i)
1146 // A;
1147 BSV = BinaryOperator::createAdd(SD.SplitValue,
1148 ConstantInt::get(Ty, 1, Sign),
1149 "lsplit.add", PHTerminator);
1150 break;
1151 case ICmpInst::ICMP_SGE:
1152 case ICmpInst::ICMP_UGE:
1153 // ** TODO **
1154 //
1155 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1156 //
1157 // is transformed into
1158 // AEV = SV - 1;
1159 // BSV = SV;
1160 // for (i = LB; i <= min(AEV, UB); ++i)
1161 // B;
1162 // for (i = max(LB, BSV); i <= UB; ++i)
1163 // A;
1164 AEV = BinaryOperator::createSub(SD.SplitValue,
1165 ConstantInt::get(Ty, 1, Sign),
1166 "lsplit.sub", PHTerminator);
1167 break;
1168 default:
1169 assert (0 && "Unexpected split condition predicate");
1170 break;
1171 } // end switch (SP)
1172 }
1173 break;
1174 }
1175
1176 // Calculate ALoop induction variable's new exiting value and
1177 // BLoop induction variable's new starting value. Calculuate these
1178 // values in original loop's preheader.
1179 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1180 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +00001181 Value *C1 = new ICmpInst(Sign ?
1182 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1183 AEV,
1184 ExitCondition->getOperand(ExitValueNum),
1185 "lsplit.ev", PHTerminator);
1186 SD.A_ExitValue = new SelectInst(C1, AEV,
1187 ExitCondition->getOperand(ExitValueNum),
1188 "lsplit.ev", PHTerminator);
1189
1190 Value *C2 = new ICmpInst(Sign ?
1191 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1192 BSV, StartValue, "lsplit.sv",
1193 PHTerminator);
1194 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1195 "lsplit.sv", PHTerminator);
1196}
1197
Devang Pateld662ace2007-08-22 18:27:01 +00001198/// splitLoop - Split current loop L in two loops using split information
1199/// SD. Update dominator information. Maintain LCSSA form.
1200bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1201
1202 if (!safeSplitCondition(SD))
1203 return false;
1204
Devang Patel3ebf4422007-09-17 21:01:05 +00001205 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1206
1207 // Unable to handle triange loops at the moment.
1208 // In triangle loop, split condition is in header and one of the
1209 // the split destination is loop latch. If split condition is EQ
1210 // then such loops are already handle in processOneIterationLoop().
1211 BasicBlock *Latch = L->getLoopLatch();
1212 BranchInst *SplitTerminator =
1213 cast<BranchInst>(SplitCondBlock->getTerminator());
1214 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1215 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1216 if (L->getHeader() == SplitCondBlock
1217 && (Latch == Succ0 || Latch == Succ1))
1218 return false;
1219
1220 // If split condition branches heads do not have single predecessor,
1221 // SplitCondBlock, then is not possible to remove inactive branch.
1222 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1223 return false;
1224
Devang Patela0ac7262007-08-22 19:33:29 +00001225 // After loop is cloned there are two loops.
1226 //
1227 // First loop, referred as ALoop, executes first part of loop's iteration
1228 // space split. Second loop, referred as BLoop, executes remaining
1229 // part of loop's iteration space.
1230 //
1231 // ALoop's exit edge enters BLoop's header through a forwarding block which
1232 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001233 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001234
Devang Pateledea5b32007-08-25 00:56:38 +00001235 // Calculate ALoop induction variable's new exiting value and
1236 // BLoop induction variable's new starting value.
1237 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001238
Devang Patela0ac7262007-08-22 19:33:29 +00001239 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001240 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001241 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001242 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001243 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001244
Devang Patela0ac7262007-08-22 19:33:29 +00001245 //[*] ALoop's exiting edge BLoop's header.
1246 // ALoop's original exit block becomes BLoop's exit block.
1247 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1248 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1249 BranchInst *A_ExitInsn =
1250 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1251 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1252 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1253 if (L->contains(B_ExitBlock)) {
1254 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1255 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001256 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001257 A_ExitInsn->setSuccessor(1, B_Header);
1258
1259 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001260 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001261
Devang Patela0ac7262007-08-22 19:33:29 +00001262 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1263 // original loop's preheader. Add incoming PHINode values from
1264 // ALoop's exiting block. Update BLoop header's domiantor info.
1265
Devang Patel59e0c062007-08-14 01:30:57 +00001266 // Collect inverse map of Header PHINodes.
1267 DenseMap<Value *, Value *> InverseMap;
1268 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1269 BE = L->getHeader()->end(); BI != BE; ++BI) {
1270 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1271 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1272 InverseMap[PNClone] = PN;
1273 } else
1274 break;
1275 }
Devang Pateledea5b32007-08-25 00:56:38 +00001276
Devang Patela0ac7262007-08-22 19:33:29 +00001277 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001278 BI != BE; ++BI) {
1279 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001280 // Remove incoming value from original preheader.
1281 PN->removeIncomingValue(Preheader);
1282
1283 // Add incoming value from A_ExitingBlock.
1284 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001285 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001286 else {
1287 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001288 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1289 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001290 }
1291 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001292 break;
1293 }
Devang Patela0ac7262007-08-22 19:33:29 +00001294 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1295 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001296
Devang Patela0ac7262007-08-22 19:33:29 +00001297 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1298 // block. Remove incoming PHINode values from ALoop's exiting block.
1299 // Add new incoming values from BLoop's incoming exiting value.
1300 // Update BLoop exit block's dominator info..
1301 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1302 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001303 BI != BE; ++BI) {
1304 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001305 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1306 B_ExitingBlock);
1307 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001308 } else
1309 break;
1310 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001311
Devang Patela0ac7262007-08-22 19:33:29 +00001312 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1313 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001314
Devang Patela0ac7262007-08-22 19:33:29 +00001315 //[*] Split ALoop's exit edge. This creates a new block which
1316 // serves two purposes. First one is to hold PHINode defnitions
1317 // to ensure that ALoop's LCSSA form. Second use it to act
1318 // as a preheader for BLoop.
1319 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001320
Devang Patela0ac7262007-08-22 19:33:29 +00001321 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1322 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1323 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001324 BI != BE; ++BI) {
1325 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001326 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001327 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001328 newPHI->addIncoming(V1, A_ExitingBlock);
1329 A_ExitBlock->getInstList().push_front(newPHI);
1330 PN->removeIncomingValue(A_ExitBlock);
1331 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001332 } else
1333 break;
1334 }
1335
Devang Patela0ac7262007-08-22 19:33:29 +00001336 //[*] Eliminate split condition's inactive branch from ALoop.
1337 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1338 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001339 BasicBlock *A_InactiveBranch = NULL;
1340 BasicBlock *A_ActiveBranch = NULL;
1341 if (SD.UseTrueBranchFirst) {
1342 A_ActiveBranch = A_BR->getSuccessor(0);
1343 A_InactiveBranch = A_BR->getSuccessor(1);
1344 } else {
1345 A_ActiveBranch = A_BR->getSuccessor(1);
1346 A_InactiveBranch = A_BR->getSuccessor(0);
1347 }
Devang Patel4e585c72007-08-24 19:32:26 +00001348 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001349 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1350
1351 //[*] Eliminate split condition's inactive branch in from BLoop.
1352 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1353 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001354 BasicBlock *B_InactiveBranch = NULL;
1355 BasicBlock *B_ActiveBranch = NULL;
1356 if (SD.UseTrueBranchFirst) {
1357 B_ActiveBranch = B_BR->getSuccessor(1);
1358 B_InactiveBranch = B_BR->getSuccessor(0);
1359 } else {
1360 B_ActiveBranch = B_BR->getSuccessor(0);
1361 B_InactiveBranch = B_BR->getSuccessor(1);
1362 }
Devang Patel4e585c72007-08-24 19:32:26 +00001363 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001364 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1365
Devang Patelcd71bed2007-08-25 02:39:24 +00001366 BasicBlock *A_Header = L->getHeader();
1367 if (A_ExitingBlock == A_Header)
1368 return true;
1369
1370 //[*] Move exit condition into split condition block to avoid
1371 // executing dead loop iteration.
1372 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1373 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1374 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1375
1376 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001377 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1378 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001379
1380 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1381 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1382
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001383 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001384}
Devang Patelcd71bed2007-08-25 02:39:24 +00001385
1386// moveExitCondition - Move exit condition EC into split condition block CondBB.
1387void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1388 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1389 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1390
1391 BasicBlock *ExitingBB = EC->getParent();
1392 Instruction *CurrentBR = CondBB->getTerminator();
1393
1394 // Move exit condition into split condition block.
1395 EC->moveBefore(CurrentBR);
1396 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1397
1398 // Move exiting block's branch into split condition block. Update its branch
1399 // destination.
1400 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1401 ExitingBR->moveBefore(CurrentBR);
1402 if (ExitingBR->getSuccessor(0) == ExitBB)
1403 ExitingBR->setSuccessor(1, ActiveBB);
1404 else
1405 ExitingBR->setSuccessor(0, ActiveBB);
1406
1407 // Remove split condition and current split condition branch.
1408 SC->eraseFromParent();
1409 CurrentBR->eraseFromParent();
1410
1411 // Connect exiting block to split condition block.
1412 new BranchInst(CondBB, ExitingBB);
1413
1414 // Update PHINodes
1415 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1416
1417 // Fix dominator info.
1418 // ExitBB is now dominated by CondBB
1419 DT->changeImmediateDominator(ExitBB, CondBB);
1420 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1421
1422 // Basicblocks dominated by ActiveBB may have ExitingBB or
1423 // a basic block outside the loop in their DF list. If so,
1424 // replace it with CondBB.
1425 DomTreeNode *Node = DT->getNode(ActiveBB);
1426 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1427 DI != DE; ++DI) {
1428 BasicBlock *BB = DI->getBlock();
1429 DominanceFrontier::iterator BBDF = DF->find(BB);
1430 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1431 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1432 while (DomSetI != DomSetE) {
1433 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1434 ++DomSetI;
1435 BasicBlock *DFBB = *CurrentItr;
1436 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1437 BBDF->second.erase(DFBB);
1438 BBDF->second.insert(CondBB);
1439 }
1440 }
1441 }
1442}
1443
1444/// updatePHINodes - CFG has been changed.
1445/// Before
1446/// - ExitBB's single predecessor was Latch
1447/// - Latch's second successor was Header
1448/// Now
1449/// - ExitBB's single predecessor was Header
1450/// - Latch's one and only successor was Header
1451///
1452/// Update ExitBB PHINodes' to reflect this change.
1453void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1454 BasicBlock *Header,
1455 PHINode *IV, Instruction *IVIncrement) {
1456
1457 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1458 BI != BE; ++BI) {
1459 PHINode *PN = dyn_cast<PHINode>(BI);
1460 if (!PN)
1461 break;
1462
1463 Value *V = PN->getIncomingValueForBlock(Latch);
1464 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1465 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1466 // (i.e. PN :)).
1467 // The second use is in Header and it is new incoming value for PN.
1468 PHINode *U1 = NULL;
1469 PHINode *U2 = NULL;
1470 Value *NewV = NULL;
1471 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1472 UI != E; ++UI) {
1473 if (!U1)
1474 U1 = cast<PHINode>(*UI);
1475 else if (!U2)
1476 U2 = cast<PHINode>(*UI);
1477 else
1478 assert ( 0 && "Unexpected third use of this PHINode");
1479 }
1480 assert (U1 && U2 && "Unable to find two uses");
1481
1482 if (U1->getParent() == Header)
1483 NewV = U1;
1484 else
1485 NewV = U2;
1486 PN->addIncoming(NewV, Header);
1487
1488 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1489 // If this instruction is IVIncrement then IV is new incoming value
1490 // from header otherwise this instruction must be incoming value from
1491 // header because loop is in LCSSA form.
1492 if (PHI == IVIncrement)
1493 PN->addIncoming(IV, Header);
1494 else
1495 PN->addIncoming(V, Header);
1496 } else
1497 // Otherwise this is an incoming value from header because loop is in
1498 // LCSSA form.
1499 PN->addIncoming(V, Header);
1500
1501 // Remove incoming value from Latch.
1502 PN->removeIncomingValue(Latch);
1503 }
1504}