blob: 145741f85ed2a011317225d560d2090e1bef32d6 [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 Patel61571ca2007-08-10 00:33:50 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000061
Devang Patelc8dadbf2007-08-08 21:02:17 +000062 // Induction variable's range is split at this value.
63 Value *SplitValue;
64
Devang Patelc8dadbf2007-08-08 21:02:17 +000065 // This compare instruction compares IndVar against SplitValue.
66 ICmpInst *SplitCondition;
67
Devang Patel31696332007-08-08 21:18:27 +000068 // Clear split info.
69 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000070 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000071 SplitCondition = NULL;
Devang Patel31696332007-08-08 21:18:27 +000072 }
Devang Patel2545f7b2007-08-09 01:39:01 +000073
Devang Patelc8dadbf2007-08-08 21:02:17 +000074 };
Devang Patel61571ca2007-08-10 00:33:50 +000075
Devang Patelc8dadbf2007-08-08 21:02:17 +000076 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000077 /// Find condition inside a loop that is suitable candidate for index split.
78 void findSplitCondition();
79
Devang Patel61571ca2007-08-10 00:33:50 +000080 /// Find loop's exit condition.
81 void findLoopConditionals();
82
83 /// Return induction variable associated with value V.
84 void findIndVar(Value *V, Loop *L);
85
Devang Patelbc5fe632007-08-07 00:25:56 +000086 /// processOneIterationLoop - Current loop L contains compare instruction
87 /// that compares induction variable, IndVar, agains loop invariant. If
88 /// entire (i.e. meaningful) loop body is dominated by this compare
89 /// instruction then loop body is executed only for one iteration. In
90 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +000091 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +000092
Devang Patel0aaeb172007-08-08 22:25:28 +000093 /// If loop header includes loop variant instruction operands then
94 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000095 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000096
Devang Patel9263fc32007-08-20 23:51:18 +000097 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +000098 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +000099 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000100
Devang Patel60a94c72007-08-14 18:35:57 +0000101 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
102 /// This routine is used to remove split condition's dead branch, dominated by
103 /// DeadBB. LiveBB dominates split conidition's other branch.
104 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000105
Devang Patel0aaeb172007-08-08 22:25:28 +0000106 /// Find cost of spliting loop L.
107 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Pateld662ace2007-08-22 18:27:01 +0000108
109 /// safeSplitCondition - Return true if it is possible to
110 /// split loop using given split condition.
111 bool safeSplitCondition(SplitInfo &SD);
112
113 /// splitLoop - Split current loop L in two loops using split information
114 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000115 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000116
Devang Patel61571ca2007-08-10 00:33:50 +0000117 void initialize() {
118 IndVar = NULL;
119 IndVarIncrement = NULL;
120 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000121 StartValue = NULL;
122 ExitValueNum = 0;
123 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000124 }
125
Devang Patelbc5fe632007-08-07 00:25:56 +0000126 private:
127
128 // Current Loop.
129 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000130 LPPassManager *LPM;
131 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000132 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000133 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000134 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000135 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000136
137 // Induction variable whose range is being split by this transformation.
138 PHINode *IndVar;
139 Instruction *IndVarIncrement;
140
141 // Loop exit condition.
142 ICmpInst *ExitCondition;
143
144 // Induction variable's initial value.
145 Value *StartValue;
146
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000147 // Induction variable's final loop exit value operand number in exit condition..
148 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000149 };
150
151 char LoopIndexSplit::ID = 0;
152 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
153}
154
155LoopPass *llvm::createLoopIndexSplitPass() {
156 return new LoopIndexSplit();
157}
158
159// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000160bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000161 bool Changed = false;
162 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000163 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000164
Devang Patel81fcdfb2007-08-15 02:14:55 +0000165 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000166 if (!L->getSubLoops().empty())
167 return false;
168
Devang Patelbc5fe632007-08-07 00:25:56 +0000169 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000170 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000171 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000172 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000173
Devang Patel61571ca2007-08-10 00:33:50 +0000174 initialize();
175
176 findLoopConditionals();
177
178 if (!ExitCondition)
179 return false;
180
Devang Patelbc5fe632007-08-07 00:25:56 +0000181 findSplitCondition();
182
Devang Patelc8dadbf2007-08-08 21:02:17 +0000183 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000184 return false;
185
Devang Patelc8dadbf2007-08-08 21:02:17 +0000186 // First see if it is possible to eliminate loop itself or not.
187 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000188 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000189 SplitInfo &SD = *SI;
190 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000191 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000192 if (Changed) {
193 ++NumIndexSplit;
194 // If is loop is eliminated then nothing else to do here.
195 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000196 } else {
197 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
198 ++SI;
199 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000200 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000201 } else
202 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000203 }
204
Devang Patel0aaeb172007-08-08 22:25:28 +0000205 unsigned MaxCost = 99;
206 unsigned Index = 0;
207 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000208 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000209 E = SplitData.end(); SI != E; ++SI, ++Index) {
210 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000211
212 // ICM_EQs are already handled above.
Devang Patel49fbf5a2007-08-20 20:24:15 +0000213 assert (SD.SplitCondition->getPredicate() != ICmpInst::ICMP_EQ &&
214 "Unexpected split condition predicate");
Devang Patel0aaeb172007-08-08 22:25:28 +0000215
216 unsigned Cost = findSplitCost(L, SD);
217 if (Cost < MaxCost)
218 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000219 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000220
Devang Patel0aaeb172007-08-08 22:25:28 +0000221 // Split most profitiable condition.
Devang Patel49fbf5a2007-08-20 20:24:15 +0000222 if (!SplitData.empty())
223 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000224
Devang Patelbc5fe632007-08-07 00:25:56 +0000225 if (Changed)
226 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000227
Devang Patelbc5fe632007-08-07 00:25:56 +0000228 return Changed;
229}
230
Devang Patel2545f7b2007-08-09 01:39:01 +0000231/// Return true if V is a induction variable or induction variable's
232/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000233void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000234
235 Instruction *I = dyn_cast<Instruction>(V);
236 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000237 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000238
239 // Check if I is a phi node from loop header or not.
240 if (PHINode *PN = dyn_cast<PHINode>(V)) {
241 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000242 IndVar = PN;
243 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000244 }
245 }
246
247 // Check if I is a add instruction whose one operand is
248 // phi node from loop header and second operand is constant.
249 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000250 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000251
252 Value *Op0 = I->getOperand(0);
253 Value *Op1 = I->getOperand(1);
254
255 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
256 if (PN->getParent() == L->getHeader()
257 && isa<ConstantInt>(Op1)) {
258 IndVar = PN;
259 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000260 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000261 }
262 }
263
264 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
265 if (PN->getParent() == L->getHeader()
266 && isa<ConstantInt>(Op0)) {
267 IndVar = PN;
268 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000269 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000270 }
271 }
272
Devang Patel61571ca2007-08-10 00:33:50 +0000273 return;
274}
275
276// Find loop's exit condition and associated induction variable.
277void LoopIndexSplit::findLoopConditionals() {
278
Devang Patel9263fc32007-08-20 23:51:18 +0000279 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000280
281 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
282 I != E; ++I) {
283 BasicBlock *BB = *I;
284 if (!L->isLoopExit(BB))
285 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000286 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000287 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000288 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000289 }
290
Devang Patel9263fc32007-08-20 23:51:18 +0000291 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000292 return;
293
294 // If exit block's terminator is conditional branch inst then we have found
295 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000296 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000297 if (!BR || BR->isUnconditional())
298 return;
299
300 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
301 if (!CI)
302 return;
303
304 ExitCondition = CI;
305
306 // Exit condition's one operand is loop invariant exit value and second
307 // operand is SCEVAddRecExpr based on induction variable.
308 Value *V0 = CI->getOperand(0);
309 Value *V1 = CI->getOperand(1);
310
311 SCEVHandle SH0 = SE->getSCEV(V0);
312 SCEVHandle SH1 = SE->getSCEV(V1);
313
314 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000315 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000316 findIndVar(V1, L);
317 }
318 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000319 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000320 findIndVar(V0, L);
321 }
322
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000323 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000324 ExitCondition = NULL;
325 else if (IndVar) {
326 BasicBlock *Preheader = L->getLoopPreheader();
327 StartValue = IndVar->getIncomingValueForBlock(Preheader);
328 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000329}
330
Devang Patelbc5fe632007-08-07 00:25:56 +0000331/// Find condition inside a loop that is suitable candidate for index split.
332void LoopIndexSplit::findSplitCondition() {
333
Devang Patelc8dadbf2007-08-08 21:02:17 +0000334 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000335 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000336
Devang Patel2545f7b2007-08-09 01:39:01 +0000337 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
338 I != E; ++I) {
339 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000340
Devang Patel2545f7b2007-08-09 01:39:01 +0000341 // If this basic block does not terminate in a conditional branch
342 // then terminator is not a suitable split condition.
343 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
344 if (!BR)
345 continue;
346
347 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000348 continue;
349
Devang Patel2545f7b2007-08-09 01:39:01 +0000350 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000351 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000352 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000353
Devang Patel2545f7b2007-08-09 01:39:01 +0000354 // If one operand is loop invariant and second operand is SCEVAddRecExpr
355 // based on induction variable then CI is a candidate split condition.
356 Value *V0 = CI->getOperand(0);
357 Value *V1 = CI->getOperand(1);
358
359 SCEVHandle SH0 = SE->getSCEV(V0);
360 SCEVHandle SH1 = SE->getSCEV(V1);
361
362 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
363 SD.SplitValue = V0;
364 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000365 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
366 if (PN == IndVar)
367 SplitData.push_back(SD);
368 }
369 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
370 if (IndVarIncrement && IndVarIncrement == Insn)
371 SplitData.push_back(SD);
372 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000373 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000374 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
375 SD.SplitValue = V1;
376 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000377 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
378 if (PN == IndVar)
379 SplitData.push_back(SD);
380 }
381 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
382 if (IndVarIncrement && IndVarIncrement == Insn)
383 SplitData.push_back(SD);
384 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000385 }
386 }
387}
388
389/// processOneIterationLoop - Current loop L contains compare instruction
390/// that compares induction variable, IndVar, against loop invariant. If
391/// entire (i.e. meaningful) loop body is dominated by this compare
392/// instruction then loop body is executed only once. In such case eliminate
393/// loop structure surrounding this loop body. For example,
394/// for (int i = start; i < end; ++i) {
395/// if ( i == somevalue) {
396/// loop_body
397/// }
398/// }
399/// can be transformed into
400/// if (somevalue >= start && somevalue < end) {
401/// i = somevalue;
402/// loop_body
403/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000404bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000405
406 BasicBlock *Header = L->getHeader();
407
408 // First of all, check if SplitCondition dominates entire loop body
409 // or not.
410
411 // If SplitCondition is not in loop header then this loop is not suitable
412 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000413 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000414 return false;
415
Devang Patelbc5fe632007-08-07 00:25:56 +0000416 // If loop header includes loop variant instruction operands then
417 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000418 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000419 return false;
420
Devang Patel9263fc32007-08-20 23:51:18 +0000421 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000422 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000423 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000424 return false;
425
Devang Patel2bcb5012007-08-08 01:51:27 +0000426 // Update CFG.
427
Devang Patelc166b952007-08-20 20:49:01 +0000428 // Replace index variable with split value in loop body. Loop body is executed
429 // only when index variable is equal to split value.
430 IndVar->replaceAllUsesWith(SD.SplitValue);
431
432 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000433 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000434 BasicBlock *LatchSucc = NULL;
435 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
436 if (!BR)
437 return false;
438 Header->removePredecessor(Latch);
439 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
440 SI != E; ++SI) {
441 if (Header != *SI)
442 LatchSucc = *SI;
443 }
444 BR->setUnconditionalDest(LatchSucc);
445
Devang Patelbc5fe632007-08-07 00:25:56 +0000446 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000447 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000448
Devang Patelbc5fe632007-08-07 00:25:56 +0000449 // Replace split condition in header.
450 // Transform
451 // SplitCondition : icmp eq i32 IndVar, SplitValue
452 // into
453 // c1 = icmp uge i32 SplitValue, StartValue
454 // c2 = icmp ult i32 vSplitValue, ExitValue
455 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000456 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000457 Instruction *C1 = new ICmpInst(SignedPredicate ?
458 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000459 SD.SplitValue, StartValue, "lisplit",
460 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000461 Instruction *C2 = new ICmpInst(SignedPredicate ?
462 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000463 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000464 Terminator);
465 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
466 Terminator);
467 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
468 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000469
Devang Patelbc5fe632007-08-07 00:25:56 +0000470 // Now, clear latch block. Remove instructions that are responsible
471 // to increment induction variable.
472 Instruction *LTerminator = Latch->getTerminator();
473 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
474 LB != LE; ) {
475 Instruction *I = LB;
476 ++LB;
477 if (isa<PHINode>(I) || I == LTerminator)
478 continue;
479
Devang Patel59e0c062007-08-14 01:30:57 +0000480 if (I == IndVarIncrement)
481 I->replaceAllUsesWith(ExitValue);
482 else
483 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000484 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000485 }
486
Devang Patel901f67e2007-08-10 18:07:13 +0000487 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000488
489 // Update Dominator Info.
490 // Only CFG change done is to remove Latch to Header edge. This
491 // does not change dominator tree because Latch did not dominate
492 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000493 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000494 DominanceFrontier::iterator HeaderDF = DF->find(Header);
495 if (HeaderDF != DF->end())
496 DF->removeFromFrontier(HeaderDF, Header);
497
498 DominanceFrontier::iterator LatchDF = DF->find(Latch);
499 if (LatchDF != DF->end())
500 DF->removeFromFrontier(LatchDF, Header);
501 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000502 return true;
503}
504
505// If loop header includes loop variant instruction operands then
506// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000507bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000508
509 Instruction *Terminator = Header->getTerminator();
510 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
511 BI != BE; ++BI) {
512 Instruction *I = BI;
513
Devang Patel59e0c062007-08-14 01:30:57 +0000514 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000515 if (isa<PHINode>(I))
516 continue;
517
518 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000519 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000520 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000521
Devang Patel2545f7b2007-08-09 01:39:01 +0000522 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000523 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000524 continue;
525
526 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000527 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000528 continue;
529
Devang Patelbc5fe632007-08-07 00:25:56 +0000530 // Terminator is also harmless.
531 if (I == Terminator)
532 continue;
533
534 // Otherwise we have a instruction that may not be safe.
535 return false;
536 }
537
538 return true;
539}
540
Devang Patel9263fc32007-08-20 23:51:18 +0000541// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000542// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000543bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
544 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000545
Devang Patel9263fc32007-08-20 23:51:18 +0000546 for (BasicBlock::iterator BI = ExitingBlock->begin(),
547 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000548 Instruction *I = BI;
549
Devang Patel59e0c062007-08-14 01:30:57 +0000550 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000551 if (isa<PHINode>(I))
552 continue;
553
Devang Patel2545f7b2007-08-09 01:39:01 +0000554 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000555 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000556 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000557
Devang Patel2545f7b2007-08-09 01:39:01 +0000558 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000559 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000560
561 Value *Op0 = I->getOperand(0);
562 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000563 PHINode *PN = NULL;
564 ConstantInt *CI = NULL;
565
566 if ((PN = dyn_cast<PHINode>(Op0))) {
567 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000568 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000569 } else
570 if ((PN = dyn_cast<PHINode>(Op1))) {
571 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000572 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000573 }
574
Devang Patel61571ca2007-08-10 00:33:50 +0000575 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000576 continue;
577 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000578
Devang Patelbc5fe632007-08-07 00:25:56 +0000579 // I is an Exit condition if next instruction is block terminator.
580 // Exit condition is OK if it compares loop invariant exit value,
581 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000582 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000583 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000584 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000585 }
586
Devang Patel9263fc32007-08-20 23:51:18 +0000587 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000588 continue;
589
Devang Patelbc5fe632007-08-07 00:25:56 +0000590 // Otherwise we have instruction that may not be safe.
591 return false;
592 }
593
Devang Patel9263fc32007-08-20 23:51:18 +0000594 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000595 return true;
596}
597
Devang Patel0aaeb172007-08-08 22:25:28 +0000598/// Find cost of spliting loop L. Cost is measured in terms of size growth.
599/// Size is growth is calculated based on amount of code duplicated in second
600/// loop.
601unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
602
603 unsigned Cost = 0;
604 BasicBlock *SDBlock = SD.SplitCondition->getParent();
605 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
606 I != E; ++I) {
607 BasicBlock *BB = *I;
608 // If a block is not dominated by split condition block then
609 // it must be duplicated in both loops.
610 if (!DT->dominates(SDBlock, BB))
611 Cost += BB->size();
612 }
613
614 return Cost;
615}
616
Devang Patel60a94c72007-08-14 18:35:57 +0000617/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
618/// This routine is used to remove split condition's dead branch, dominated by
619/// DeadBB. LiveBB dominates split conidition's other branch.
620void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
621 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000622
Devang Patelf4277122007-08-15 03:31:47 +0000623 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000624 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000625 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
626 if (DeadBBDF != DF->end()) {
627 SmallVector<BasicBlock *, 8> PredBlocks;
628
629 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
630 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
631 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
632 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000633 FrontierBBs.push_back(FrontierBB);
634
Devang Patelf4277122007-08-15 03:31:47 +0000635 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
636 PredBlocks.clear();
637 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
638 PI != PE; ++PI) {
639 BasicBlock *P = *PI;
640 if (P == DeadBB || DT->dominates(DeadBB, P))
641 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000642 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000643
644 BasicBlock *NewDominator = NULL;
Devang Patelf4277122007-08-15 03:31:47 +0000645 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
646 FBI != FBE; ++FBI) {
647 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
648 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
649 PE = PredBlocks.end(); PI != PE; ++PI) {
650 BasicBlock *P = *PI;
651 PN->removeIncomingValue(P);
652 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000653 // If we have not identified new dominator then see if we can identify
654 // one based on remaining incoming PHINode values.
655 if (NewDominator == NULL && PN->getNumIncomingValues() == 1)
656 NewDominator = PN->getIncomingBlock(0);
Devang Patelf4277122007-08-15 03:31:47 +0000657 }
658 else
659 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000660 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000661 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000662 }
Devang Patelf4277122007-08-15 03:31:47 +0000663
664 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
665 SmallVector<BasicBlock *, 32> WorkList;
666 DomTreeNode *DN = DT->getNode(DeadBB);
667 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
668 E = df_end(DN); DI != E; ++DI) {
669 BasicBlock *BB = DI->getBlock();
670 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000671 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000672 }
673
674 while (!WorkList.empty()) {
675 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
676 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
677 BBI != BBE; ++BBI) {
678 Instruction *I = BBI;
679 I->replaceAllUsesWith(UndefValue::get(I->getType()));
680 I->eraseFromParent();
681 }
682 LPM->deleteSimpleAnalysisValue(BB, LP);
683 DT->eraseNode(BB);
684 DF->removeBlock(BB);
685 LI->removeBlock(BB);
686 BB->eraseFromParent();
687 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000688
689 // Update Frontier BBs' dominator info.
690 while (!FrontierBBs.empty()) {
691 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
692 BasicBlock *NewDominator = FBB->getSinglePredecessor();
693 if (!NewDominator) {
694 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
695 NewDominator = *PI;
696 ++PI;
697 if (NewDominator != LiveBB) {
698 for(; PI != PE; ++PI) {
699 BasicBlock *P = *PI;
700 if (P == LiveBB) {
701 NewDominator = LiveBB;
702 break;
703 }
704 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
705 }
706 }
707 }
708 assert (NewDominator && "Unable to fix dominator info.");
709 DT->changeImmediateDominator(FBB, NewDominator);
710 DF->changeImmediateDominator(FBB, NewDominator, DT);
711 }
712
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000713}
714
Devang Pateld662ace2007-08-22 18:27:01 +0000715/// safeSplitCondition - Return true if it is possible to
716/// split loop using given split condition.
717bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000718
Devang Pateld662ace2007-08-22 18:27:01 +0000719 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000720
Devang Pateld662ace2007-08-22 18:27:01 +0000721 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000722 // In triangle loop, split condition is in header and one of the
723 // the split destination is loop latch. If split condition is EQ
724 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000725 BasicBlock *Latch = L->getLoopLatch();
726 BranchInst *SplitTerminator =
727 cast<BranchInst>(SplitCondBlock->getTerminator());
728 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
729 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
730 if (L->getHeader() == SplitCondBlock
731 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000732 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000733
Devang Patel9cba64e2007-08-18 00:00:32 +0000734 // If one of the split condition branch is post dominating other then loop
735 // index split is not appropriate.
Devang Pateld662ace2007-08-22 18:27:01 +0000736 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
Devang Patel9cee7a02007-08-17 21:59:16 +0000737 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000738
Devang Patel9cba64e2007-08-18 00:00:32 +0000739 // If one of the split condition branch is a predecessor of the other
740 // split condition branch head then do not split loop on this condition.
Devang Patel2a24ff32007-08-21 21:12:02 +0000741 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
742 PI != PE; ++PI)
Devang Patel9cba64e2007-08-18 00:00:32 +0000743 if (Succ1 == *PI)
744 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000745 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
746 PI != PE; ++PI)
Devang Patel9cba64e2007-08-18 00:00:32 +0000747 if (Succ0 == *PI)
748 return false;
749
Devang Pateld662ace2007-08-22 18:27:01 +0000750 return true;
751}
752
753/// splitLoop - Split current loop L in two loops using split information
754/// SD. Update dominator information. Maintain LCSSA form.
755bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
756
757 if (!safeSplitCondition(SD))
758 return false;
759
760 // True loop is original loop. False loop is cloned loop.
761 BasicBlock *TL_SplitCondBlock = SD.SplitCondition->getParent();
762 BasicBlock *TL_Preheader = L->getLoopPreheader();
763
Devang Patelf824fb42007-08-10 00:53:35 +0000764 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000765 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patel2a24ff32007-08-21 21:12:02 +0000766 // TL_ExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000767 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patel5671efc2007-08-22 18:07:47 +0000768 // FL_StartValue = max(SplitValue, TrueLoop.StartValue)
Devang Patel2a24ff32007-08-21 21:12:02 +0000769 Value *TL_ExitValue = NULL;
770 Value *FL_StartValue = NULL;
Devang Patelf824fb42007-08-10 00:53:35 +0000771 if (isa<ConstantInt>(SD.SplitValue)) {
Devang Patel2a24ff32007-08-21 21:12:02 +0000772 TL_ExitValue = SD.SplitValue;
773 FL_StartValue = SD.SplitValue;
Devang Patelf824fb42007-08-10 00:53:35 +0000774 }
775 else {
Devang Patel2a24ff32007-08-21 21:12:02 +0000776 Instruction *TL_PHTerminator = TL_Preheader->getTerminator();
Devang Patelf824fb42007-08-10 00:53:35 +0000777 Value *C1 = new ICmpInst(SignedPredicate ?
778 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000779 SD.SplitValue,
780 ExitCondition->getOperand(ExitValueNum),
Devang Patel2a24ff32007-08-21 21:12:02 +0000781 "lsplit.ev", TL_PHTerminator);
782 TL_ExitValue = new SelectInst(C1, SD.SplitValue,
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000783 ExitCondition->getOperand(ExitValueNum),
Devang Patel2a24ff32007-08-21 21:12:02 +0000784 "lsplit.ev", TL_PHTerminator);
Devang Patelf824fb42007-08-10 00:53:35 +0000785
786 Value *C2 = new ICmpInst(SignedPredicate ?
787 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
788 SD.SplitValue, StartValue, "lsplit.sv",
Devang Patel2a24ff32007-08-21 21:12:02 +0000789 TL_PHTerminator);
Devang Patel5671efc2007-08-22 18:07:47 +0000790 FL_StartValue = new SelectInst(C2, StartValue, SD.SplitValue,
791 "lsplit.sv", TL_PHTerminator);
Devang Patelf824fb42007-08-10 00:53:35 +0000792 }
Devang Patel901f67e2007-08-10 18:07:13 +0000793
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000794 //[*] Clone loop. Avoid true destination of split condition and
795 // the blocks dominated by true destination.
796 DenseMap<const Value *, Value *> ValueMap;
797 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patel2a24ff32007-08-21 21:12:02 +0000798 BasicBlock *FL_Header = FalseLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000799
800 //[*] True loop's exit edge enters False loop.
Devang Patel2a24ff32007-08-21 21:12:02 +0000801 PHINode *FL_IndVar = cast<PHINode>(ValueMap[IndVar]);
802 BasicBlock *TL_ExitingBlock = ExitCondition->getParent();
803 BranchInst *TL_ExitInsn =
804 dyn_cast<BranchInst>(TL_ExitingBlock->getTerminator());
805 assert (TL_ExitInsn && "Unable to find suitable loop exit branch");
806 BasicBlock *TL_ExitDest = TL_ExitInsn->getSuccessor(1);
807
808 if (L->contains(TL_ExitDest)) {
809 TL_ExitDest = TL_ExitInsn->getSuccessor(0);
810 TL_ExitInsn->setSuccessor(0, FL_Header);
Devang Patel59e0c062007-08-14 01:30:57 +0000811 } else
Devang Patel2a24ff32007-08-21 21:12:02 +0000812 TL_ExitInsn->setSuccessor(1, FL_Header);
813
Devang Patel59e0c062007-08-14 01:30:57 +0000814 // Collect inverse map of Header PHINodes.
815 DenseMap<Value *, Value *> InverseMap;
816 for (BasicBlock::iterator BI = L->getHeader()->begin(),
817 BE = L->getHeader()->end(); BI != BE; ++BI) {
818 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
819 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
820 InverseMap[PNClone] = PN;
821 } else
822 break;
823 }
Devang Patel2a24ff32007-08-21 21:12:02 +0000824
Devang Patel59e0c062007-08-14 01:30:57 +0000825 // Update False loop's header
Devang Patel2a24ff32007-08-21 21:12:02 +0000826 for (BasicBlock::iterator BI = FL_Header->begin(), BE = FL_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000827 BI != BE; ++BI) {
828 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patel2a24ff32007-08-21 21:12:02 +0000829 PN->removeIncomingValue(TL_Preheader);
830 if (PN == FL_IndVar)
831 PN->addIncoming(FL_StartValue, TL_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000832 else {
833 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patel2a24ff32007-08-21 21:12:02 +0000834 Value *V2 = OrigPN->getIncomingValueForBlock(TL_ExitingBlock);
835 PN->addIncoming(V2, TL_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000836 }
837 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000838 break;
839 }
Devang Patel2a24ff32007-08-21 21:12:02 +0000840
841 // Update TL_ExitDest. Now it's predecessor is False loop's exit block.
842 BasicBlock *FL_ExitingBlock = cast<BasicBlock>(ValueMap[TL_ExitingBlock]);
843 for (BasicBlock::iterator BI = TL_ExitDest->begin(), BE = TL_ExitDest->end();
Devang Patel59e0c062007-08-14 01:30:57 +0000844 BI != BE; ++BI) {
845 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patel2a24ff32007-08-21 21:12:02 +0000846 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(TL_ExitingBlock)],
847 FL_ExitingBlock);
848 PN->removeIncomingValue(TL_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +0000849 } else
850 break;
851 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000852
Devang Patelb7639612007-08-13 22:13:24 +0000853 if (DT) {
Devang Patel2a24ff32007-08-21 21:12:02 +0000854 DT->changeImmediateDominator(FL_Header, TL_ExitingBlock);
855 DT->changeImmediateDominator(TL_ExitDest,
856 cast<BasicBlock>(ValueMap[TL_ExitingBlock]));
Devang Patelb7639612007-08-13 22:13:24 +0000857 }
858
Devang Patel2a24ff32007-08-21 21:12:02 +0000859 assert (!L->contains(TL_ExitDest) && " Unable to find exit edge destination");
Devang Patel901f67e2007-08-10 18:07:13 +0000860
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000861 //[*] Split Exit Edge.
Devang Patel2a24ff32007-08-21 21:12:02 +0000862 BasicBlock *TL_ExitBlock = SplitEdge(TL_ExitingBlock, FL_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +0000863
Devang Patel61571ca2007-08-10 00:33:50 +0000864 //[*] Eliminate split condition's false branch from True loop.
Devang Patel2a24ff32007-08-21 21:12:02 +0000865 BranchInst *TL_BR = cast<BranchInst>(TL_SplitCondBlock->getTerminator());
866 BasicBlock *TL_FalseBlock = TL_BR->getSuccessor(1);
867 TL_BR->setUnconditionalDest(TL_BR->getSuccessor(0));
868 removeBlocks(TL_FalseBlock, L, TL_BR->getSuccessor(0));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000869
870 //[*] Update True loop's exit value using new exit value.
Devang Patel2a24ff32007-08-21 21:12:02 +0000871 ExitCondition->setOperand(ExitValueNum, TL_ExitValue);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000872
873 //[*] Eliminate split condition's true branch in False loop CFG.
Devang Patel2a24ff32007-08-21 21:12:02 +0000874 BasicBlock *FL_SplitCondBlock = cast<BasicBlock>(ValueMap[TL_SplitCondBlock]);
875 BranchInst *FL_BR = cast<BranchInst>(FL_SplitCondBlock->getTerminator());
876 BasicBlock *FL_TrueBlock = FL_BR->getSuccessor(0);
877 FL_BR->setUnconditionalDest(FL_BR->getSuccessor(1));
878 removeBlocks(FL_TrueBlock, FalseLoop,
879 cast<BasicBlock>(FL_BR->getSuccessor(0)));
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000880
Devang Patel7ef89b82007-08-21 19:47:46 +0000881 //[*] Preserve LCSSA
Devang Patel2a24ff32007-08-21 21:12:02 +0000882 for(BasicBlock::iterator BI = FL_Header->begin(), BE = FL_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +0000883 BI != BE; ++BI) {
884 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
885 Value *V1 = PN->getIncomingValueForBlock(TL_ExitBlock);
886 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patel2a24ff32007-08-21 21:12:02 +0000887 newPHI->addIncoming(V1, TL_ExitingBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +0000888 TL_ExitBlock->getInstList().push_front(newPHI);
889 PN->removeIncomingValue(TL_ExitBlock);
890 PN->addIncoming(newPHI, TL_ExitBlock);
891 } else
892 break;
893 }
894
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000895 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000896}