blob: a326f126be87a34def816cb843795e3758aa6004 [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000018#include "llvm/Analysis/AssumptionCache.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000019#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"
Adam Nemet0965da22017-10-09 23:19:02 +000025#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000026#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/Analysis/TargetTransformInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000031#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000034#include "llvm/IR/InstIterator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/IR/IntrinsicInst.h"
Karthik Bhat8210fdf2015-04-23 04:51:44 +000036#include "llvm/IR/Module.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000037#include "llvm/Pass.h"
38#include "llvm/Support/Debug.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000039#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000040#include "llvm/Transforms/Scalar.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000042#include "llvm/Transforms/Utils/LoopUtils.h"
Davide Italiano9d8f6f82017-01-29 01:55:24 +000043
Karthik Bhat88db86d2015-03-06 10:11:25 +000044using namespace llvm;
45
46#define DEBUG_TYPE "loop-interchange"
47
Chad Rosier72431892016-09-14 17:07:13 +000048static cl::opt<int> LoopInterchangeCostThreshold(
49 "loop-interchange-threshold", cl::init(0), cl::Hidden,
50 cl::desc("Interchange if you gain more than this number"));
51
Karthik Bhat88db86d2015-03-06 10:11:25 +000052namespace {
53
54typedef SmallVector<Loop *, 8> LoopVector;
55
56// TODO: Check if we can use a sparse matrix here.
57typedef std::vector<std::vector<char>> CharMatrix;
58
59// Maximum number of dependencies that can be handled in the dependency matrix.
60static const unsigned MaxMemInstrCount = 100;
61
62// Maximum loop depth supported.
63static const unsigned MaxLoopNestDepth = 10;
64
65struct LoopInterchange;
66
67#ifdef DUMP_DEP_MATRICIES
68void printDepMatrix(CharMatrix &DepMatrix) {
Florian Hahnf66efd62017-07-24 11:41:30 +000069 for (auto &Row : DepMatrix) {
70 for (auto D : Row)
71 DEBUG(dbgs() << D << " ");
Karthik Bhat88db86d2015-03-06 10:11:25 +000072 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.
Florian Hahnf66efd62017-07-24 11:41:30 +000083 for (BasicBlock *BB : L->blocks()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000084 // Scan the BB and collect legal loads and stores.
Florian Hahnf66efd62017-07-24 11:41:30 +000085 for (Instruction &I : *BB) {
Chad Rosier09c11092016-09-13 12:56:04 +000086 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000087 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000088 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000089 if (!Ld->isSimple())
90 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000091 MemInstr.push_back(&I);
92 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000093 if (!St->isSimple())
94 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000095 MemInstr.push_back(&I);
Chad Rosier09c11092016-09-13 12:56:04 +000096 }
Karthik Bhat88db86d2015-03-06 10:11:25 +000097 }
98 }
99
100 DEBUG(dbgs() << "Found " << MemInstr.size()
101 << " Loads and Stores to analyze\n");
102
103 ValueVector::iterator I, IE, J, JE;
104
105 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
106 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
107 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000108 Instruction *Src = cast<Instruction>(*I);
109 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000110 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000111 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000112 // Ignore Input dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000113 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000114 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000115 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000116 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000117 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
118 DEBUG(StringRef DepType =
119 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
120 dbgs() << "Found " << DepType
121 << " dependency between Src and Dst\n"
Chad Rosier90bcb912016-09-07 16:07:17 +0000122 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000123 unsigned Levels = D->getLevels();
124 char Direction;
125 for (unsigned II = 1; II <= Levels; ++II) {
126 const SCEV *Distance = D->getDistance(II);
127 const SCEVConstant *SCEVConst =
128 dyn_cast_or_null<SCEVConstant>(Distance);
129 if (SCEVConst) {
130 const ConstantInt *CI = SCEVConst->getValue();
131 if (CI->isNegative())
132 Direction = '<';
133 else if (CI->isZero())
134 Direction = '=';
135 else
136 Direction = '>';
137 Dep.push_back(Direction);
138 } else if (D->isScalar(II)) {
139 Direction = 'S';
140 Dep.push_back(Direction);
141 } else {
142 unsigned Dir = D->getDirection(II);
143 if (Dir == Dependence::DVEntry::LT ||
144 Dir == Dependence::DVEntry::LE)
145 Direction = '<';
146 else if (Dir == Dependence::DVEntry::GT ||
147 Dir == Dependence::DVEntry::GE)
148 Direction = '>';
149 else if (Dir == Dependence::DVEntry::EQ)
150 Direction = '=';
151 else
152 Direction = '*';
153 Dep.push_back(Direction);
154 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000155 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000156 while (Dep.size() != Level) {
157 Dep.push_back('I');
158 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000159
Chad Rosier00eb8db2016-09-21 19:16:47 +0000160 DepMatrix.push_back(Dep);
161 if (DepMatrix.size() > MaxMemInstrCount) {
162 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
163 << " dependencies inside loop\n");
164 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000165 }
166 }
167 }
168 }
169
Vikram TV74b41112015-12-09 05:16:24 +0000170 // We don't have a DepMatrix to check legality return false.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000171 if (DepMatrix.size() == 0)
172 return false;
173 return true;
174}
175
176// A loop is moved from index 'from' to an index 'to'. Update the Dependence
177// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000178static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
179 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000180 unsigned numRows = DepMatrix.size();
181 for (unsigned i = 0; i < numRows; ++i) {
182 char TmpVal = DepMatrix[i][ToIndx];
183 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
184 DepMatrix[i][FromIndx] = TmpVal;
185 }
186}
187
188// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
189// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000190static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
191 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000192 for (unsigned i = 0; i <= Column; ++i) {
193 if (DepMatrix[Row][i] == '<')
194 return false;
195 if (DepMatrix[Row][i] == '>')
196 return true;
197 }
198 // All dependencies were '=','S' or 'I'
199 return false;
200}
201
202// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000203static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
204 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000205 for (unsigned i = 0; i < Column; ++i) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000206 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000207 DepMatrix[Row][i] != 'I')
208 return false;
209 }
210 return true;
211}
212
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000213static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
214 unsigned OuterLoopId, char InnerDep,
215 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000216
217 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
218 return false;
219
220 if (InnerDep == OuterDep)
221 return true;
222
223 // It is legal to interchange if and only if after interchange no row has a
224 // '>' direction as the leftmost non-'='.
225
226 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
227 return true;
228
229 if (InnerDep == '<')
230 return true;
231
232 if (InnerDep == '>') {
233 // If OuterLoopId represents outermost loop then interchanging will make the
234 // 1st dependency as '>'
235 if (OuterLoopId == 0)
236 return false;
237
238 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
239 // interchanging will result in this row having an outermost non '='
240 // dependency of '>'
241 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
242 return true;
243 }
244
245 return false;
246}
247
248// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000249// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000250// if the direction matrix, after the same permutation is applied to its
251// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000252static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
253 unsigned InnerLoopId,
254 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000255
256 unsigned NumRows = DepMatrix.size();
257 // For each row check if it is valid to interchange.
258 for (unsigned Row = 0; Row < NumRows; ++Row) {
259 char InnerDep = DepMatrix[Row][InnerLoopId];
260 char OuterDep = DepMatrix[Row][OuterLoopId];
261 if (InnerDep == '*' || OuterDep == '*')
262 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000263 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000264 return false;
265 }
266 return true;
267}
268
269static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
270
Chad Rosierf5814f52016-09-07 15:56:59 +0000271 DEBUG(dbgs() << "Calling populateWorklist on Func: "
272 << L.getHeader()->getParent()->getName() << " Loop: %"
273 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000274 LoopVector LoopList;
275 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000276 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
277 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000278 // The current loop has multiple subloops in it hence it is not tightly
279 // nested.
280 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000281 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000282 LoopList.clear();
283 return;
284 }
285 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000286 CurrentLoop = Vec->front();
287 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000288 }
289 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000290 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000291}
292
293static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
294 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
295 if (InnerIndexVar)
296 return InnerIndexVar;
297 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
298 return nullptr;
299 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
300 PHINode *PhiVar = cast<PHINode>(I);
301 Type *PhiTy = PhiVar->getType();
302 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
303 !PhiTy->isPointerTy())
304 return nullptr;
305 const SCEVAddRecExpr *AddRec =
306 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
307 if (!AddRec || !AddRec->isAffine())
308 continue;
309 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000310 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000311 continue;
312 // Found the induction variable.
313 // FIXME: Handle loops with more than one induction variable. Note that,
314 // currently, legality makes sure we have only one induction variable.
315 return PhiVar;
316 }
317 return nullptr;
318}
319
320/// LoopInterchangeLegality checks if it is legal to interchange the loop.
321class LoopInterchangeLegality {
322public:
323 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000324 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA,
325 OptimizationRemarkEmitter *ORE)
Justin Bogner843fb202015-12-15 19:40:57 +0000326 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Florian Hahnad993522017-07-15 13:13:19 +0000327 PreserveLCSSA(PreserveLCSSA), ORE(ORE), 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;
Florian Hahnad993522017-07-15 13:13:19 +0000355 /// Interface to emit optimization remarks.
356 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000357
358 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000359};
360
361/// LoopInterchangeProfitability checks if it is profitable to interchange the
362/// loop.
363class LoopInterchangeProfitability {
364public:
Florian Hahnad993522017-07-15 13:13:19 +0000365 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
366 OptimizationRemarkEmitter *ORE)
367 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000368
Vikram TV74b41112015-12-09 05:16:24 +0000369 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000370 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
371 CharMatrix &DepMatrix);
372
373private:
374 int getInstrOrderCost();
375
376 Loop *OuterLoop;
377 Loop *InnerLoop;
378
379 /// Scev analysis.
380 ScalarEvolution *SE;
Florian Hahnad993522017-07-15 13:13:19 +0000381 /// Interface to emit optimization remarks.
382 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000383};
384
Vikram TV74b41112015-12-09 05:16:24 +0000385/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000386class LoopInterchangeTransform {
387public:
388 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
389 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000390 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000391 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000392 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000393 LoopExit(LoopNestExit),
394 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000395
396 /// Interchange OuterLoop and InnerLoop.
397 bool transform();
398 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
399 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000400
401private:
402 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000403 void splitInnerLoopHeader();
404 bool adjustLoopLinks();
405 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000406 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000407 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
408 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000409
410 Loop *OuterLoop;
411 Loop *InnerLoop;
412
413 /// Scev analysis.
414 ScalarEvolution *SE;
415 LoopInfo *LI;
416 DominatorTree *DT;
417 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000418 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000419};
420
Vikram TV74b41112015-12-09 05:16:24 +0000421// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000422struct LoopInterchange : public FunctionPass {
423 static char ID;
424 ScalarEvolution *SE;
425 LoopInfo *LI;
Chandler Carruth49c22192016-05-12 22:19:39 +0000426 DependenceInfo *DI;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000427 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000428 bool PreserveLCSSA;
Florian Hahnad993522017-07-15 13:13:19 +0000429 /// Interface to emit optimization remarks.
430 OptimizationRemarkEmitter *ORE;
431
Karthik Bhat88db86d2015-03-06 10:11:25 +0000432 LoopInterchange()
Chandler Carruth49c22192016-05-12 22:19:39 +0000433 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000434 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
435 }
436
437 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000438 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000439 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000440 AU.addRequired<DominatorTreeWrapperPass>();
441 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000442 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000443 AU.addRequiredID(LoopSimplifyID);
444 AU.addRequiredID(LCSSAID);
Florian Hahnad993522017-07-15 13:13:19 +0000445 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000446 }
447
448 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000449 if (skipFunction(F))
450 return false;
451
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000452 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000453 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000454 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000455 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
456 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Florian Hahnad993522017-07-15 13:13:19 +0000457 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000458 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
459
Karthik Bhat88db86d2015-03-06 10:11:25 +0000460 // Build up a worklist of loop pairs to analyze.
461 SmallVector<LoopVector, 8> Worklist;
462
463 for (Loop *L : *LI)
464 populateWorklist(*L, Worklist);
465
Chad Rosiera4c42462016-09-12 13:24:47 +0000466 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000467 bool Changed = true;
468 while (!Worklist.empty()) {
469 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000470 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000471 }
472 return Changed;
473 }
474
475 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000476 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000477 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
478 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000479 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000480 return false;
481 }
482 if (L->getNumBackEdges() != 1) {
483 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
484 return false;
485 }
486 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000487 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000488 return false;
489 }
490 }
491 return true;
492 }
493
Benjamin Kramerc321e532016-06-08 19:09:22 +0000494 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000495 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000496 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000497 return LoopList.size() - 1;
498 }
499
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000500 bool processLoopList(LoopVector LoopList, Function &F) {
501
Karthik Bhat88db86d2015-03-06 10:11:25 +0000502 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000503 unsigned LoopNestDepth = LoopList.size();
504 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000505 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
506 return false;
507 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000508 if (LoopNestDepth > MaxLoopNestDepth) {
509 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
510 << MaxLoopNestDepth << "\n");
511 return false;
512 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000513 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000514 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000515 return false;
516 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000517
518 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
519
520 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000521 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000522 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000523 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000524 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000525 return false;
526 }
527#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000528 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000529 printDepMatrix(DependencyMatrix);
530#endif
531
532 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
533 BranchInst *OuterMostLoopLatchBI =
534 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
535 if (!OuterMostLoopLatchBI)
536 return false;
537
538 // Since we currently do not handle LCSSA PHI's any failure in loop
539 // condition will now branch to LoopNestExit.
540 // TODO: This should be removed once we handle LCSSA PHI nodes.
541
542 // Get the Outermost loop exit.
543 BasicBlock *LoopNestExit;
544 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
545 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
546 else
547 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
548
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000549 if (isa<PHINode>(LoopNestExit->begin())) {
550 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
551 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000552 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000553 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000554
555 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000556 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000557 for (unsigned i = SelecLoopId; i > 0; i--) {
558 bool Interchanged =
559 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
560 if (!Interchanged)
561 return Changed;
562 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000563 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000564
565 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000566 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000567 DT->recalculate(F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000568#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000569 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000570 printDepMatrix(DependencyMatrix);
571#endif
572 Changed |= Interchanged;
573 }
574 return Changed;
575 }
576
577 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
578 unsigned OuterLoopId, BasicBlock *LoopNestExit,
579 std::vector<std::vector<char>> &DependencyMatrix) {
580
Chad Rosier13bc0d192016-09-07 18:15:12 +0000581 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000582 << " and OuterLoopId = " << OuterLoopId << "\n");
583 Loop *InnerLoop = LoopList[InnerLoopId];
584 Loop *OuterLoop = LoopList[OuterLoopId];
585
Justin Bogner843fb202015-12-15 19:40:57 +0000586 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
Florian Hahnad993522017-07-15 13:13:19 +0000587 PreserveLCSSA, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000588 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
589 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
590 return false;
591 }
592 DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000593 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000594 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000595 DEBUG(dbgs() << "Interchanging loops not profitable\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000596 return false;
597 }
598
Vivek Pandya95906582017-10-11 17:12:59 +0000599 ORE->emit([&]() {
600 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
601 InnerLoop->getStartLoc(),
602 InnerLoop->getHeader())
603 << "Loop interchanged with enclosing loop.";
604 });
Florian Hahnad993522017-07-15 13:13:19 +0000605
Justin Bogner843fb202015-12-15 19:40:57 +0000606 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000607 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000608 LIT.transform();
609 DEBUG(dbgs() << "Loops interchanged\n");
610 return true;
611 }
612};
613
614} // end of namespace
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000615bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
David Majnemer0a16c222016-08-11 21:15:00 +0000616 return none_of(Ins->users(), [=](User *U) -> bool {
617 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000618 RecurrenceDescriptor RD;
619 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000620 });
621}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000622
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000623bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
624 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000625 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000626 // Load corresponding to reduction PHI's are safe while concluding if
627 // tightly nested.
628 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
629 if (!areAllUsesReductions(L, InnerLoop))
630 return true;
631 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
632 return true;
633 }
634 return false;
635}
636
637bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
638 BasicBlock *BB) {
639 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
640 // Stores corresponding to reductions are safe while concluding if tightly
641 // nested.
642 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000643 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000644 return true;
645 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000646 return true;
647 }
648 return false;
649}
650
651bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
652 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
653 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
654 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
655
Chad Rosierf7c76f92016-09-21 13:28:41 +0000656 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000657
658 // A perfectly nested loop will not have any branch in between the outer and
659 // inner block i.e. outer header will branch to either inner preheader and
660 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000661 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000662 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000663 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000664 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000665
Florian Hahnf66efd62017-07-24 11:41:30 +0000666 for (BasicBlock *Succ : OuterLoopHeaderBI->successors())
667 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000668 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000669
Chad Rosierf7c76f92016-09-21 13:28:41 +0000670 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000671 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000672 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000673 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
674 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000675 return false;
676
Chad Rosierf7c76f92016-09-21 13:28:41 +0000677 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000678 // We have a perfect loop nest.
679 return true;
680}
681
Karthik Bhat88db86d2015-03-06 10:11:25 +0000682
683bool LoopInterchangeLegality::isLoopStructureUnderstood(
684 PHINode *InnerInduction) {
685
686 unsigned Num = InnerInduction->getNumOperands();
687 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
688 for (unsigned i = 0; i < Num; ++i) {
689 Value *Val = InnerInduction->getOperand(i);
690 if (isa<Constant>(Val))
691 continue;
692 Instruction *I = dyn_cast<Instruction>(Val);
693 if (!I)
694 return false;
695 // TODO: Handle triangular loops.
696 // e.g. for(int i=0;i<N;i++)
697 // for(int j=i;j<N;j++)
698 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
699 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
700 InnerLoopPreheader &&
701 !OuterLoop->isLoopInvariant(I)) {
702 return false;
703 }
704 }
705 return true;
706}
707
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000708bool LoopInterchangeLegality::findInductionAndReductions(
709 Loop *L, SmallVector<PHINode *, 8> &Inductions,
710 SmallVector<PHINode *, 8> &Reductions) {
711 if (!L->getLoopLatch() || !L->getLoopPredecessor())
712 return false;
713 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000714 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000715 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000716 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000717 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000718 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000719 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000720 Reductions.push_back(PHI);
721 else {
722 DEBUG(
723 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
724 return false;
725 }
726 }
727 return true;
728}
729
730static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
731 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
732 PHINode *PHI = cast<PHINode>(I);
733 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
734 if (PHI->getNumIncomingValues() > 1)
735 return false;
736 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
737 if (!Ins)
738 return false;
739 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
740 // exits lcssa phi else it would not be tightly nested.
741 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
742 return false;
743 }
744 return true;
745}
746
747static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
748 BasicBlock *LoopHeader) {
749 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
Florian Hahnf66efd62017-07-24 11:41:30 +0000750 assert(BI->getNumSuccessors() == 2 &&
751 "Branch leaving loop latch must have 2 successors");
752 for (BasicBlock *Succ : BI->successors()) {
753 if (Succ == LoopHeader)
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000754 continue;
Florian Hahnf66efd62017-07-24 11:41:30 +0000755 return Succ;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000756 }
757 }
758 return nullptr;
759}
760
Karthik Bhat88db86d2015-03-06 10:11:25 +0000761// This function indicates the current limitations in the transform as a result
762// of which we do not proceed.
763bool LoopInterchangeLegality::currentLimitations() {
764
765 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
766 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000767 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
768 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000769 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000770
771 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000772 SmallVector<PHINode *, 8> Inductions;
773 SmallVector<PHINode *, 8> Reductions;
Florian Hahn4eeff392017-07-03 15:32:00 +0000774 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
775 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes "
776 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000777 ORE->emit([&]() {
778 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
779 InnerLoop->getStartLoc(),
780 InnerLoop->getHeader())
781 << "Only inner loops with induction or reduction PHI nodes can be"
782 " interchange currently.";
783 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000784 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000785 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000786
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000787 // TODO: Currently we handle only loops with 1 induction variable.
788 if (Inductions.size() != 1) {
789 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
790 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000791 ORE->emit([&]() {
792 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
793 InnerLoop->getStartLoc(),
794 InnerLoop->getHeader())
795 << "Only inner loops with 1 induction variable can be "
796 "interchanged currently.";
797 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000798 return true;
799 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000800 if (Reductions.size() > 0)
801 InnerLoopHasReduction = true;
802
803 InnerInductionVar = Inductions.pop_back_val();
804 Reductions.clear();
Florian Hahn4eeff392017-07-03 15:32:00 +0000805 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
806 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes "
807 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000808 ORE->emit([&]() {
809 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
810 OuterLoop->getStartLoc(),
811 OuterLoop->getHeader())
812 << "Only outer loops with induction or reduction PHI nodes can be"
813 " interchanged currently.";
814 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000815 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000816 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000817
818 // Outer loop cannot have reduction because then loops will not be tightly
819 // nested.
Florian Hahn4eeff392017-07-03 15:32:00 +0000820 if (!Reductions.empty()) {
821 DEBUG(dbgs() << "Outer loops with reductions are not supported "
822 << "currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000823 ORE->emit([&]() {
824 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter",
825 OuterLoop->getStartLoc(),
826 OuterLoop->getHeader())
827 << "Outer loops with reductions cannot be interchangeed "
828 "currently.";
829 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000830 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000831 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000832 // TODO: Currently we handle only loops with 1 induction variable.
Florian Hahn4eeff392017-07-03 15:32:00 +0000833 if (Inductions.size() != 1) {
834 DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
835 << "supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000836 ORE->emit([&]() {
837 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
838 OuterLoop->getStartLoc(),
839 OuterLoop->getHeader())
840 << "Only outer loops with 1 induction variable can be "
841 "interchanged currently.";
842 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000843 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000844 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000845
846 // TODO: Triangular loops are not handled for now.
847 if (!isLoopStructureUnderstood(InnerInductionVar)) {
848 DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000849 ORE->emit([&]() {
850 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
851 InnerLoop->getStartLoc(),
852 InnerLoop->getHeader())
853 << "Inner loop structure not understood currently.";
854 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000855 return true;
856 }
857
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000858 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
859 BasicBlock *LoopExitBlock =
860 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000861 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) {
862 DEBUG(dbgs() << "Can only handle LCSSA PHIs in outer loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000863 ORE->emit([&]() {
864 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuter",
865 OuterLoop->getStartLoc(),
866 OuterLoop->getHeader())
867 << "Only outer loops with LCSSA PHIs can be interchange "
868 "currently.";
869 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000870 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000871 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000872
873 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000874 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) {
875 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000876 ORE->emit([&]() {
877 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
878 InnerLoop->getStartLoc(),
879 InnerLoop->getHeader())
880 << "Only inner loops with LCSSA PHIs can be interchange "
881 "currently.";
882 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000883 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000884 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000885
886 // TODO: Current limitation: Since we split the inner loop latch at the point
887 // were induction variable is incremented (induction.next); We cannot have
888 // more than 1 user of induction.next since it would result in broken code
889 // after split.
890 // e.g.
891 // for(i=0;i<N;i++) {
892 // for(j = 0;j<M;j++) {
893 // A[j+1][i+2] = A[j][i]+k;
894 // }
895 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000896 Instruction *InnerIndexVarInc = nullptr;
897 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
898 InnerIndexVarInc =
899 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
900 else
901 InnerIndexVarInc =
902 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
903
Florian Hahn4eeff392017-07-03 15:32:00 +0000904 if (!InnerIndexVarInc) {
905 DEBUG(dbgs() << "Did not find an instruction to increment the induction "
906 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000907 ORE->emit([&]() {
908 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
909 InnerLoop->getStartLoc(),
910 InnerLoop->getHeader())
911 << "The inner loop does not increment the induction variable.";
912 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000913 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000914 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000915
Karthik Bhat88db86d2015-03-06 10:11:25 +0000916 // Since we split the inner loop latch on this induction variable. Make sure
917 // we do not have any instruction between the induction variable and branch
918 // instruction.
919
David Majnemerd7708772016-06-24 04:05:21 +0000920 bool FoundInduction = false;
921 for (const Instruction &I : reverse(*InnerLoopLatch)) {
Florian Hahncd783452017-08-25 16:52:29 +0000922 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
923 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000924 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000925
Karthik Bhat88db86d2015-03-06 10:11:25 +0000926 // We found an instruction. If this is not induction variable then it is not
927 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000928 if (!I.isIdenticalTo(InnerIndexVarInc)) {
929 DEBUG(dbgs() << "Found unsupported instructions between induction "
930 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000931 ORE->emit([&]() {
932 return OptimizationRemarkMissed(
933 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
934 InnerLoop->getStartLoc(), InnerLoop->getHeader())
935 << "Found unsupported instruction between induction variable "
936 "increment and branch.";
937 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000938 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000939 }
David Majnemerd7708772016-06-24 04:05:21 +0000940
941 FoundInduction = true;
942 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000943 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000944 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000945 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000946 if (!FoundInduction) {
947 DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000948 ORE->emit([&]() {
949 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
950 InnerLoop->getStartLoc(),
951 InnerLoop->getHeader())
952 << "Did not find the induction variable.";
953 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000954 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000955 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000956 return false;
957}
958
959bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
960 unsigned OuterLoopId,
961 CharMatrix &DepMatrix) {
962
963 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
964 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000965 << " and OuterLoopId = " << OuterLoopId
966 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000967 ORE->emit([&]() {
968 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
969 InnerLoop->getStartLoc(),
970 InnerLoop->getHeader())
971 << "Cannot interchange loops due to dependences.";
972 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000973 return false;
974 }
975
Florian Hahn42840492017-07-31 09:00:52 +0000976 // Check if outer and inner loop contain legal instructions only.
977 for (auto *BB : OuterLoop->blocks())
978 for (Instruction &I : *BB)
979 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
980 // readnone functions do not prevent interchanging.
981 if (CI->doesNotReadMemory())
982 continue;
983 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged "
984 << "safely.");
985 return false;
986 }
987
Karthik Bhat88db86d2015-03-06 10:11:25 +0000988 // Create unique Preheaders if we already do not have one.
989 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
990 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
991
992 // Create a unique outer preheader -
993 // 1) If OuterLoop preheader is not present.
994 // 2) If OuterLoop Preheader is same as OuterLoop Header
995 // 3) If OuterLoop Preheader is same as Header of the previous loop.
996 // 4) If OuterLoop Preheader is Entry node.
997 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
998 isa<PHINode>(OuterLoopPreHeader->begin()) ||
999 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001000 OuterLoopPreHeader =
1001 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001002 }
1003
1004 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
1005 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001006 InnerLoopPreHeader =
1007 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001008 }
1009
Karthik Bhat88db86d2015-03-06 10:11:25 +00001010 // TODO: The loops could not be interchanged due to current limitations in the
1011 // transform module.
1012 if (currentLimitations()) {
1013 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1014 return false;
1015 }
1016
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001017 // Check if the loops are tightly nested.
1018 if (!tightlyNested(OuterLoop, InnerLoop)) {
1019 DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001020 ORE->emit([&]() {
1021 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1022 InnerLoop->getStartLoc(),
1023 InnerLoop->getHeader())
1024 << "Cannot interchange loops because they are not tightly "
1025 "nested.";
1026 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001027 return false;
1028 }
1029
Karthik Bhat88db86d2015-03-06 10:11:25 +00001030 return true;
1031}
1032
1033int LoopInterchangeProfitability::getInstrOrderCost() {
1034 unsigned GoodOrder, BadOrder;
1035 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001036 for (BasicBlock *BB : InnerLoop->blocks()) {
1037 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001038 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1039 unsigned NumOp = GEP->getNumOperands();
1040 bool FoundInnerInduction = false;
1041 bool FoundOuterInduction = false;
1042 for (unsigned i = 0; i < NumOp; ++i) {
1043 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1044 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1045 if (!AR)
1046 continue;
1047
1048 // If we find the inner induction after an outer induction e.g.
1049 // for(int i=0;i<N;i++)
1050 // for(int j=0;j<N;j++)
1051 // A[i][j] = A[i-1][j-1]+k;
1052 // then it is a good order.
1053 if (AR->getLoop() == InnerLoop) {
1054 // We found an InnerLoop induction after OuterLoop induction. It is
1055 // a good order.
1056 FoundInnerInduction = true;
1057 if (FoundOuterInduction) {
1058 GoodOrder++;
1059 break;
1060 }
1061 }
1062 // If we find the outer induction after an inner induction e.g.
1063 // for(int i=0;i<N;i++)
1064 // for(int j=0;j<N;j++)
1065 // A[j][i] = A[j-1][i-1]+k;
1066 // then it is a bad order.
1067 if (AR->getLoop() == OuterLoop) {
1068 // We found an OuterLoop induction after InnerLoop induction. It is
1069 // a bad order.
1070 FoundOuterInduction = true;
1071 if (FoundInnerInduction) {
1072 BadOrder++;
1073 break;
1074 }
1075 }
1076 }
1077 }
1078 }
1079 }
1080 return GoodOrder - BadOrder;
1081}
1082
Chad Rosiere6b3a632016-09-14 17:12:30 +00001083static bool isProfitableForVectorization(unsigned InnerLoopId,
1084 unsigned OuterLoopId,
1085 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001086 // TODO: Improve this heuristic to catch more cases.
1087 // If the inner loop is loop independent or doesn't carry any dependency it is
1088 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001089 for (auto &Row : DepMatrix) {
1090 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001091 return false;
1092 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001093 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001094 return false;
1095 }
1096 // If outer loop has dependence and inner loop is loop independent then it is
1097 // profitable to interchange to enable parallelism.
1098 return true;
1099}
1100
1101bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1102 unsigned OuterLoopId,
1103 CharMatrix &DepMatrix) {
1104
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001105 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001106 // e.g
1107 // 1) Construct dependency matrix and move the one with no loop carried dep
1108 // inside to enable vectorization.
1109
1110 // This is rough cost estimation algorithm. It counts the good and bad order
1111 // of induction variables in the instruction and allows reordering if number
1112 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001113 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001114 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001115 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001116 return true;
1117
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001118 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001119 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001120 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1121 return true;
1122
Vivek Pandya95906582017-10-11 17:12:59 +00001123 ORE->emit([&]() {
1124 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1125 InnerLoop->getStartLoc(),
1126 InnerLoop->getHeader())
1127 << "Interchanging loops is too costly (cost="
1128 << ore::NV("Cost", Cost) << ", threshold="
1129 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1130 << ") and it does not improve parallelism.";
1131 });
Florian Hahnad993522017-07-15 13:13:19 +00001132 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001133}
1134
1135void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1136 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001137 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
1138 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001139 if (*I == InnerLoop) {
1140 OuterLoop->removeChildLoop(I);
1141 return;
1142 }
1143 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001144 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001145}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001146
Karthik Bhat88db86d2015-03-06 10:11:25 +00001147void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1148 Loop *OuterLoop) {
1149 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1150 if (OuterLoopParent) {
1151 // Remove the loop from its parent loop.
1152 removeChildLoop(OuterLoopParent, OuterLoop);
1153 removeChildLoop(OuterLoop, InnerLoop);
1154 OuterLoopParent->addChildLoop(InnerLoop);
1155 } else {
1156 removeChildLoop(OuterLoop, InnerLoop);
1157 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1158 }
1159
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001160 while (!InnerLoop->empty())
1161 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001162
1163 InnerLoop->addChildLoop(OuterLoop);
1164}
1165
1166bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001167 bool Transformed = false;
1168 Instruction *InnerIndexVar;
1169
1170 if (InnerLoop->getSubLoops().size() == 0) {
1171 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1172 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1173 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1174 if (!InductionPHI) {
1175 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1176 return false;
1177 }
1178
1179 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1180 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1181 else
1182 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1183
1184 //
1185 // Split at the place were the induction variable is
1186 // incremented/decremented.
1187 // TODO: This splitting logic may not work always. Fix this.
1188 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001189 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001190
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001191 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001192 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001193 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001194 }
1195
1196 Transformed |= adjustLoopLinks();
1197 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001198 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001199 return false;
1200 }
1201
1202 restructureLoops(InnerLoop, OuterLoop);
1203 return true;
1204}
1205
Benjamin Kramer79442922015-03-06 18:59:14 +00001206void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001207 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001208 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001209 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001210}
1211
Karthik Bhat88db86d2015-03-06 10:11:25 +00001212void LoopInterchangeTransform::splitInnerLoopHeader() {
1213
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001214 // Split the inner loop header out. Here make sure that the reduction PHI's
1215 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001216 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001217 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1218 if (InnerLoopHasReduction) {
1219 // FIXME: Check if the induction PHI will always be the first PHI.
1220 BasicBlock *New = InnerLoopHeader->splitBasicBlock(
1221 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split");
1222 if (LI)
1223 if (Loop *L = LI->getLoopFor(InnerLoopHeader))
1224 L->addBasicBlockToLoop(New, *LI);
1225
1226 // Adjust Reduction PHI's in the block.
1227 SmallVector<PHINode *, 8> PHIVec;
1228 for (auto I = New->begin(); isa<PHINode>(I); ++I) {
1229 PHINode *PHI = dyn_cast<PHINode>(I);
1230 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1231 PHI->replaceAllUsesWith(V);
1232 PHIVec.push_back((PHI));
1233 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001234 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001235 P->eraseFromParent();
1236 }
1237 } else {
1238 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1239 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001240
1241 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001242 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001243}
1244
Benjamin Kramer79442922015-03-06 18:59:14 +00001245/// \brief Move all instructions except the terminator from FromBB right before
1246/// InsertBefore
1247static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1248 auto &ToList = InsertBefore->getParent()->getInstList();
1249 auto &FromList = FromBB->getInstList();
1250
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001251 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1252 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001253}
1254
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001255void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1256 BasicBlock *OldPred,
1257 BasicBlock *NewPred) {
1258 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1259 PHINode *PHI = cast<PHINode>(I);
1260 unsigned Num = PHI->getNumIncomingValues();
1261 for (unsigned i = 0; i < Num; ++i) {
1262 if (PHI->getIncomingBlock(i) == OldPred)
1263 PHI->setIncomingBlock(i, NewPred);
1264 }
1265 }
1266}
1267
Karthik Bhat88db86d2015-03-06 10:11:25 +00001268bool LoopInterchangeTransform::adjustLoopBranches() {
1269
1270 DEBUG(dbgs() << "adjustLoopBranches called\n");
1271 // Adjust the loop preheader
1272 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1273 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1274 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1275 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1276 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1277 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1278 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1279 BasicBlock *InnerLoopLatchPredecessor =
1280 InnerLoopLatch->getUniquePredecessor();
1281 BasicBlock *InnerLoopLatchSuccessor;
1282 BasicBlock *OuterLoopLatchSuccessor;
1283
1284 BranchInst *OuterLoopLatchBI =
1285 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1286 BranchInst *InnerLoopLatchBI =
1287 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1288 BranchInst *OuterLoopHeaderBI =
1289 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1290 BranchInst *InnerLoopHeaderBI =
1291 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1292
1293 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1294 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1295 !InnerLoopHeaderBI)
1296 return false;
1297
1298 BranchInst *InnerLoopLatchPredecessorBI =
1299 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1300 BranchInst *OuterLoopPredecessorBI =
1301 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1302
1303 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1304 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001305 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1306 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001307 return false;
1308
1309 // Adjust Loop Preheader and headers
1310
1311 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1312 for (unsigned i = 0; i < NumSucc; ++i) {
1313 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1314 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1315 }
1316
1317 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1318 for (unsigned i = 0; i < NumSucc; ++i) {
1319 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1320 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1321 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001322 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001323 }
1324
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001325 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001326 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001327 OuterLoopHeader);
1328
Karthik Bhat88db86d2015-03-06 10:11:25 +00001329 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1330 InnerLoopHeaderBI->eraseFromParent();
1331
1332 // -------------Adjust loop latches-----------
1333 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1334 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1335 else
1336 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1337
1338 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1339 for (unsigned i = 0; i < NumSucc; ++i) {
1340 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1341 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1342 }
1343
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001344 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1345 // the value and remove this PHI node from inner loop.
1346 SmallVector<PHINode *, 8> LcssaVec;
1347 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1348 PHINode *LcssaPhi = cast<PHINode>(I);
1349 LcssaVec.push_back(LcssaPhi);
1350 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001351 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001352 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1353 P->replaceAllUsesWith(Incoming);
1354 P->eraseFromParent();
1355 }
1356
Karthik Bhat88db86d2015-03-06 10:11:25 +00001357 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1358 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1359 else
1360 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1361
1362 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1363 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1364 else
1365 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1366
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001367 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1368
Karthik Bhat88db86d2015-03-06 10:11:25 +00001369 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1370 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1371 } else {
1372 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1373 }
1374
1375 return true;
1376}
1377void LoopInterchangeTransform::adjustLoopPreheaders() {
1378
1379 // We have interchanged the preheaders so we need to interchange the data in
1380 // the preheader as well.
1381 // This is because the content of inner preheader was previously executed
1382 // inside the outer loop.
1383 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1384 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1385 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1386 BranchInst *InnerTermBI =
1387 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1388
Karthik Bhat88db86d2015-03-06 10:11:25 +00001389 // These instructions should now be executed inside the loop.
1390 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001391 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001392 // These instructions were not executed previously in the loop so move them to
1393 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001394 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001395}
1396
1397bool LoopInterchangeTransform::adjustLoopLinks() {
1398
1399 // Adjust all branches in the inner and outer loop.
1400 bool Changed = adjustLoopBranches();
1401 if (Changed)
1402 adjustLoopPreheaders();
1403 return Changed;
1404}
1405
1406char LoopInterchange::ID = 0;
1407INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1408 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001409INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001410INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001411INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001412INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001413INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001414INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001415INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001416INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001417
1418INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1419 "Interchanges loops for cache reuse", false, false)
1420
1421Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }