blob: 37d5ce4d3f78566f9516828f3d5ea0974f108cab [file] [log] [blame]
Karthik Bhat88db86d2015-03-06 10:11:25 +00001//===- LoopInterchange.cpp - Loop interchange pass------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This Pass handles loop interchange transform.
11// This pass interchanges loops to provide a more cache-friendly memory access
12// patterns.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/AliasAnalysis.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000018#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/BlockFrequencyInfo.h"
20#include "llvm/Analysis/CodeMetrics.h"
21#include "llvm/Analysis/DependenceAnalysis.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/LoopIterator.h"
24#include "llvm/Analysis/LoopPass.h"
25#include "llvm/Analysis/ScalarEvolution.h"
26#include "llvm/Analysis/ScalarEvolutionExpander.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/Analysis/TargetTransformInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000030#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000033#include "llvm/IR/InstIterator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/IR/IntrinsicInst.h"
Karthik Bhat8210fdf2015-04-23 04:51:44 +000035#include "llvm/IR/Module.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000036#include "llvm/Pass.h"
37#include "llvm/Support/Debug.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000039#include "llvm/Transforms/Scalar.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/SSAUpdater.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000043using namespace llvm;
44
45#define DEBUG_TYPE "loop-interchange"
46
Chad Rosier72431892016-09-14 17:07:13 +000047static cl::opt<int> LoopInterchangeCostThreshold(
48 "loop-interchange-threshold", cl::init(0), cl::Hidden,
49 cl::desc("Interchange if you gain more than this number"));
50
Karthik Bhat88db86d2015-03-06 10:11:25 +000051namespace {
52
53typedef SmallVector<Loop *, 8> LoopVector;
54
55// TODO: Check if we can use a sparse matrix here.
56typedef std::vector<std::vector<char>> CharMatrix;
57
58// Maximum number of dependencies that can be handled in the dependency matrix.
59static const unsigned MaxMemInstrCount = 100;
60
61// Maximum loop depth supported.
62static const unsigned MaxLoopNestDepth = 10;
63
64struct LoopInterchange;
65
66#ifdef DUMP_DEP_MATRICIES
67void printDepMatrix(CharMatrix &DepMatrix) {
68 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) {
69 std::vector<char> Vec = *I;
70 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II)
71 DEBUG(dbgs() << *II << " ");
72 DEBUG(dbgs() << "\n");
73 }
74}
75#endif
76
Karthik Bhat8210fdf2015-04-23 04:51:44 +000077static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000078 Loop *L, DependenceInfo *DI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000079 typedef SmallVector<Value *, 16> ValueVector;
80 ValueVector MemInstr;
81
Karthik Bhat88db86d2015-03-06 10:11:25 +000082 // For each block.
83 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end();
84 BB != BE; ++BB) {
85 // Scan the BB and collect legal loads and stores.
86 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E;
87 ++I) {
Chad Rosier09c11092016-09-13 12:56:04 +000088 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000089 return false;
Chad Rosier09c11092016-09-13 12:56:04 +000090 if (LoadInst *Ld = dyn_cast<LoadInst>(I)) {
91 if (!Ld->isSimple())
92 return false;
93 MemInstr.push_back(&*I);
94 } else if (StoreInst *St = dyn_cast<StoreInst>(I)) {
95 if (!St->isSimple())
96 return false;
97 MemInstr.push_back(&*I);
98 }
Karthik Bhat88db86d2015-03-06 10:11:25 +000099 }
100 }
101
102 DEBUG(dbgs() << "Found " << MemInstr.size()
103 << " Loads and Stores to analyze\n");
104
105 ValueVector::iterator I, IE, J, JE;
106
107 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
108 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
109 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000110 Instruction *Src = cast<Instruction>(*I);
111 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000112 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000113 continue;
Chad Rosier90bcb912016-09-07 16:07:17 +0000114 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000115 continue;
Chad Rosier90bcb912016-09-07 16:07:17 +0000116 if (auto D = DI->depends(Src, Dst, true)) {
117 DEBUG(dbgs() << "Found Dependency between Src and Dst\n"
118 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000119 if (D->isFlow()) {
120 // TODO: Handle Flow dependence.Check if it is sufficient to populate
121 // the Dependence Matrix with the direction reversed.
Chad Rosierf5814f52016-09-07 15:56:59 +0000122 DEBUG(dbgs() << "Flow dependence not handled\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000123 return false;
124 }
125 if (D->isAnti()) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000126 DEBUG(dbgs() << "Found Anti dependence\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000127 unsigned Levels = D->getLevels();
128 char Direction;
129 for (unsigned II = 1; II <= Levels; ++II) {
130 const SCEV *Distance = D->getDistance(II);
131 const SCEVConstant *SCEVConst =
132 dyn_cast_or_null<SCEVConstant>(Distance);
133 if (SCEVConst) {
134 const ConstantInt *CI = SCEVConst->getValue();
135 if (CI->isNegative())
136 Direction = '<';
137 else if (CI->isZero())
138 Direction = '=';
139 else
140 Direction = '>';
141 Dep.push_back(Direction);
142 } else if (D->isScalar(II)) {
143 Direction = 'S';
144 Dep.push_back(Direction);
145 } else {
146 unsigned Dir = D->getDirection(II);
147 if (Dir == Dependence::DVEntry::LT ||
148 Dir == Dependence::DVEntry::LE)
149 Direction = '<';
150 else if (Dir == Dependence::DVEntry::GT ||
151 Dir == Dependence::DVEntry::GE)
152 Direction = '>';
153 else if (Dir == Dependence::DVEntry::EQ)
154 Direction = '=';
155 else
156 Direction = '*';
157 Dep.push_back(Direction);
158 }
159 }
160 while (Dep.size() != Level) {
161 Dep.push_back('I');
162 }
163
164 DepMatrix.push_back(Dep);
165 if (DepMatrix.size() > MaxMemInstrCount) {
166 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
167 << " dependencies inside loop\n");
168 return false;
169 }
170 }
171 }
172 }
173 }
174
Vikram TV74b41112015-12-09 05:16:24 +0000175 // We don't have a DepMatrix to check legality return false.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000176 if (DepMatrix.size() == 0)
177 return false;
178 return true;
179}
180
181// A loop is moved from index 'from' to an index 'to'. Update the Dependence
182// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000183static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
184 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000185 unsigned numRows = DepMatrix.size();
186 for (unsigned i = 0; i < numRows; ++i) {
187 char TmpVal = DepMatrix[i][ToIndx];
188 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
189 DepMatrix[i][FromIndx] = TmpVal;
190 }
191}
192
193// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
194// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000195static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
196 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000197 for (unsigned i = 0; i <= Column; ++i) {
198 if (DepMatrix[Row][i] == '<')
199 return false;
200 if (DepMatrix[Row][i] == '>')
201 return true;
202 }
203 // All dependencies were '=','S' or 'I'
204 return false;
205}
206
207// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000208static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
209 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000210 for (unsigned i = 0; i < Column; ++i) {
211 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' ||
212 DepMatrix[Row][i] != 'I')
213 return false;
214 }
215 return true;
216}
217
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000218static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
219 unsigned OuterLoopId, char InnerDep,
220 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000221
222 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
223 return false;
224
225 if (InnerDep == OuterDep)
226 return true;
227
228 // It is legal to interchange if and only if after interchange no row has a
229 // '>' direction as the leftmost non-'='.
230
231 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
232 return true;
233
234 if (InnerDep == '<')
235 return true;
236
237 if (InnerDep == '>') {
238 // If OuterLoopId represents outermost loop then interchanging will make the
239 // 1st dependency as '>'
240 if (OuterLoopId == 0)
241 return false;
242
243 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
244 // interchanging will result in this row having an outermost non '='
245 // dependency of '>'
246 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
247 return true;
248 }
249
250 return false;
251}
252
253// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000254// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000255// if the direction matrix, after the same permutation is applied to its
256// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000257static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
258 unsigned InnerLoopId,
259 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000260
261 unsigned NumRows = DepMatrix.size();
262 // For each row check if it is valid to interchange.
263 for (unsigned Row = 0; Row < NumRows; ++Row) {
264 char InnerDep = DepMatrix[Row][InnerLoopId];
265 char OuterDep = DepMatrix[Row][OuterLoopId];
266 if (InnerDep == '*' || OuterDep == '*')
267 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000269 return false;
270 }
271 return true;
272}
273
274static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
275
Chad Rosierf5814f52016-09-07 15:56:59 +0000276 DEBUG(dbgs() << "Calling populateWorklist on Func: "
277 << L.getHeader()->getParent()->getName() << " Loop: %"
278 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000279 LoopVector LoopList;
280 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000281 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
282 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000283 // The current loop has multiple subloops in it hence it is not tightly
284 // nested.
285 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000286 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000287 LoopList.clear();
288 return;
289 }
290 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000291 CurrentLoop = Vec->front();
292 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000293 }
294 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000295 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000296}
297
298static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
299 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
300 if (InnerIndexVar)
301 return InnerIndexVar;
302 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
303 return nullptr;
304 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
305 PHINode *PhiVar = cast<PHINode>(I);
306 Type *PhiTy = PhiVar->getType();
307 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
308 !PhiTy->isPointerTy())
309 return nullptr;
310 const SCEVAddRecExpr *AddRec =
311 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
312 if (!AddRec || !AddRec->isAffine())
313 continue;
314 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000315 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000316 continue;
317 // Found the induction variable.
318 // FIXME: Handle loops with more than one induction variable. Note that,
319 // currently, legality makes sure we have only one induction variable.
320 return PhiVar;
321 }
322 return nullptr;
323}
324
325/// LoopInterchangeLegality checks if it is legal to interchange the loop.
326class LoopInterchangeLegality {
327public:
328 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Justin Bogner843fb202015-12-15 19:40:57 +0000329 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA)
330 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
331 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000332
333 /// Check if the loops can be interchanged.
334 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
335 CharMatrix &DepMatrix);
336 /// Check if the loop structure is understood. We do not handle triangular
337 /// loops for now.
338 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
339
340 bool currentLimitations();
341
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000342 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
343
Karthik Bhat88db86d2015-03-06 10:11:25 +0000344private:
345 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000346 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
347 bool areAllUsesReductions(Instruction *Ins, Loop *L);
348 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
349 bool findInductionAndReductions(Loop *L,
350 SmallVector<PHINode *, 8> &Inductions,
351 SmallVector<PHINode *, 8> &Reductions);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000352 Loop *OuterLoop;
353 Loop *InnerLoop;
354
Karthik Bhat88db86d2015-03-06 10:11:25 +0000355 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000356 LoopInfo *LI;
357 DominatorTree *DT;
358 bool PreserveLCSSA;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000359
360 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000361};
362
363/// LoopInterchangeProfitability checks if it is profitable to interchange the
364/// loop.
365class LoopInterchangeProfitability {
366public:
367 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE)
368 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {}
369
Vikram TV74b41112015-12-09 05:16:24 +0000370 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000371 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
372 CharMatrix &DepMatrix);
373
374private:
375 int getInstrOrderCost();
376
377 Loop *OuterLoop;
378 Loop *InnerLoop;
379
380 /// Scev analysis.
381 ScalarEvolution *SE;
382};
383
Vikram TV74b41112015-12-09 05:16:24 +0000384/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000385class LoopInterchangeTransform {
386public:
387 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
388 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000389 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000390 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000391 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000392 LoopExit(LoopNestExit),
393 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000394
395 /// Interchange OuterLoop and InnerLoop.
396 bool transform();
397 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
398 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000399
400private:
401 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000402 void splitInnerLoopHeader();
403 bool adjustLoopLinks();
404 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000405 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000406 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
407 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000408
409 Loop *OuterLoop;
410 Loop *InnerLoop;
411
412 /// Scev analysis.
413 ScalarEvolution *SE;
414 LoopInfo *LI;
415 DominatorTree *DT;
416 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000417 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000418};
419
Vikram TV74b41112015-12-09 05:16:24 +0000420// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000421struct LoopInterchange : public FunctionPass {
422 static char ID;
423 ScalarEvolution *SE;
424 LoopInfo *LI;
Chandler Carruth49c22192016-05-12 22:19:39 +0000425 DependenceInfo *DI;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000426 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000427 bool PreserveLCSSA;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000428 LoopInterchange()
Chandler Carruth49c22192016-05-12 22:19:39 +0000429 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000430 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
431 }
432
433 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000434 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000435 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000436 AU.addRequired<DominatorTreeWrapperPass>();
437 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000438 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000439 AU.addRequiredID(LoopSimplifyID);
440 AU.addRequiredID(LCSSAID);
441 }
442
443 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000444 if (skipFunction(F))
445 return false;
446
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000447 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000448 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000449 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000450 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
451 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000452 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
453
Karthik Bhat88db86d2015-03-06 10:11:25 +0000454 // Build up a worklist of loop pairs to analyze.
455 SmallVector<LoopVector, 8> Worklist;
456
457 for (Loop *L : *LI)
458 populateWorklist(*L, Worklist);
459
Chad Rosiera4c42462016-09-12 13:24:47 +0000460 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000461 bool Changed = true;
462 while (!Worklist.empty()) {
463 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000464 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000465 }
466 return Changed;
467 }
468
469 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000470 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000471 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
472 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000473 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000474 return false;
475 }
476 if (L->getNumBackEdges() != 1) {
477 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
478 return false;
479 }
480 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000481 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000482 return false;
483 }
484 }
485 return true;
486 }
487
Benjamin Kramerc321e532016-06-08 19:09:22 +0000488 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000489 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000490 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000491 return LoopList.size() - 1;
492 }
493
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000494 bool processLoopList(LoopVector LoopList, Function &F) {
495
Karthik Bhat88db86d2015-03-06 10:11:25 +0000496 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000497 unsigned LoopNestDepth = LoopList.size();
498 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000499 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
500 return false;
501 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000502 if (LoopNestDepth > MaxLoopNestDepth) {
503 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
504 << MaxLoopNestDepth << "\n");
505 return false;
506 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000507 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000508 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000509 return false;
510 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000511
512 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
513
514 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000515 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000516 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000517 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000518 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000519 return false;
520 }
521#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000522 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000523 printDepMatrix(DependencyMatrix);
524#endif
525
526 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
527 BranchInst *OuterMostLoopLatchBI =
528 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
529 if (!OuterMostLoopLatchBI)
530 return false;
531
532 // Since we currently do not handle LCSSA PHI's any failure in loop
533 // condition will now branch to LoopNestExit.
534 // TODO: This should be removed once we handle LCSSA PHI nodes.
535
536 // Get the Outermost loop exit.
537 BasicBlock *LoopNestExit;
538 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
539 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
540 else
541 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
542
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000543 if (isa<PHINode>(LoopNestExit->begin())) {
544 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
545 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000546 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000547 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000548
549 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000550 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000551 for (unsigned i = SelecLoopId; i > 0; i--) {
552 bool Interchanged =
553 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
554 if (!Interchanged)
555 return Changed;
556 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000557 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000558
559 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000560 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000561 DT->recalculate(F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000562#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000563 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000564 printDepMatrix(DependencyMatrix);
565#endif
566 Changed |= Interchanged;
567 }
568 return Changed;
569 }
570
571 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
572 unsigned OuterLoopId, BasicBlock *LoopNestExit,
573 std::vector<std::vector<char>> &DependencyMatrix) {
574
Chad Rosier13bc0d192016-09-07 18:15:12 +0000575 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000576 << " and OuterLoopId = " << OuterLoopId << "\n");
577 Loop *InnerLoop = LoopList[InnerLoopId];
578 Loop *OuterLoop = LoopList[OuterLoopId];
579
Justin Bogner843fb202015-12-15 19:40:57 +0000580 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
581 PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000582 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
583 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
584 return false;
585 }
586 DEBUG(dbgs() << "Loops are legal to interchange\n");
587 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE);
588 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000589 DEBUG(dbgs() << "Interchanging loops not profitable\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000590 return false;
591 }
592
Justin Bogner843fb202015-12-15 19:40:57 +0000593 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000594 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000595 LIT.transform();
596 DEBUG(dbgs() << "Loops interchanged\n");
597 return true;
598 }
599};
600
601} // end of namespace
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000602bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
David Majnemer0a16c222016-08-11 21:15:00 +0000603 return none_of(Ins->users(), [=](User *U) -> bool {
604 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000605 RecurrenceDescriptor RD;
606 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000607 });
608}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000609
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000610bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
611 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000612 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000613 // Load corresponding to reduction PHI's are safe while concluding if
614 // tightly nested.
615 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
616 if (!areAllUsesReductions(L, InnerLoop))
617 return true;
618 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
619 return true;
620 }
621 return false;
622}
623
624bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
625 BasicBlock *BB) {
626 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
627 // Stores corresponding to reductions are safe while concluding if tightly
628 // nested.
629 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000630 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000631 return true;
632 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000633 return true;
634 }
635 return false;
636}
637
638bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
639 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
640 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
641 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
642
Chad Rosierf7c76f92016-09-21 13:28:41 +0000643 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000644
645 // A perfectly nested loop will not have any branch in between the outer and
646 // inner block i.e. outer header will branch to either inner preheader and
647 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000648 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000649 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000650 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000651 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000652
653 for (unsigned i = 0, e = OuterLoopHeaderBI->getNumSuccessors(); i < e; ++i) {
654 if (OuterLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader &&
655 OuterLoopHeaderBI->getSuccessor(i) != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000656 return false;
657 }
658
Chad Rosierf7c76f92016-09-21 13:28:41 +0000659 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000660 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000661 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000662 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
663 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000664 return false;
665
Chad Rosierf7c76f92016-09-21 13:28:41 +0000666 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000667 // We have a perfect loop nest.
668 return true;
669}
670
Karthik Bhat88db86d2015-03-06 10:11:25 +0000671
672bool LoopInterchangeLegality::isLoopStructureUnderstood(
673 PHINode *InnerInduction) {
674
675 unsigned Num = InnerInduction->getNumOperands();
676 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
677 for (unsigned i = 0; i < Num; ++i) {
678 Value *Val = InnerInduction->getOperand(i);
679 if (isa<Constant>(Val))
680 continue;
681 Instruction *I = dyn_cast<Instruction>(Val);
682 if (!I)
683 return false;
684 // TODO: Handle triangular loops.
685 // e.g. for(int i=0;i<N;i++)
686 // for(int j=i;j<N;j++)
687 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
688 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
689 InnerLoopPreheader &&
690 !OuterLoop->isLoopInvariant(I)) {
691 return false;
692 }
693 }
694 return true;
695}
696
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000697bool LoopInterchangeLegality::findInductionAndReductions(
698 Loop *L, SmallVector<PHINode *, 8> &Inductions,
699 SmallVector<PHINode *, 8> &Reductions) {
700 if (!L->getLoopLatch() || !L->getLoopPredecessor())
701 return false;
702 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000703 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000704 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000705 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000706 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000707 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000708 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000709 Reductions.push_back(PHI);
710 else {
711 DEBUG(
712 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
713 return false;
714 }
715 }
716 return true;
717}
718
719static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
720 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
721 PHINode *PHI = cast<PHINode>(I);
722 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
723 if (PHI->getNumIncomingValues() > 1)
724 return false;
725 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
726 if (!Ins)
727 return false;
728 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
729 // exits lcssa phi else it would not be tightly nested.
730 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
731 return false;
732 }
733 return true;
734}
735
736static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
737 BasicBlock *LoopHeader) {
738 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
739 unsigned Num = BI->getNumSuccessors();
740 assert(Num == 2);
741 for (unsigned i = 0; i < Num; ++i) {
742 if (BI->getSuccessor(i) == LoopHeader)
743 continue;
744 return BI->getSuccessor(i);
745 }
746 }
747 return nullptr;
748}
749
Karthik Bhat88db86d2015-03-06 10:11:25 +0000750// This function indicates the current limitations in the transform as a result
751// of which we do not proceed.
752bool LoopInterchangeLegality::currentLimitations() {
753
754 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
755 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000756 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
757 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000758 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000759
760 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000761 SmallVector<PHINode *, 8> Inductions;
762 SmallVector<PHINode *, 8> Reductions;
763 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000764 return true;
765
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000766 // TODO: Currently we handle only loops with 1 induction variable.
767 if (Inductions.size() != 1) {
768 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
769 << "Failed to interchange due to current limitation\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000770 return true;
771 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000772 if (Reductions.size() > 0)
773 InnerLoopHasReduction = true;
774
775 InnerInductionVar = Inductions.pop_back_val();
776 Reductions.clear();
777 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions))
778 return true;
779
780 // Outer loop cannot have reduction because then loops will not be tightly
781 // nested.
782 if (!Reductions.empty())
783 return true;
784 // TODO: Currently we handle only loops with 1 induction variable.
785 if (Inductions.size() != 1)
786 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000787
788 // TODO: Triangular loops are not handled for now.
789 if (!isLoopStructureUnderstood(InnerInductionVar)) {
790 DEBUG(dbgs() << "Loop structure not understood by pass\n");
791 return true;
792 }
793
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000794 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
795 BasicBlock *LoopExitBlock =
796 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
797 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000798 return true;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000799
800 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
801 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000802 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000803
804 // TODO: Current limitation: Since we split the inner loop latch at the point
805 // were induction variable is incremented (induction.next); We cannot have
806 // more than 1 user of induction.next since it would result in broken code
807 // after split.
808 // e.g.
809 // for(i=0;i<N;i++) {
810 // for(j = 0;j<M;j++) {
811 // A[j+1][i+2] = A[j][i]+k;
812 // }
813 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000814 Instruction *InnerIndexVarInc = nullptr;
815 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
816 InnerIndexVarInc =
817 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
818 else
819 InnerIndexVarInc =
820 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
821
Pete Cooper11bd9582015-07-27 18:37:58 +0000822 if (!InnerIndexVarInc)
823 return true;
824
Karthik Bhat88db86d2015-03-06 10:11:25 +0000825 // Since we split the inner loop latch on this induction variable. Make sure
826 // we do not have any instruction between the induction variable and branch
827 // instruction.
828
David Majnemerd7708772016-06-24 04:05:21 +0000829 bool FoundInduction = false;
830 for (const Instruction &I : reverse(*InnerLoopLatch)) {
831 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000832 continue;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000833 // We found an instruction. If this is not induction variable then it is not
834 // safe to split this loop latch.
David Majnemerd7708772016-06-24 04:05:21 +0000835 if (!I.isIdenticalTo(InnerIndexVarInc))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000836 return true;
David Majnemerd7708772016-06-24 04:05:21 +0000837
838 FoundInduction = true;
839 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000840 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000841 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000842 // current limitation.
843 if (!FoundInduction)
844 return true;
845
846 return false;
847}
848
849bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
850 unsigned OuterLoopId,
851 CharMatrix &DepMatrix) {
852
853 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
854 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000855 << " and OuterLoopId = " << OuterLoopId
856 << " due to dependence\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000857 return false;
858 }
859
860 // Create unique Preheaders if we already do not have one.
861 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
862 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
863
864 // Create a unique outer preheader -
865 // 1) If OuterLoop preheader is not present.
866 // 2) If OuterLoop Preheader is same as OuterLoop Header
867 // 3) If OuterLoop Preheader is same as Header of the previous loop.
868 // 4) If OuterLoop Preheader is Entry node.
869 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
870 isa<PHINode>(OuterLoopPreHeader->begin()) ||
871 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000872 OuterLoopPreHeader =
873 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000874 }
875
876 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
877 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000878 InnerLoopPreHeader =
879 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000880 }
881
Karthik Bhat88db86d2015-03-06 10:11:25 +0000882 // TODO: The loops could not be interchanged due to current limitations in the
883 // transform module.
884 if (currentLimitations()) {
885 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
886 return false;
887 }
888
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000889 // Check if the loops are tightly nested.
890 if (!tightlyNested(OuterLoop, InnerLoop)) {
891 DEBUG(dbgs() << "Loops not tightly nested\n");
892 return false;
893 }
894
Karthik Bhat88db86d2015-03-06 10:11:25 +0000895 return true;
896}
897
898int LoopInterchangeProfitability::getInstrOrderCost() {
899 unsigned GoodOrder, BadOrder;
900 BadOrder = GoodOrder = 0;
901 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end();
902 BI != BE; ++BI) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000903 for (Instruction &Ins : **BI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000904 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
905 unsigned NumOp = GEP->getNumOperands();
906 bool FoundInnerInduction = false;
907 bool FoundOuterInduction = false;
908 for (unsigned i = 0; i < NumOp; ++i) {
909 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
910 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
911 if (!AR)
912 continue;
913
914 // If we find the inner induction after an outer induction e.g.
915 // for(int i=0;i<N;i++)
916 // for(int j=0;j<N;j++)
917 // A[i][j] = A[i-1][j-1]+k;
918 // then it is a good order.
919 if (AR->getLoop() == InnerLoop) {
920 // We found an InnerLoop induction after OuterLoop induction. It is
921 // a good order.
922 FoundInnerInduction = true;
923 if (FoundOuterInduction) {
924 GoodOrder++;
925 break;
926 }
927 }
928 // If we find the outer induction after an inner induction e.g.
929 // for(int i=0;i<N;i++)
930 // for(int j=0;j<N;j++)
931 // A[j][i] = A[j-1][i-1]+k;
932 // then it is a bad order.
933 if (AR->getLoop() == OuterLoop) {
934 // We found an OuterLoop induction after InnerLoop induction. It is
935 // a bad order.
936 FoundOuterInduction = true;
937 if (FoundInnerInduction) {
938 BadOrder++;
939 break;
940 }
941 }
942 }
943 }
944 }
945 }
946 return GoodOrder - BadOrder;
947}
948
Chad Rosiere6b3a632016-09-14 17:12:30 +0000949static bool isProfitableForVectorization(unsigned InnerLoopId,
950 unsigned OuterLoopId,
951 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000952 // TODO: Improve this heuristic to catch more cases.
953 // If the inner loop is loop independent or doesn't carry any dependency it is
954 // profitable to move this to outer position.
955 unsigned Row = DepMatrix.size();
956 for (unsigned i = 0; i < Row; ++i) {
957 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I')
958 return false;
959 // TODO: We need to improve this heuristic.
960 if (DepMatrix[i][OuterLoopId] != '=')
961 return false;
962 }
963 // If outer loop has dependence and inner loop is loop independent then it is
964 // profitable to interchange to enable parallelism.
965 return true;
966}
967
968bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
969 unsigned OuterLoopId,
970 CharMatrix &DepMatrix) {
971
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000972 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000973 // e.g
974 // 1) Construct dependency matrix and move the one with no loop carried dep
975 // inside to enable vectorization.
976
977 // This is rough cost estimation algorithm. It counts the good and bad order
978 // of induction variables in the instruction and allows reordering if number
979 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +0000980 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000981 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +0000982 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000983 return true;
984
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000985 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +0000986 // we can move this loop outside to improve parallelism.
987 bool ImprovesPar =
Chad Rosiere6b3a632016-09-14 17:12:30 +0000988 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000989 return ImprovesPar;
990}
991
992void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
993 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000994 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
995 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000996 if (*I == InnerLoop) {
997 OuterLoop->removeChildLoop(I);
998 return;
999 }
1000 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001001 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001002}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001003
Karthik Bhat88db86d2015-03-06 10:11:25 +00001004void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1005 Loop *OuterLoop) {
1006 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1007 if (OuterLoopParent) {
1008 // Remove the loop from its parent loop.
1009 removeChildLoop(OuterLoopParent, OuterLoop);
1010 removeChildLoop(OuterLoop, InnerLoop);
1011 OuterLoopParent->addChildLoop(InnerLoop);
1012 } else {
1013 removeChildLoop(OuterLoop, InnerLoop);
1014 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1015 }
1016
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001017 while (!InnerLoop->empty())
1018 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001019
1020 InnerLoop->addChildLoop(OuterLoop);
1021}
1022
1023bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001024 bool Transformed = false;
1025 Instruction *InnerIndexVar;
1026
1027 if (InnerLoop->getSubLoops().size() == 0) {
1028 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1029 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1030 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1031 if (!InductionPHI) {
1032 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1033 return false;
1034 }
1035
1036 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1037 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1038 else
1039 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1040
1041 //
1042 // Split at the place were the induction variable is
1043 // incremented/decremented.
1044 // TODO: This splitting logic may not work always. Fix this.
1045 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001046 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001047
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001048 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001049 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001050 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001051 }
1052
1053 Transformed |= adjustLoopLinks();
1054 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001055 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001056 return false;
1057 }
1058
1059 restructureLoops(InnerLoop, OuterLoop);
1060 return true;
1061}
1062
Benjamin Kramer79442922015-03-06 18:59:14 +00001063void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001064 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001065 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001066 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001067}
1068
Karthik Bhat88db86d2015-03-06 10:11:25 +00001069void LoopInterchangeTransform::splitInnerLoopHeader() {
1070
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001071 // Split the inner loop header out. Here make sure that the reduction PHI's
1072 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001073 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001074 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1075 if (InnerLoopHasReduction) {
1076 // FIXME: Check if the induction PHI will always be the first PHI.
1077 BasicBlock *New = InnerLoopHeader->splitBasicBlock(
1078 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split");
1079 if (LI)
1080 if (Loop *L = LI->getLoopFor(InnerLoopHeader))
1081 L->addBasicBlockToLoop(New, *LI);
1082
1083 // Adjust Reduction PHI's in the block.
1084 SmallVector<PHINode *, 8> PHIVec;
1085 for (auto I = New->begin(); isa<PHINode>(I); ++I) {
1086 PHINode *PHI = dyn_cast<PHINode>(I);
1087 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1088 PHI->replaceAllUsesWith(V);
1089 PHIVec.push_back((PHI));
1090 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001091 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001092 P->eraseFromParent();
1093 }
1094 } else {
1095 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1096 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001097
1098 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001099 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001100}
1101
Benjamin Kramer79442922015-03-06 18:59:14 +00001102/// \brief Move all instructions except the terminator from FromBB right before
1103/// InsertBefore
1104static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1105 auto &ToList = InsertBefore->getParent()->getInstList();
1106 auto &FromList = FromBB->getInstList();
1107
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001108 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1109 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001110}
1111
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001112void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1113 BasicBlock *OldPred,
1114 BasicBlock *NewPred) {
1115 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1116 PHINode *PHI = cast<PHINode>(I);
1117 unsigned Num = PHI->getNumIncomingValues();
1118 for (unsigned i = 0; i < Num; ++i) {
1119 if (PHI->getIncomingBlock(i) == OldPred)
1120 PHI->setIncomingBlock(i, NewPred);
1121 }
1122 }
1123}
1124
Karthik Bhat88db86d2015-03-06 10:11:25 +00001125bool LoopInterchangeTransform::adjustLoopBranches() {
1126
1127 DEBUG(dbgs() << "adjustLoopBranches called\n");
1128 // Adjust the loop preheader
1129 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1130 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1131 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1132 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1133 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1134 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1135 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1136 BasicBlock *InnerLoopLatchPredecessor =
1137 InnerLoopLatch->getUniquePredecessor();
1138 BasicBlock *InnerLoopLatchSuccessor;
1139 BasicBlock *OuterLoopLatchSuccessor;
1140
1141 BranchInst *OuterLoopLatchBI =
1142 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1143 BranchInst *InnerLoopLatchBI =
1144 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1145 BranchInst *OuterLoopHeaderBI =
1146 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1147 BranchInst *InnerLoopHeaderBI =
1148 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1149
1150 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1151 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1152 !InnerLoopHeaderBI)
1153 return false;
1154
1155 BranchInst *InnerLoopLatchPredecessorBI =
1156 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1157 BranchInst *OuterLoopPredecessorBI =
1158 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1159
1160 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1161 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001162 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1163 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001164 return false;
1165
1166 // Adjust Loop Preheader and headers
1167
1168 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1169 for (unsigned i = 0; i < NumSucc; ++i) {
1170 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1171 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1172 }
1173
1174 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1175 for (unsigned i = 0; i < NumSucc; ++i) {
1176 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1177 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1178 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001179 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001180 }
1181
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001182 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001183 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001184 OuterLoopHeader);
1185
Karthik Bhat88db86d2015-03-06 10:11:25 +00001186 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1187 InnerLoopHeaderBI->eraseFromParent();
1188
1189 // -------------Adjust loop latches-----------
1190 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1191 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1192 else
1193 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1194
1195 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1196 for (unsigned i = 0; i < NumSucc; ++i) {
1197 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1198 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1199 }
1200
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001201 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1202 // the value and remove this PHI node from inner loop.
1203 SmallVector<PHINode *, 8> LcssaVec;
1204 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1205 PHINode *LcssaPhi = cast<PHINode>(I);
1206 LcssaVec.push_back(LcssaPhi);
1207 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001208 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001209 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1210 P->replaceAllUsesWith(Incoming);
1211 P->eraseFromParent();
1212 }
1213
Karthik Bhat88db86d2015-03-06 10:11:25 +00001214 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1215 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1216 else
1217 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1218
1219 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1220 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1221 else
1222 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1223
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001224 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1225
Karthik Bhat88db86d2015-03-06 10:11:25 +00001226 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1227 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1228 } else {
1229 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1230 }
1231
1232 return true;
1233}
1234void LoopInterchangeTransform::adjustLoopPreheaders() {
1235
1236 // We have interchanged the preheaders so we need to interchange the data in
1237 // the preheader as well.
1238 // This is because the content of inner preheader was previously executed
1239 // inside the outer loop.
1240 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1241 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1242 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1243 BranchInst *InnerTermBI =
1244 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1245
Karthik Bhat88db86d2015-03-06 10:11:25 +00001246 // These instructions should now be executed inside the loop.
1247 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001248 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001249 // These instructions were not executed previously in the loop so move them to
1250 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001251 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001252}
1253
1254bool LoopInterchangeTransform::adjustLoopLinks() {
1255
1256 // Adjust all branches in the inner and outer loop.
1257 bool Changed = adjustLoopBranches();
1258 if (Changed)
1259 adjustLoopPreheaders();
1260 return Changed;
1261}
1262
1263char LoopInterchange::ID = 0;
1264INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1265 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001266INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001267INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001268INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001269INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001270INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001271INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001272INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1273
1274INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1275 "Interchanges loops for cache reuse", false, false)
1276
1277Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }