blob: e9c1f2ed05f367609aeb589fbae72fd5078b8251 [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/BlockFrequencyInfo.h"
19#include "llvm/Analysis/CodeMetrics.h"
20#include "llvm/Analysis/DependenceAnalysis.h"
21#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/LoopIterator.h"
23#include "llvm/Analysis/LoopPass.h"
24#include "llvm/Analysis/ScalarEvolution.h"
25#include "llvm/Analysis/ScalarEvolutionExpander.h"
26#include "llvm/Analysis/ScalarEvolutionExpressions.h"
27#include "llvm/Analysis/TargetTransformInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000032#include "llvm/IR/InstIterator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include "llvm/IR/IntrinsicInst.h"
Karthik Bhat8210fdf2015-04-23 04:51:44 +000034#include "llvm/IR/Module.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000035#include "llvm/Pass.h"
36#include "llvm/Support/Debug.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000037#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000038#include "llvm/Transforms/Scalar.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000040#include "llvm/Transforms/Utils/LoopUtils.h"
41#include "llvm/Transforms/Utils/SSAUpdater.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000042using namespace llvm;
43
44#define DEBUG_TYPE "loop-interchange"
45
Chad Rosier72431892016-09-14 17:07:13 +000046static cl::opt<int> LoopInterchangeCostThreshold(
47 "loop-interchange-threshold", cl::init(0), cl::Hidden,
48 cl::desc("Interchange if you gain more than this number"));
49
Karthik Bhat88db86d2015-03-06 10:11:25 +000050namespace {
51
52typedef SmallVector<Loop *, 8> LoopVector;
53
54// TODO: Check if we can use a sparse matrix here.
55typedef std::vector<std::vector<char>> CharMatrix;
56
57// Maximum number of dependencies that can be handled in the dependency matrix.
58static const unsigned MaxMemInstrCount = 100;
59
60// Maximum loop depth supported.
61static const unsigned MaxLoopNestDepth = 10;
62
63struct LoopInterchange;
64
65#ifdef DUMP_DEP_MATRICIES
66void printDepMatrix(CharMatrix &DepMatrix) {
67 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) {
68 std::vector<char> Vec = *I;
69 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II)
70 DEBUG(dbgs() << *II << " ");
71 DEBUG(dbgs() << "\n");
72 }
73}
74#endif
75
Karthik Bhat8210fdf2015-04-23 04:51:44 +000076static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000077 Loop *L, DependenceInfo *DI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000078 typedef SmallVector<Value *, 16> ValueVector;
79 ValueVector MemInstr;
80
Karthik Bhat88db86d2015-03-06 10:11:25 +000081 // For each block.
82 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end();
83 BB != BE; ++BB) {
84 // Scan the BB and collect legal loads and stores.
85 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E;
86 ++I) {
Chad Rosier09c11092016-09-13 12:56:04 +000087 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000088 return false;
Chad Rosier09c11092016-09-13 12:56:04 +000089 if (LoadInst *Ld = dyn_cast<LoadInst>(I)) {
90 if (!Ld->isSimple())
91 return false;
92 MemInstr.push_back(&*I);
93 } else if (StoreInst *St = dyn_cast<StoreInst>(I)) {
94 if (!St->isSimple())
95 return false;
96 MemInstr.push_back(&*I);
97 }
Karthik Bhat88db86d2015-03-06 10:11:25 +000098 }
99 }
100
101 DEBUG(dbgs() << "Found " << MemInstr.size()
102 << " Loads and Stores to analyze\n");
103
104 ValueVector::iterator I, IE, J, JE;
105
106 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
107 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
108 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000109 Instruction *Src = cast<Instruction>(*I);
110 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000111 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000112 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000113 // Ignore Input dependencies.
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 Rosier00eb8db2016-09-21 19:16:47 +0000116 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000117 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000118 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
119 DEBUG(StringRef DepType =
120 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
121 dbgs() << "Found " << DepType
122 << " dependency between Src and Dst\n"
Chad Rosier90bcb912016-09-07 16:07:17 +0000123 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000124 unsigned Levels = D->getLevels();
125 char Direction;
126 for (unsigned II = 1; II <= Levels; ++II) {
127 const SCEV *Distance = D->getDistance(II);
128 const SCEVConstant *SCEVConst =
129 dyn_cast_or_null<SCEVConstant>(Distance);
130 if (SCEVConst) {
131 const ConstantInt *CI = SCEVConst->getValue();
132 if (CI->isNegative())
133 Direction = '<';
134 else if (CI->isZero())
135 Direction = '=';
136 else
137 Direction = '>';
138 Dep.push_back(Direction);
139 } else if (D->isScalar(II)) {
140 Direction = 'S';
141 Dep.push_back(Direction);
142 } else {
143 unsigned Dir = D->getDirection(II);
144 if (Dir == Dependence::DVEntry::LT ||
145 Dir == Dependence::DVEntry::LE)
146 Direction = '<';
147 else if (Dir == Dependence::DVEntry::GT ||
148 Dir == Dependence::DVEntry::GE)
149 Direction = '>';
150 else if (Dir == Dependence::DVEntry::EQ)
151 Direction = '=';
152 else
153 Direction = '*';
154 Dep.push_back(Direction);
155 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000156 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000157 while (Dep.size() != Level) {
158 Dep.push_back('I');
159 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000160
Chad Rosier00eb8db2016-09-21 19:16:47 +0000161 DepMatrix.push_back(Dep);
162 if (DepMatrix.size() > MaxMemInstrCount) {
163 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
164 << " dependencies inside loop\n");
165 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000166 }
167 }
168 }
169 }
170
Vikram TV74b41112015-12-09 05:16:24 +0000171 // We don't have a DepMatrix to check legality return false.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000172 if (DepMatrix.size() == 0)
173 return false;
174 return true;
175}
176
177// A loop is moved from index 'from' to an index 'to'. Update the Dependence
178// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000179static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
180 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000181 unsigned numRows = DepMatrix.size();
182 for (unsigned i = 0; i < numRows; ++i) {
183 char TmpVal = DepMatrix[i][ToIndx];
184 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
185 DepMatrix[i][FromIndx] = TmpVal;
186 }
187}
188
189// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
190// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000191static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
192 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000193 for (unsigned i = 0; i <= Column; ++i) {
194 if (DepMatrix[Row][i] == '<')
195 return false;
196 if (DepMatrix[Row][i] == '>')
197 return true;
198 }
199 // All dependencies were '=','S' or 'I'
200 return false;
201}
202
203// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000204static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
205 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000206 for (unsigned i = 0; i < Column; ++i) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000207 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000208 DepMatrix[Row][i] != 'I')
209 return false;
210 }
211 return true;
212}
213
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000214static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
215 unsigned OuterLoopId, char InnerDep,
216 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000217
218 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
219 return false;
220
221 if (InnerDep == OuterDep)
222 return true;
223
224 // It is legal to interchange if and only if after interchange no row has a
225 // '>' direction as the leftmost non-'='.
226
227 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
228 return true;
229
230 if (InnerDep == '<')
231 return true;
232
233 if (InnerDep == '>') {
234 // If OuterLoopId represents outermost loop then interchanging will make the
235 // 1st dependency as '>'
236 if (OuterLoopId == 0)
237 return false;
238
239 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
240 // interchanging will result in this row having an outermost non '='
241 // dependency of '>'
242 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
243 return true;
244 }
245
246 return false;
247}
248
249// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000250// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000251// if the direction matrix, after the same permutation is applied to its
252// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000253static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
254 unsigned InnerLoopId,
255 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000256
257 unsigned NumRows = DepMatrix.size();
258 // For each row check if it is valid to interchange.
259 for (unsigned Row = 0; Row < NumRows; ++Row) {
260 char InnerDep = DepMatrix[Row][InnerLoopId];
261 char OuterDep = DepMatrix[Row][OuterLoopId];
262 if (InnerDep == '*' || OuterDep == '*')
263 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000264 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000265 return false;
266 }
267 return true;
268}
269
270static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
271
Chad Rosierf5814f52016-09-07 15:56:59 +0000272 DEBUG(dbgs() << "Calling populateWorklist on Func: "
273 << L.getHeader()->getParent()->getName() << " Loop: %"
274 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000275 LoopVector LoopList;
276 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000277 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
278 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000279 // The current loop has multiple subloops in it hence it is not tightly
280 // nested.
281 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000282 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000283 LoopList.clear();
284 return;
285 }
286 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000287 CurrentLoop = Vec->front();
288 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000289 }
290 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000291 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000292}
293
294static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
295 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
296 if (InnerIndexVar)
297 return InnerIndexVar;
298 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
299 return nullptr;
300 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
301 PHINode *PhiVar = cast<PHINode>(I);
302 Type *PhiTy = PhiVar->getType();
303 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
304 !PhiTy->isPointerTy())
305 return nullptr;
306 const SCEVAddRecExpr *AddRec =
307 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
308 if (!AddRec || !AddRec->isAffine())
309 continue;
310 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000311 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000312 continue;
313 // Found the induction variable.
314 // FIXME: Handle loops with more than one induction variable. Note that,
315 // currently, legality makes sure we have only one induction variable.
316 return PhiVar;
317 }
318 return nullptr;
319}
320
321/// LoopInterchangeLegality checks if it is legal to interchange the loop.
322class LoopInterchangeLegality {
323public:
324 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Justin Bogner843fb202015-12-15 19:40:57 +0000325 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA)
326 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
327 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000328
329 /// Check if the loops can be interchanged.
330 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
331 CharMatrix &DepMatrix);
332 /// Check if the loop structure is understood. We do not handle triangular
333 /// loops for now.
334 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
335
336 bool currentLimitations();
337
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000338 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
339
Karthik Bhat88db86d2015-03-06 10:11:25 +0000340private:
341 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000342 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
343 bool areAllUsesReductions(Instruction *Ins, Loop *L);
344 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
345 bool findInductionAndReductions(Loop *L,
346 SmallVector<PHINode *, 8> &Inductions,
347 SmallVector<PHINode *, 8> &Reductions);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000348 Loop *OuterLoop;
349 Loop *InnerLoop;
350
Karthik Bhat88db86d2015-03-06 10:11:25 +0000351 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000352 LoopInfo *LI;
353 DominatorTree *DT;
354 bool PreserveLCSSA;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000355
356 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000357};
358
359/// LoopInterchangeProfitability checks if it is profitable to interchange the
360/// loop.
361class LoopInterchangeProfitability {
362public:
363 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE)
364 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {}
365
Vikram TV74b41112015-12-09 05:16:24 +0000366 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000367 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
368 CharMatrix &DepMatrix);
369
370private:
371 int getInstrOrderCost();
372
373 Loop *OuterLoop;
374 Loop *InnerLoop;
375
376 /// Scev analysis.
377 ScalarEvolution *SE;
378};
379
Vikram TV74b41112015-12-09 05:16:24 +0000380/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000381class LoopInterchangeTransform {
382public:
383 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
384 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000385 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000386 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000387 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000388 LoopExit(LoopNestExit),
389 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000390
391 /// Interchange OuterLoop and InnerLoop.
392 bool transform();
393 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
394 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000395
396private:
397 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000398 void splitInnerLoopHeader();
399 bool adjustLoopLinks();
400 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000401 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000402 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
403 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000404
405 Loop *OuterLoop;
406 Loop *InnerLoop;
407
408 /// Scev analysis.
409 ScalarEvolution *SE;
410 LoopInfo *LI;
411 DominatorTree *DT;
412 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000413 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000414};
415
Vikram TV74b41112015-12-09 05:16:24 +0000416// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000417struct LoopInterchange : public FunctionPass {
418 static char ID;
419 ScalarEvolution *SE;
420 LoopInfo *LI;
Chandler Carruth49c22192016-05-12 22:19:39 +0000421 DependenceInfo *DI;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000422 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000423 bool PreserveLCSSA;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000424 LoopInterchange()
Chandler Carruth49c22192016-05-12 22:19:39 +0000425 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000426 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
427 }
428
429 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000430 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000431 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000432 AU.addRequired<DominatorTreeWrapperPass>();
433 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000434 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000435 AU.addRequiredID(LoopSimplifyID);
436 AU.addRequiredID(LCSSAID);
437 }
438
439 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000440 if (skipFunction(F))
441 return false;
442
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000443 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000444 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000445 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000446 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
447 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000448 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
449
Karthik Bhat88db86d2015-03-06 10:11:25 +0000450 // Build up a worklist of loop pairs to analyze.
451 SmallVector<LoopVector, 8> Worklist;
452
453 for (Loop *L : *LI)
454 populateWorklist(*L, Worklist);
455
Chad Rosiera4c42462016-09-12 13:24:47 +0000456 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000457 bool Changed = true;
458 while (!Worklist.empty()) {
459 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000460 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000461 }
462 return Changed;
463 }
464
465 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000466 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000467 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
468 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000469 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000470 return false;
471 }
472 if (L->getNumBackEdges() != 1) {
473 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
474 return false;
475 }
476 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000477 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000478 return false;
479 }
480 }
481 return true;
482 }
483
Benjamin Kramerc321e532016-06-08 19:09:22 +0000484 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000485 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000486 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000487 return LoopList.size() - 1;
488 }
489
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000490 bool processLoopList(LoopVector LoopList, Function &F) {
491
Karthik Bhat88db86d2015-03-06 10:11:25 +0000492 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000493 unsigned LoopNestDepth = LoopList.size();
494 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000495 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
496 return false;
497 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000498 if (LoopNestDepth > MaxLoopNestDepth) {
499 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
500 << MaxLoopNestDepth << "\n");
501 return false;
502 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000503 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000504 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000505 return false;
506 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000507
508 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
509
510 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000511 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000512 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000513 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000514 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000515 return false;
516 }
517#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000518 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000519 printDepMatrix(DependencyMatrix);
520#endif
521
522 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
523 BranchInst *OuterMostLoopLatchBI =
524 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
525 if (!OuterMostLoopLatchBI)
526 return false;
527
528 // Since we currently do not handle LCSSA PHI's any failure in loop
529 // condition will now branch to LoopNestExit.
530 // TODO: This should be removed once we handle LCSSA PHI nodes.
531
532 // Get the Outermost loop exit.
533 BasicBlock *LoopNestExit;
534 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
535 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
536 else
537 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
538
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000539 if (isa<PHINode>(LoopNestExit->begin())) {
540 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
541 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000542 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000543 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000544
545 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000546 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000547 for (unsigned i = SelecLoopId; i > 0; i--) {
548 bool Interchanged =
549 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
550 if (!Interchanged)
551 return Changed;
552 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000553 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000554
555 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000556 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000557 DT->recalculate(F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000558#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000559 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000560 printDepMatrix(DependencyMatrix);
561#endif
562 Changed |= Interchanged;
563 }
564 return Changed;
565 }
566
567 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
568 unsigned OuterLoopId, BasicBlock *LoopNestExit,
569 std::vector<std::vector<char>> &DependencyMatrix) {
570
Chad Rosier13bc0d192016-09-07 18:15:12 +0000571 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000572 << " and OuterLoopId = " << OuterLoopId << "\n");
573 Loop *InnerLoop = LoopList[InnerLoopId];
574 Loop *OuterLoop = LoopList[OuterLoopId];
575
Justin Bogner843fb202015-12-15 19:40:57 +0000576 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
577 PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000578 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
579 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
580 return false;
581 }
582 DEBUG(dbgs() << "Loops are legal to interchange\n");
583 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE);
584 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000585 DEBUG(dbgs() << "Interchanging loops not profitable\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000586 return false;
587 }
588
Justin Bogner843fb202015-12-15 19:40:57 +0000589 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000590 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000591 LIT.transform();
592 DEBUG(dbgs() << "Loops interchanged\n");
593 return true;
594 }
595};
596
597} // end of namespace
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000598bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
David Majnemer0a16c222016-08-11 21:15:00 +0000599 return none_of(Ins->users(), [=](User *U) -> bool {
600 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000601 RecurrenceDescriptor RD;
602 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000603 });
604}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000605
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000606bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
607 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000608 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000609 // Load corresponding to reduction PHI's are safe while concluding if
610 // tightly nested.
611 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
612 if (!areAllUsesReductions(L, InnerLoop))
613 return true;
614 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
615 return true;
616 }
617 return false;
618}
619
620bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
621 BasicBlock *BB) {
622 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
623 // Stores corresponding to reductions are safe while concluding if tightly
624 // nested.
625 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000626 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000627 return true;
628 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000629 return true;
630 }
631 return false;
632}
633
634bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
635 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
636 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
637 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
638
Chad Rosierf7c76f92016-09-21 13:28:41 +0000639 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000640
641 // A perfectly nested loop will not have any branch in between the outer and
642 // inner block i.e. outer header will branch to either inner preheader and
643 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000644 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000645 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000646 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000647 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000648
649 for (unsigned i = 0, e = OuterLoopHeaderBI->getNumSuccessors(); i < e; ++i) {
650 if (OuterLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader &&
651 OuterLoopHeaderBI->getSuccessor(i) != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000652 return false;
653 }
654
Chad Rosierf7c76f92016-09-21 13:28:41 +0000655 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000656 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000657 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000658 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
659 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000660 return false;
661
Chad Rosierf7c76f92016-09-21 13:28:41 +0000662 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000663 // We have a perfect loop nest.
664 return true;
665}
666
Karthik Bhat88db86d2015-03-06 10:11:25 +0000667
668bool LoopInterchangeLegality::isLoopStructureUnderstood(
669 PHINode *InnerInduction) {
670
671 unsigned Num = InnerInduction->getNumOperands();
672 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
673 for (unsigned i = 0; i < Num; ++i) {
674 Value *Val = InnerInduction->getOperand(i);
675 if (isa<Constant>(Val))
676 continue;
677 Instruction *I = dyn_cast<Instruction>(Val);
678 if (!I)
679 return false;
680 // TODO: Handle triangular loops.
681 // e.g. for(int i=0;i<N;i++)
682 // for(int j=i;j<N;j++)
683 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
684 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
685 InnerLoopPreheader &&
686 !OuterLoop->isLoopInvariant(I)) {
687 return false;
688 }
689 }
690 return true;
691}
692
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000693bool LoopInterchangeLegality::findInductionAndReductions(
694 Loop *L, SmallVector<PHINode *, 8> &Inductions,
695 SmallVector<PHINode *, 8> &Reductions) {
696 if (!L->getLoopLatch() || !L->getLoopPredecessor())
697 return false;
698 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000699 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000700 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000701 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000702 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000703 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000704 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000705 Reductions.push_back(PHI);
706 else {
707 DEBUG(
708 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
709 return false;
710 }
711 }
712 return true;
713}
714
715static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
716 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
717 PHINode *PHI = cast<PHINode>(I);
718 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
719 if (PHI->getNumIncomingValues() > 1)
720 return false;
721 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
722 if (!Ins)
723 return false;
724 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
725 // exits lcssa phi else it would not be tightly nested.
726 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
727 return false;
728 }
729 return true;
730}
731
732static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
733 BasicBlock *LoopHeader) {
734 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
735 unsigned Num = BI->getNumSuccessors();
736 assert(Num == 2);
737 for (unsigned i = 0; i < Num; ++i) {
738 if (BI->getSuccessor(i) == LoopHeader)
739 continue;
740 return BI->getSuccessor(i);
741 }
742 }
743 return nullptr;
744}
745
Karthik Bhat88db86d2015-03-06 10:11:25 +0000746// This function indicates the current limitations in the transform as a result
747// of which we do not proceed.
748bool LoopInterchangeLegality::currentLimitations() {
749
750 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
751 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000752 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
753 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000754 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000755
756 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000757 SmallVector<PHINode *, 8> Inductions;
758 SmallVector<PHINode *, 8> Reductions;
759 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000760 return true;
761
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000762 // TODO: Currently we handle only loops with 1 induction variable.
763 if (Inductions.size() != 1) {
764 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
765 << "Failed to interchange due to current limitation\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000766 return true;
767 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000768 if (Reductions.size() > 0)
769 InnerLoopHasReduction = true;
770
771 InnerInductionVar = Inductions.pop_back_val();
772 Reductions.clear();
773 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions))
774 return true;
775
776 // Outer loop cannot have reduction because then loops will not be tightly
777 // nested.
778 if (!Reductions.empty())
779 return true;
780 // TODO: Currently we handle only loops with 1 induction variable.
781 if (Inductions.size() != 1)
782 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000783
784 // TODO: Triangular loops are not handled for now.
785 if (!isLoopStructureUnderstood(InnerInductionVar)) {
786 DEBUG(dbgs() << "Loop structure not understood by pass\n");
787 return true;
788 }
789
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000790 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
791 BasicBlock *LoopExitBlock =
792 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
793 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000794 return true;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000795
796 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
797 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000798 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000799
800 // TODO: Current limitation: Since we split the inner loop latch at the point
801 // were induction variable is incremented (induction.next); We cannot have
802 // more than 1 user of induction.next since it would result in broken code
803 // after split.
804 // e.g.
805 // for(i=0;i<N;i++) {
806 // for(j = 0;j<M;j++) {
807 // A[j+1][i+2] = A[j][i]+k;
808 // }
809 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000810 Instruction *InnerIndexVarInc = nullptr;
811 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
812 InnerIndexVarInc =
813 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
814 else
815 InnerIndexVarInc =
816 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
817
Pete Cooper11bd9582015-07-27 18:37:58 +0000818 if (!InnerIndexVarInc)
819 return true;
820
Karthik Bhat88db86d2015-03-06 10:11:25 +0000821 // Since we split the inner loop latch on this induction variable. Make sure
822 // we do not have any instruction between the induction variable and branch
823 // instruction.
824
David Majnemerd7708772016-06-24 04:05:21 +0000825 bool FoundInduction = false;
826 for (const Instruction &I : reverse(*InnerLoopLatch)) {
827 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000828 continue;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000829 // We found an instruction. If this is not induction variable then it is not
830 // safe to split this loop latch.
David Majnemerd7708772016-06-24 04:05:21 +0000831 if (!I.isIdenticalTo(InnerIndexVarInc))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000832 return true;
David Majnemerd7708772016-06-24 04:05:21 +0000833
834 FoundInduction = true;
835 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000836 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000837 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000838 // current limitation.
839 if (!FoundInduction)
840 return true;
841
842 return false;
843}
844
845bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
846 unsigned OuterLoopId,
847 CharMatrix &DepMatrix) {
848
849 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
850 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000851 << " and OuterLoopId = " << OuterLoopId
852 << " due to dependence\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000853 return false;
854 }
855
856 // Create unique Preheaders if we already do not have one.
857 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
858 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
859
860 // Create a unique outer preheader -
861 // 1) If OuterLoop preheader is not present.
862 // 2) If OuterLoop Preheader is same as OuterLoop Header
863 // 3) If OuterLoop Preheader is same as Header of the previous loop.
864 // 4) If OuterLoop Preheader is Entry node.
865 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
866 isa<PHINode>(OuterLoopPreHeader->begin()) ||
867 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000868 OuterLoopPreHeader =
869 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000870 }
871
872 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
873 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000874 InnerLoopPreHeader =
875 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000876 }
877
Karthik Bhat88db86d2015-03-06 10:11:25 +0000878 // TODO: The loops could not be interchanged due to current limitations in the
879 // transform module.
880 if (currentLimitations()) {
881 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
882 return false;
883 }
884
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000885 // Check if the loops are tightly nested.
886 if (!tightlyNested(OuterLoop, InnerLoop)) {
887 DEBUG(dbgs() << "Loops not tightly nested\n");
888 return false;
889 }
890
Karthik Bhat88db86d2015-03-06 10:11:25 +0000891 return true;
892}
893
894int LoopInterchangeProfitability::getInstrOrderCost() {
895 unsigned GoodOrder, BadOrder;
896 BadOrder = GoodOrder = 0;
897 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end();
898 BI != BE; ++BI) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000899 for (Instruction &Ins : **BI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000900 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
901 unsigned NumOp = GEP->getNumOperands();
902 bool FoundInnerInduction = false;
903 bool FoundOuterInduction = false;
904 for (unsigned i = 0; i < NumOp; ++i) {
905 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
906 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
907 if (!AR)
908 continue;
909
910 // If we find the inner induction after an outer induction e.g.
911 // for(int i=0;i<N;i++)
912 // for(int j=0;j<N;j++)
913 // A[i][j] = A[i-1][j-1]+k;
914 // then it is a good order.
915 if (AR->getLoop() == InnerLoop) {
916 // We found an InnerLoop induction after OuterLoop induction. It is
917 // a good order.
918 FoundInnerInduction = true;
919 if (FoundOuterInduction) {
920 GoodOrder++;
921 break;
922 }
923 }
924 // If we find the outer induction after an inner induction e.g.
925 // for(int i=0;i<N;i++)
926 // for(int j=0;j<N;j++)
927 // A[j][i] = A[j-1][i-1]+k;
928 // then it is a bad order.
929 if (AR->getLoop() == OuterLoop) {
930 // We found an OuterLoop induction after InnerLoop induction. It is
931 // a bad order.
932 FoundOuterInduction = true;
933 if (FoundInnerInduction) {
934 BadOrder++;
935 break;
936 }
937 }
938 }
939 }
940 }
941 }
942 return GoodOrder - BadOrder;
943}
944
Chad Rosiere6b3a632016-09-14 17:12:30 +0000945static bool isProfitableForVectorization(unsigned InnerLoopId,
946 unsigned OuterLoopId,
947 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000948 // TODO: Improve this heuristic to catch more cases.
949 // If the inner loop is loop independent or doesn't carry any dependency it is
950 // profitable to move this to outer position.
951 unsigned Row = DepMatrix.size();
952 for (unsigned i = 0; i < Row; ++i) {
953 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I')
954 return false;
955 // TODO: We need to improve this heuristic.
956 if (DepMatrix[i][OuterLoopId] != '=')
957 return false;
958 }
959 // If outer loop has dependence and inner loop is loop independent then it is
960 // profitable to interchange to enable parallelism.
961 return true;
962}
963
964bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
965 unsigned OuterLoopId,
966 CharMatrix &DepMatrix) {
967
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000968 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000969 // e.g
970 // 1) Construct dependency matrix and move the one with no loop carried dep
971 // inside to enable vectorization.
972
973 // This is rough cost estimation algorithm. It counts the good and bad order
974 // of induction variables in the instruction and allows reordering if number
975 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +0000976 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000977 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +0000978 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000979 return true;
980
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000981 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +0000982 // we can move this loop outside to improve parallelism.
983 bool ImprovesPar =
Chad Rosiere6b3a632016-09-14 17:12:30 +0000984 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000985 return ImprovesPar;
986}
987
988void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
989 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000990 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
991 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000992 if (*I == InnerLoop) {
993 OuterLoop->removeChildLoop(I);
994 return;
995 }
996 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +0000997 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000998}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000999
Karthik Bhat88db86d2015-03-06 10:11:25 +00001000void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1001 Loop *OuterLoop) {
1002 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1003 if (OuterLoopParent) {
1004 // Remove the loop from its parent loop.
1005 removeChildLoop(OuterLoopParent, OuterLoop);
1006 removeChildLoop(OuterLoop, InnerLoop);
1007 OuterLoopParent->addChildLoop(InnerLoop);
1008 } else {
1009 removeChildLoop(OuterLoop, InnerLoop);
1010 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1011 }
1012
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001013 while (!InnerLoop->empty())
1014 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001015
1016 InnerLoop->addChildLoop(OuterLoop);
1017}
1018
1019bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001020 bool Transformed = false;
1021 Instruction *InnerIndexVar;
1022
1023 if (InnerLoop->getSubLoops().size() == 0) {
1024 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1025 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1026 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1027 if (!InductionPHI) {
1028 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1029 return false;
1030 }
1031
1032 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1033 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1034 else
1035 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1036
1037 //
1038 // Split at the place were the induction variable is
1039 // incremented/decremented.
1040 // TODO: This splitting logic may not work always. Fix this.
1041 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001042 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001043
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001044 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001045 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001046 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001047 }
1048
1049 Transformed |= adjustLoopLinks();
1050 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001051 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001052 return false;
1053 }
1054
1055 restructureLoops(InnerLoop, OuterLoop);
1056 return true;
1057}
1058
Benjamin Kramer79442922015-03-06 18:59:14 +00001059void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001060 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001061 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001062 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001063}
1064
Karthik Bhat88db86d2015-03-06 10:11:25 +00001065void LoopInterchangeTransform::splitInnerLoopHeader() {
1066
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001067 // Split the inner loop header out. Here make sure that the reduction PHI's
1068 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001069 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001070 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1071 if (InnerLoopHasReduction) {
1072 // FIXME: Check if the induction PHI will always be the first PHI.
1073 BasicBlock *New = InnerLoopHeader->splitBasicBlock(
1074 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split");
1075 if (LI)
1076 if (Loop *L = LI->getLoopFor(InnerLoopHeader))
1077 L->addBasicBlockToLoop(New, *LI);
1078
1079 // Adjust Reduction PHI's in the block.
1080 SmallVector<PHINode *, 8> PHIVec;
1081 for (auto I = New->begin(); isa<PHINode>(I); ++I) {
1082 PHINode *PHI = dyn_cast<PHINode>(I);
1083 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1084 PHI->replaceAllUsesWith(V);
1085 PHIVec.push_back((PHI));
1086 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001087 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001088 P->eraseFromParent();
1089 }
1090 } else {
1091 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1092 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001093
1094 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001095 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001096}
1097
Benjamin Kramer79442922015-03-06 18:59:14 +00001098/// \brief Move all instructions except the terminator from FromBB right before
1099/// InsertBefore
1100static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1101 auto &ToList = InsertBefore->getParent()->getInstList();
1102 auto &FromList = FromBB->getInstList();
1103
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001104 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1105 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001106}
1107
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001108void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1109 BasicBlock *OldPred,
1110 BasicBlock *NewPred) {
1111 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1112 PHINode *PHI = cast<PHINode>(I);
1113 unsigned Num = PHI->getNumIncomingValues();
1114 for (unsigned i = 0; i < Num; ++i) {
1115 if (PHI->getIncomingBlock(i) == OldPred)
1116 PHI->setIncomingBlock(i, NewPred);
1117 }
1118 }
1119}
1120
Karthik Bhat88db86d2015-03-06 10:11:25 +00001121bool LoopInterchangeTransform::adjustLoopBranches() {
1122
1123 DEBUG(dbgs() << "adjustLoopBranches called\n");
1124 // Adjust the loop preheader
1125 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1126 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1127 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1128 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1129 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1130 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1131 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1132 BasicBlock *InnerLoopLatchPredecessor =
1133 InnerLoopLatch->getUniquePredecessor();
1134 BasicBlock *InnerLoopLatchSuccessor;
1135 BasicBlock *OuterLoopLatchSuccessor;
1136
1137 BranchInst *OuterLoopLatchBI =
1138 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1139 BranchInst *InnerLoopLatchBI =
1140 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1141 BranchInst *OuterLoopHeaderBI =
1142 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1143 BranchInst *InnerLoopHeaderBI =
1144 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1145
1146 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1147 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1148 !InnerLoopHeaderBI)
1149 return false;
1150
1151 BranchInst *InnerLoopLatchPredecessorBI =
1152 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1153 BranchInst *OuterLoopPredecessorBI =
1154 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1155
1156 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1157 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001158 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1159 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001160 return false;
1161
1162 // Adjust Loop Preheader and headers
1163
1164 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1165 for (unsigned i = 0; i < NumSucc; ++i) {
1166 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1167 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1168 }
1169
1170 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1171 for (unsigned i = 0; i < NumSucc; ++i) {
1172 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1173 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1174 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001175 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001176 }
1177
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001178 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001179 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001180 OuterLoopHeader);
1181
Karthik Bhat88db86d2015-03-06 10:11:25 +00001182 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1183 InnerLoopHeaderBI->eraseFromParent();
1184
1185 // -------------Adjust loop latches-----------
1186 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1187 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1188 else
1189 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1190
1191 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1192 for (unsigned i = 0; i < NumSucc; ++i) {
1193 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1194 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1195 }
1196
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001197 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1198 // the value and remove this PHI node from inner loop.
1199 SmallVector<PHINode *, 8> LcssaVec;
1200 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1201 PHINode *LcssaPhi = cast<PHINode>(I);
1202 LcssaVec.push_back(LcssaPhi);
1203 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001204 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001205 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1206 P->replaceAllUsesWith(Incoming);
1207 P->eraseFromParent();
1208 }
1209
Karthik Bhat88db86d2015-03-06 10:11:25 +00001210 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1211 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1212 else
1213 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1214
1215 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1216 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1217 else
1218 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1219
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001220 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1221
Karthik Bhat88db86d2015-03-06 10:11:25 +00001222 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1223 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1224 } else {
1225 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1226 }
1227
1228 return true;
1229}
1230void LoopInterchangeTransform::adjustLoopPreheaders() {
1231
1232 // We have interchanged the preheaders so we need to interchange the data in
1233 // the preheader as well.
1234 // This is because the content of inner preheader was previously executed
1235 // inside the outer loop.
1236 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1237 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1238 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1239 BranchInst *InnerTermBI =
1240 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1241
Karthik Bhat88db86d2015-03-06 10:11:25 +00001242 // These instructions should now be executed inside the loop.
1243 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001244 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001245 // These instructions were not executed previously in the loop so move them to
1246 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001247 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001248}
1249
1250bool LoopInterchangeTransform::adjustLoopLinks() {
1251
1252 // Adjust all branches in the inner and outer loop.
1253 bool Changed = adjustLoopBranches();
1254 if (Changed)
1255 adjustLoopPreheaders();
1256 return Changed;
1257}
1258
1259char LoopInterchange::ID = 0;
1260INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1261 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001262INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001263INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001264INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001265INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001266INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001267INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001268INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1269
1270INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1271 "Interchanges loops for cache reuse", false, false)
1272
1273Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }