blob: 02653491b8616876b0b1bd09eed128a1a1b4da8d [file] [log] [blame]
Karthik Bhat88db86d2015-03-06 10:11:25 +00001//===- LoopInterchange.cpp - Loop interchange pass------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This Pass handles loop interchange transform.
11// This pass interchanges loops to provide a more cache-friendly memory access
12// patterns.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/AliasAnalysis.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000018#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/BlockFrequencyInfo.h"
20#include "llvm/Analysis/CodeMetrics.h"
21#include "llvm/Analysis/DependenceAnalysis.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/LoopIterator.h"
24#include "llvm/Analysis/LoopPass.h"
25#include "llvm/Analysis/ScalarEvolution.h"
26#include "llvm/Analysis/ScalarEvolutionExpander.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/Analysis/TargetTransformInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000030#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000033#include "llvm/IR/InstIterator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/IR/IntrinsicInst.h"
Karthik Bhat8210fdf2015-04-23 04:51:44 +000035#include "llvm/IR/Module.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000036#include "llvm/Pass.h"
37#include "llvm/Support/Debug.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000039#include "llvm/Transforms/Scalar.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/SSAUpdater.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000043using namespace llvm;
44
45#define DEBUG_TYPE "loop-interchange"
46
47namespace {
48
49typedef SmallVector<Loop *, 8> LoopVector;
50
51// TODO: Check if we can use a sparse matrix here.
52typedef std::vector<std::vector<char>> CharMatrix;
53
54// Maximum number of dependencies that can be handled in the dependency matrix.
55static const unsigned MaxMemInstrCount = 100;
56
57// Maximum loop depth supported.
58static const unsigned MaxLoopNestDepth = 10;
59
60struct LoopInterchange;
61
62#ifdef DUMP_DEP_MATRICIES
63void printDepMatrix(CharMatrix &DepMatrix) {
64 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) {
65 std::vector<char> Vec = *I;
66 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II)
67 DEBUG(dbgs() << *II << " ");
68 DEBUG(dbgs() << "\n");
69 }
70}
71#endif
72
Karthik Bhat8210fdf2015-04-23 04:51:44 +000073static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000074 Loop *L, DependenceInfo *DI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000075 typedef SmallVector<Value *, 16> ValueVector;
76 ValueVector MemInstr;
77
78 if (Level > MaxLoopNestDepth) {
79 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
80 << MaxLoopNestDepth << "\n");
81 return false;
82 }
83
84 // For each block.
85 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end();
86 BB != BE; ++BB) {
87 // Scan the BB and collect legal loads and stores.
88 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E;
89 ++I) {
Chad Rosier09c11092016-09-13 12:56:04 +000090 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000091 return false;
Chad Rosier09c11092016-09-13 12:56:04 +000092 if (LoadInst *Ld = dyn_cast<LoadInst>(I)) {
93 if (!Ld->isSimple())
94 return false;
95 MemInstr.push_back(&*I);
96 } else if (StoreInst *St = dyn_cast<StoreInst>(I)) {
97 if (!St->isSimple())
98 return false;
99 MemInstr.push_back(&*I);
100 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000101 }
102 }
103
104 DEBUG(dbgs() << "Found " << MemInstr.size()
105 << " Loads and Stores to analyze\n");
106
107 ValueVector::iterator I, IE, J, JE;
108
109 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
110 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
111 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000112 Instruction *Src = cast<Instruction>(*I);
113 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000114 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000115 continue;
Chad Rosier90bcb912016-09-07 16:07:17 +0000116 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000117 continue;
Chad Rosier90bcb912016-09-07 16:07:17 +0000118 if (auto D = DI->depends(Src, Dst, true)) {
119 DEBUG(dbgs() << "Found Dependency between Src and Dst\n"
120 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000121 if (D->isFlow()) {
122 // TODO: Handle Flow dependence.Check if it is sufficient to populate
123 // the Dependence Matrix with the direction reversed.
Chad Rosierf5814f52016-09-07 15:56:59 +0000124 DEBUG(dbgs() << "Flow dependence not handled\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000125 return false;
126 }
127 if (D->isAnti()) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000128 DEBUG(dbgs() << "Found Anti dependence\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000129 unsigned Levels = D->getLevels();
130 char Direction;
131 for (unsigned II = 1; II <= Levels; ++II) {
132 const SCEV *Distance = D->getDistance(II);
133 const SCEVConstant *SCEVConst =
134 dyn_cast_or_null<SCEVConstant>(Distance);
135 if (SCEVConst) {
136 const ConstantInt *CI = SCEVConst->getValue();
137 if (CI->isNegative())
138 Direction = '<';
139 else if (CI->isZero())
140 Direction = '=';
141 else
142 Direction = '>';
143 Dep.push_back(Direction);
144 } else if (D->isScalar(II)) {
145 Direction = 'S';
146 Dep.push_back(Direction);
147 } else {
148 unsigned Dir = D->getDirection(II);
149 if (Dir == Dependence::DVEntry::LT ||
150 Dir == Dependence::DVEntry::LE)
151 Direction = '<';
152 else if (Dir == Dependence::DVEntry::GT ||
153 Dir == Dependence::DVEntry::GE)
154 Direction = '>';
155 else if (Dir == Dependence::DVEntry::EQ)
156 Direction = '=';
157 else
158 Direction = '*';
159 Dep.push_back(Direction);
160 }
161 }
162 while (Dep.size() != Level) {
163 Dep.push_back('I');
164 }
165
166 DepMatrix.push_back(Dep);
167 if (DepMatrix.size() > MaxMemInstrCount) {
168 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
169 << " dependencies inside loop\n");
170 return false;
171 }
172 }
173 }
174 }
175 }
176
Vikram TV74b41112015-12-09 05:16:24 +0000177 // We don't have a DepMatrix to check legality return false.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000178 if (DepMatrix.size() == 0)
179 return false;
180 return true;
181}
182
183// A loop is moved from index 'from' to an index 'to'. Update the Dependence
184// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000185static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
186 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000187 unsigned numRows = DepMatrix.size();
188 for (unsigned i = 0; i < numRows; ++i) {
189 char TmpVal = DepMatrix[i][ToIndx];
190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
191 DepMatrix[i][FromIndx] = TmpVal;
192 }
193}
194
195// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
196// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000197static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
198 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000199 for (unsigned i = 0; i <= Column; ++i) {
200 if (DepMatrix[Row][i] == '<')
201 return false;
202 if (DepMatrix[Row][i] == '>')
203 return true;
204 }
205 // All dependencies were '=','S' or 'I'
206 return false;
207}
208
209// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000210static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
211 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000212 for (unsigned i = 0; i < Column; ++i) {
213 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' ||
214 DepMatrix[Row][i] != 'I')
215 return false;
216 }
217 return true;
218}
219
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000220static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
221 unsigned OuterLoopId, char InnerDep,
222 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000223
224 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
225 return false;
226
227 if (InnerDep == OuterDep)
228 return true;
229
230 // It is legal to interchange if and only if after interchange no row has a
231 // '>' direction as the leftmost non-'='.
232
233 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
234 return true;
235
236 if (InnerDep == '<')
237 return true;
238
239 if (InnerDep == '>') {
240 // If OuterLoopId represents outermost loop then interchanging will make the
241 // 1st dependency as '>'
242 if (OuterLoopId == 0)
243 return false;
244
245 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
246 // interchanging will result in this row having an outermost non '='
247 // dependency of '>'
248 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
249 return true;
250 }
251
252 return false;
253}
254
255// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000256// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000257// if the direction matrix, after the same permutation is applied to its
258// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000259static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
260 unsigned InnerLoopId,
261 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000262
263 unsigned NumRows = DepMatrix.size();
264 // For each row check if it is valid to interchange.
265 for (unsigned Row = 0; Row < NumRows; ++Row) {
266 char InnerDep = DepMatrix[Row][InnerLoopId];
267 char OuterDep = DepMatrix[Row][OuterLoopId];
268 if (InnerDep == '*' || OuterDep == '*')
269 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000270 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000271 return false;
272 }
273 return true;
274}
275
276static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
277
Chad Rosierf5814f52016-09-07 15:56:59 +0000278 DEBUG(dbgs() << "Calling populateWorklist on Func: "
279 << L.getHeader()->getParent()->getName() << " Loop: %"
280 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000281 LoopVector LoopList;
282 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000283 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
284 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000285 // The current loop has multiple subloops in it hence it is not tightly
286 // nested.
287 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000288 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000289 LoopList.clear();
290 return;
291 }
292 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000293 CurrentLoop = Vec->front();
294 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000295 }
296 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000297 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000298}
299
300static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
301 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
302 if (InnerIndexVar)
303 return InnerIndexVar;
304 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
305 return nullptr;
306 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
307 PHINode *PhiVar = cast<PHINode>(I);
308 Type *PhiTy = PhiVar->getType();
309 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
310 !PhiTy->isPointerTy())
311 return nullptr;
312 const SCEVAddRecExpr *AddRec =
313 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
314 if (!AddRec || !AddRec->isAffine())
315 continue;
316 const SCEV *Step = AddRec->getStepRecurrence(*SE);
317 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
318 if (!C)
319 continue;
320 // Found the induction variable.
321 // FIXME: Handle loops with more than one induction variable. Note that,
322 // currently, legality makes sure we have only one induction variable.
323 return PhiVar;
324 }
325 return nullptr;
326}
327
328/// LoopInterchangeLegality checks if it is legal to interchange the loop.
329class LoopInterchangeLegality {
330public:
331 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Justin Bogner843fb202015-12-15 19:40:57 +0000332 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA)
333 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
334 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000335
336 /// Check if the loops can be interchanged.
337 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
338 CharMatrix &DepMatrix);
339 /// Check if the loop structure is understood. We do not handle triangular
340 /// loops for now.
341 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
342
343 bool currentLimitations();
344
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000345 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
346
Karthik Bhat88db86d2015-03-06 10:11:25 +0000347private:
348 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000349 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
350 bool areAllUsesReductions(Instruction *Ins, Loop *L);
351 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
352 bool findInductionAndReductions(Loop *L,
353 SmallVector<PHINode *, 8> &Inductions,
354 SmallVector<PHINode *, 8> &Reductions);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000355 Loop *OuterLoop;
356 Loop *InnerLoop;
357
Karthik Bhat88db86d2015-03-06 10:11:25 +0000358 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000359 LoopInfo *LI;
360 DominatorTree *DT;
361 bool PreserveLCSSA;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000362
363 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000364};
365
366/// LoopInterchangeProfitability checks if it is profitable to interchange the
367/// loop.
368class LoopInterchangeProfitability {
369public:
370 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE)
371 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {}
372
Vikram TV74b41112015-12-09 05:16:24 +0000373 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000374 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
375 CharMatrix &DepMatrix);
376
377private:
378 int getInstrOrderCost();
379
380 Loop *OuterLoop;
381 Loop *InnerLoop;
382
383 /// Scev analysis.
384 ScalarEvolution *SE;
385};
386
Vikram TV74b41112015-12-09 05:16:24 +0000387/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000388class LoopInterchangeTransform {
389public:
390 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
391 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000392 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000393 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000394 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000395 LoopExit(LoopNestExit),
396 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000397
398 /// Interchange OuterLoop and InnerLoop.
399 bool transform();
400 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
401 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000402
403private:
404 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000405 void splitInnerLoopHeader();
406 bool adjustLoopLinks();
407 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000408 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000409 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
410 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000411
412 Loop *OuterLoop;
413 Loop *InnerLoop;
414
415 /// Scev analysis.
416 ScalarEvolution *SE;
417 LoopInfo *LI;
418 DominatorTree *DT;
419 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000420 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000421};
422
Vikram TV74b41112015-12-09 05:16:24 +0000423// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000424struct LoopInterchange : public FunctionPass {
425 static char ID;
426 ScalarEvolution *SE;
427 LoopInfo *LI;
Chandler Carruth49c22192016-05-12 22:19:39 +0000428 DependenceInfo *DI;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000429 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000430 bool PreserveLCSSA;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000431 LoopInterchange()
Chandler Carruth49c22192016-05-12 22:19:39 +0000432 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000433 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
434 }
435
436 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000437 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000438 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000439 AU.addRequired<DominatorTreeWrapperPass>();
440 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000441 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000442 AU.addRequiredID(LoopSimplifyID);
443 AU.addRequiredID(LCSSAID);
444 }
445
446 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000447 if (skipFunction(F))
448 return false;
449
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000450 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000451 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000452 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000453 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
454 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000455 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
456
Karthik Bhat88db86d2015-03-06 10:11:25 +0000457 // Build up a worklist of loop pairs to analyze.
458 SmallVector<LoopVector, 8> Worklist;
459
460 for (Loop *L : *LI)
461 populateWorklist(*L, Worklist);
462
Chad Rosiera4c42462016-09-12 13:24:47 +0000463 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000464 bool Changed = true;
465 while (!Worklist.empty()) {
466 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000467 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000468 }
469 return Changed;
470 }
471
472 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000473 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000474 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
475 if (ExitCountOuter == SE->getCouldNotCompute()) {
476 DEBUG(dbgs() << "Couldn't compute Backedge count\n");
477 return false;
478 }
479 if (L->getNumBackEdges() != 1) {
480 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
481 return false;
482 }
483 if (!L->getExitingBlock()) {
484 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n");
485 return false;
486 }
487 }
488 return true;
489 }
490
Benjamin Kramerc321e532016-06-08 19:09:22 +0000491 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000492 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000493 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000494 return LoopList.size() - 1;
495 }
496
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000497 bool processLoopList(LoopVector LoopList, Function &F) {
498
Karthik Bhat88db86d2015-03-06 10:11:25 +0000499 bool Changed = false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000500 CharMatrix DependencyMatrix;
501 if (LoopList.size() < 2) {
502 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
503 return false;
504 }
505 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000506 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000507 return false;
508 }
509 Loop *OuterMostLoop = *(LoopList.begin());
510
511 DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size()
512 << "\n");
513
514 if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(),
Chandler Carruth49c22192016-05-12 22:19:39 +0000515 OuterMostLoop, DI)) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000516 DEBUG(dbgs() << "Populating Dependency matrix failed\n");
517 return false;
518 }
519#ifdef DUMP_DEP_MATRICIES
520 DEBUG(dbgs() << "Dependence before inter change \n");
521 printDepMatrix(DependencyMatrix);
522#endif
523
524 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
525 BranchInst *OuterMostLoopLatchBI =
526 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
527 if (!OuterMostLoopLatchBI)
528 return false;
529
530 // Since we currently do not handle LCSSA PHI's any failure in loop
531 // condition will now branch to LoopNestExit.
532 // TODO: This should be removed once we handle LCSSA PHI nodes.
533
534 // Get the Outermost loop exit.
535 BasicBlock *LoopNestExit;
536 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
537 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
538 else
539 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
540
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000541 if (isa<PHINode>(LoopNestExit->begin())) {
542 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
543 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000544 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000545 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000546
547 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000548 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000549 for (unsigned i = SelecLoopId; i > 0; i--) {
550 bool Interchanged =
551 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
552 if (!Interchanged)
553 return Changed;
554 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000555 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000556
557 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000558 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000559 DT->recalculate(F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000560#ifdef DUMP_DEP_MATRICIES
561 DEBUG(dbgs() << "Dependence after inter change \n");
562 printDepMatrix(DependencyMatrix);
563#endif
564 Changed |= Interchanged;
565 }
566 return Changed;
567 }
568
569 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
570 unsigned OuterLoopId, BasicBlock *LoopNestExit,
571 std::vector<std::vector<char>> &DependencyMatrix) {
572
Chad Rosier13bc0d192016-09-07 18:15:12 +0000573 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000574 << " and OuterLoopId = " << OuterLoopId << "\n");
575 Loop *InnerLoop = LoopList[InnerLoopId];
576 Loop *OuterLoop = LoopList[OuterLoopId];
577
Justin Bogner843fb202015-12-15 19:40:57 +0000578 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
579 PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000580 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
581 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
582 return false;
583 }
584 DEBUG(dbgs() << "Loops are legal to interchange\n");
585 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE);
586 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
587 DEBUG(dbgs() << "Interchanging Loops not profitable\n");
588 return false;
589 }
590
Justin Bogner843fb202015-12-15 19:40:57 +0000591 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000592 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000593 LIT.transform();
594 DEBUG(dbgs() << "Loops interchanged\n");
595 return true;
596 }
597};
598
599} // end of namespace
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000600bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
David Majnemer0a16c222016-08-11 21:15:00 +0000601 return none_of(Ins->users(), [=](User *U) -> bool {
602 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000603 RecurrenceDescriptor RD;
604 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000605 });
606}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000607
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000608bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
609 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000610 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000611 // Load corresponding to reduction PHI's are safe while concluding if
612 // tightly nested.
613 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
614 if (!areAllUsesReductions(L, InnerLoop))
615 return true;
616 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
617 return true;
618 }
619 return false;
620}
621
622bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
623 BasicBlock *BB) {
624 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
625 // Stores corresponding to reductions are safe while concluding if tightly
626 // nested.
627 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
628 PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0));
629 if (!PHI)
630 return true;
631 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000632 return true;
633 }
634 return false;
635}
636
637bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
638 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
639 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
640 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
641
642 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n");
643
644 // A perfectly nested loop will not have any branch in between the outer and
645 // inner block i.e. outer header will branch to either inner preheader and
646 // outerloop latch.
647 BranchInst *outerLoopHeaderBI =
648 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
649 if (!outerLoopHeaderBI)
650 return false;
651 unsigned num = outerLoopHeaderBI->getNumSuccessors();
652 for (unsigned i = 0; i < num; i++) {
653 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader &&
654 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch)
655 return false;
656 }
657
658 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n");
659 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000660 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000661 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
662 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000663 return false;
664
665 DEBUG(dbgs() << "Loops are perfectly nested \n");
666 // We have a perfect loop nest.
667 return true;
668}
669
Karthik Bhat88db86d2015-03-06 10:11:25 +0000670
671bool LoopInterchangeLegality::isLoopStructureUnderstood(
672 PHINode *InnerInduction) {
673
674 unsigned Num = InnerInduction->getNumOperands();
675 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
676 for (unsigned i = 0; i < Num; ++i) {
677 Value *Val = InnerInduction->getOperand(i);
678 if (isa<Constant>(Val))
679 continue;
680 Instruction *I = dyn_cast<Instruction>(Val);
681 if (!I)
682 return false;
683 // TODO: Handle triangular loops.
684 // e.g. for(int i=0;i<N;i++)
685 // for(int j=i;j<N;j++)
686 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
687 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
688 InnerLoopPreheader &&
689 !OuterLoop->isLoopInvariant(I)) {
690 return false;
691 }
692 }
693 return true;
694}
695
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000696bool LoopInterchangeLegality::findInductionAndReductions(
697 Loop *L, SmallVector<PHINode *, 8> &Inductions,
698 SmallVector<PHINode *, 8> &Reductions) {
699 if (!L->getLoopLatch() || !L->getLoopPredecessor())
700 return false;
701 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000702 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000703 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000704 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000705 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000706 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000707 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000708 Reductions.push_back(PHI);
709 else {
710 DEBUG(
711 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
712 return false;
713 }
714 }
715 return true;
716}
717
718static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
719 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
720 PHINode *PHI = cast<PHINode>(I);
721 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
722 if (PHI->getNumIncomingValues() > 1)
723 return false;
724 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
725 if (!Ins)
726 return false;
727 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
728 // exits lcssa phi else it would not be tightly nested.
729 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
730 return false;
731 }
732 return true;
733}
734
735static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
736 BasicBlock *LoopHeader) {
737 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
738 unsigned Num = BI->getNumSuccessors();
739 assert(Num == 2);
740 for (unsigned i = 0; i < Num; ++i) {
741 if (BI->getSuccessor(i) == LoopHeader)
742 continue;
743 return BI->getSuccessor(i);
744 }
745 }
746 return nullptr;
747}
748
Karthik Bhat88db86d2015-03-06 10:11:25 +0000749// This function indicates the current limitations in the transform as a result
750// of which we do not proceed.
751bool LoopInterchangeLegality::currentLimitations() {
752
753 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
754 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000755 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
756 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000757 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000758
759 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000760 SmallVector<PHINode *, 8> Inductions;
761 SmallVector<PHINode *, 8> Reductions;
762 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000763 return true;
764
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000765 // TODO: Currently we handle only loops with 1 induction variable.
766 if (Inductions.size() != 1) {
767 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
768 << "Failed to interchange due to current limitation\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000769 return true;
770 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000771 if (Reductions.size() > 0)
772 InnerLoopHasReduction = true;
773
774 InnerInductionVar = Inductions.pop_back_val();
775 Reductions.clear();
776 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions))
777 return true;
778
779 // Outer loop cannot have reduction because then loops will not be tightly
780 // nested.
781 if (!Reductions.empty())
782 return true;
783 // TODO: Currently we handle only loops with 1 induction variable.
784 if (Inductions.size() != 1)
785 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000786
787 // TODO: Triangular loops are not handled for now.
788 if (!isLoopStructureUnderstood(InnerInductionVar)) {
789 DEBUG(dbgs() << "Loop structure not understood by pass\n");
790 return true;
791 }
792
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000793 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
794 BasicBlock *LoopExitBlock =
795 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
796 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000797 return true;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000798
799 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
800 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000801 return true;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000802
803 // TODO: Current limitation: Since we split the inner loop latch at the point
804 // were induction variable is incremented (induction.next); We cannot have
805 // more than 1 user of induction.next since it would result in broken code
806 // after split.
807 // e.g.
808 // for(i=0;i<N;i++) {
809 // for(j = 0;j<M;j++) {
810 // A[j+1][i+2] = A[j][i]+k;
811 // }
812 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000813 Instruction *InnerIndexVarInc = nullptr;
814 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
815 InnerIndexVarInc =
816 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
817 else
818 InnerIndexVarInc =
819 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
820
Pete Cooper11bd9582015-07-27 18:37:58 +0000821 if (!InnerIndexVarInc)
822 return true;
823
Karthik Bhat88db86d2015-03-06 10:11:25 +0000824 // Since we split the inner loop latch on this induction variable. Make sure
825 // we do not have any instruction between the induction variable and branch
826 // instruction.
827
David Majnemerd7708772016-06-24 04:05:21 +0000828 bool FoundInduction = false;
829 for (const Instruction &I : reverse(*InnerLoopLatch)) {
830 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000831 continue;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000832 // We found an instruction. If this is not induction variable then it is not
833 // safe to split this loop latch.
David Majnemerd7708772016-06-24 04:05:21 +0000834 if (!I.isIdenticalTo(InnerIndexVarInc))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000835 return true;
David Majnemerd7708772016-06-24 04:05:21 +0000836
837 FoundInduction = true;
838 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000839 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000840 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000841 // current limitation.
842 if (!FoundInduction)
843 return true;
844
845 return false;
846}
847
848bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
849 unsigned OuterLoopId,
850 CharMatrix &DepMatrix) {
851
852 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
853 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
854 << "and OuterLoopId = " << OuterLoopId
855 << "due to dependence\n");
856 return false;
857 }
858
859 // Create unique Preheaders if we already do not have one.
860 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
861 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
862
863 // Create a unique outer preheader -
864 // 1) If OuterLoop preheader is not present.
865 // 2) If OuterLoop Preheader is same as OuterLoop Header
866 // 3) If OuterLoop Preheader is same as Header of the previous loop.
867 // 4) If OuterLoop Preheader is Entry node.
868 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
869 isa<PHINode>(OuterLoopPreHeader->begin()) ||
870 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000871 OuterLoopPreHeader =
872 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000873 }
874
875 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
876 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +0000877 InnerLoopPreHeader =
878 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000879 }
880
Karthik Bhat88db86d2015-03-06 10:11:25 +0000881 // TODO: The loops could not be interchanged due to current limitations in the
882 // transform module.
883 if (currentLimitations()) {
884 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
885 return false;
886 }
887
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000888 // Check if the loops are tightly nested.
889 if (!tightlyNested(OuterLoop, InnerLoop)) {
890 DEBUG(dbgs() << "Loops not tightly nested\n");
891 return false;
892 }
893
Karthik Bhat88db86d2015-03-06 10:11:25 +0000894 return true;
895}
896
897int LoopInterchangeProfitability::getInstrOrderCost() {
898 unsigned GoodOrder, BadOrder;
899 BadOrder = GoodOrder = 0;
900 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end();
901 BI != BE; ++BI) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000902 for (Instruction &Ins : **BI) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000903 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
904 unsigned NumOp = GEP->getNumOperands();
905 bool FoundInnerInduction = false;
906 bool FoundOuterInduction = false;
907 for (unsigned i = 0; i < NumOp; ++i) {
908 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
909 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
910 if (!AR)
911 continue;
912
913 // If we find the inner induction after an outer induction e.g.
914 // for(int i=0;i<N;i++)
915 // for(int j=0;j<N;j++)
916 // A[i][j] = A[i-1][j-1]+k;
917 // then it is a good order.
918 if (AR->getLoop() == InnerLoop) {
919 // We found an InnerLoop induction after OuterLoop induction. It is
920 // a good order.
921 FoundInnerInduction = true;
922 if (FoundOuterInduction) {
923 GoodOrder++;
924 break;
925 }
926 }
927 // If we find the outer induction after an inner induction e.g.
928 // for(int i=0;i<N;i++)
929 // for(int j=0;j<N;j++)
930 // A[j][i] = A[j-1][i-1]+k;
931 // then it is a bad order.
932 if (AR->getLoop() == OuterLoop) {
933 // We found an OuterLoop induction after InnerLoop induction. It is
934 // a bad order.
935 FoundOuterInduction = true;
936 if (FoundInnerInduction) {
937 BadOrder++;
938 break;
939 }
940 }
941 }
942 }
943 }
944 }
945 return GoodOrder - BadOrder;
946}
947
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000948static bool isProfitabileForVectorization(unsigned InnerLoopId,
949 unsigned OuterLoopId,
950 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000951 // TODO: Improve this heuristic to catch more cases.
952 // If the inner loop is loop independent or doesn't carry any dependency it is
953 // profitable to move this to outer position.
954 unsigned Row = DepMatrix.size();
955 for (unsigned i = 0; i < Row; ++i) {
956 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I')
957 return false;
958 // TODO: We need to improve this heuristic.
959 if (DepMatrix[i][OuterLoopId] != '=')
960 return false;
961 }
962 // If outer loop has dependence and inner loop is loop independent then it is
963 // profitable to interchange to enable parallelism.
964 return true;
965}
966
967bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
968 unsigned OuterLoopId,
969 CharMatrix &DepMatrix) {
970
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000971 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000972 // e.g
973 // 1) Construct dependency matrix and move the one with no loop carried dep
974 // inside to enable vectorization.
975
976 // This is rough cost estimation algorithm. It counts the good and bad order
977 // of induction variables in the instruction and allows reordering if number
978 // of bad orders is more than good.
979 int Cost = 0;
980 Cost += getInstrOrderCost();
981 DEBUG(dbgs() << "Cost = " << Cost << "\n");
982 if (Cost < 0)
983 return true;
984
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000985 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +0000986 // we can move this loop outside to improve parallelism.
987 bool ImprovesPar =
988 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
989 return ImprovesPar;
990}
991
992void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
993 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000994 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
995 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000996 if (*I == InnerLoop) {
997 OuterLoop->removeChildLoop(I);
998 return;
999 }
1000 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001001 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001002}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001003
Karthik Bhat88db86d2015-03-06 10:11:25 +00001004void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1005 Loop *OuterLoop) {
1006 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1007 if (OuterLoopParent) {
1008 // Remove the loop from its parent loop.
1009 removeChildLoop(OuterLoopParent, OuterLoop);
1010 removeChildLoop(OuterLoop, InnerLoop);
1011 OuterLoopParent->addChildLoop(InnerLoop);
1012 } else {
1013 removeChildLoop(OuterLoop, InnerLoop);
1014 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1015 }
1016
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001017 while (!InnerLoop->empty())
1018 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001019
1020 InnerLoop->addChildLoop(OuterLoop);
1021}
1022
1023bool LoopInterchangeTransform::transform() {
1024
1025 DEBUG(dbgs() << "transform\n");
1026 bool Transformed = false;
1027 Instruction *InnerIndexVar;
1028
1029 if (InnerLoop->getSubLoops().size() == 0) {
1030 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1031 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1032 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1033 if (!InductionPHI) {
1034 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1035 return false;
1036 }
1037
1038 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1039 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1040 else
1041 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1042
1043 //
1044 // Split at the place were the induction variable is
1045 // incremented/decremented.
1046 // TODO: This splitting logic may not work always. Fix this.
1047 splitInnerLoopLatch(InnerIndexVar);
1048 DEBUG(dbgs() << "splitInnerLoopLatch Done\n");
1049
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001050 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001051 splitInnerLoopHeader();
1052 DEBUG(dbgs() << "splitInnerLoopHeader Done\n");
1053 }
1054
1055 Transformed |= adjustLoopLinks();
1056 if (!Transformed) {
1057 DEBUG(dbgs() << "adjustLoopLinks Failed\n");
1058 return false;
1059 }
1060
1061 restructureLoops(InnerLoop, OuterLoop);
1062 return true;
1063}
1064
Benjamin Kramer79442922015-03-06 18:59:14 +00001065void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001066 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001067 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001068 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001069}
1070
Karthik Bhat88db86d2015-03-06 10:11:25 +00001071void LoopInterchangeTransform::splitInnerLoopHeader() {
1072
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001073 // Split the inner loop header out. Here make sure that the reduction PHI's
1074 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001075 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001076 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1077 if (InnerLoopHasReduction) {
1078 // FIXME: Check if the induction PHI will always be the first PHI.
1079 BasicBlock *New = InnerLoopHeader->splitBasicBlock(
1080 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split");
1081 if (LI)
1082 if (Loop *L = LI->getLoopFor(InnerLoopHeader))
1083 L->addBasicBlockToLoop(New, *LI);
1084
1085 // Adjust Reduction PHI's in the block.
1086 SmallVector<PHINode *, 8> PHIVec;
1087 for (auto I = New->begin(); isa<PHINode>(I); ++I) {
1088 PHINode *PHI = dyn_cast<PHINode>(I);
1089 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1090 PHI->replaceAllUsesWith(V);
1091 PHIVec.push_back((PHI));
1092 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001093 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001094 P->eraseFromParent();
1095 }
1096 } else {
1097 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1098 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001099
1100 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
1101 "InnerLoopHeader \n");
1102}
1103
Benjamin Kramer79442922015-03-06 18:59:14 +00001104/// \brief Move all instructions except the terminator from FromBB right before
1105/// InsertBefore
1106static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1107 auto &ToList = InsertBefore->getParent()->getInstList();
1108 auto &FromList = FromBB->getInstList();
1109
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001110 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1111 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001112}
1113
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001114void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1115 BasicBlock *OldPred,
1116 BasicBlock *NewPred) {
1117 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1118 PHINode *PHI = cast<PHINode>(I);
1119 unsigned Num = PHI->getNumIncomingValues();
1120 for (unsigned i = 0; i < Num; ++i) {
1121 if (PHI->getIncomingBlock(i) == OldPred)
1122 PHI->setIncomingBlock(i, NewPred);
1123 }
1124 }
1125}
1126
Karthik Bhat88db86d2015-03-06 10:11:25 +00001127bool LoopInterchangeTransform::adjustLoopBranches() {
1128
1129 DEBUG(dbgs() << "adjustLoopBranches called\n");
1130 // Adjust the loop preheader
1131 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1132 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1133 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1134 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1135 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1136 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1137 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1138 BasicBlock *InnerLoopLatchPredecessor =
1139 InnerLoopLatch->getUniquePredecessor();
1140 BasicBlock *InnerLoopLatchSuccessor;
1141 BasicBlock *OuterLoopLatchSuccessor;
1142
1143 BranchInst *OuterLoopLatchBI =
1144 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1145 BranchInst *InnerLoopLatchBI =
1146 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1147 BranchInst *OuterLoopHeaderBI =
1148 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1149 BranchInst *InnerLoopHeaderBI =
1150 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1151
1152 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1153 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1154 !InnerLoopHeaderBI)
1155 return false;
1156
1157 BranchInst *InnerLoopLatchPredecessorBI =
1158 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1159 BranchInst *OuterLoopPredecessorBI =
1160 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1161
1162 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1163 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001164 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1165 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001166 return false;
1167
1168 // Adjust Loop Preheader and headers
1169
1170 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1171 for (unsigned i = 0; i < NumSucc; ++i) {
1172 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1173 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1174 }
1175
1176 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1177 for (unsigned i = 0; i < NumSucc; ++i) {
1178 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1179 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1180 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001181 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001182 }
1183
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001184 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001185 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001186 OuterLoopHeader);
1187
Karthik Bhat88db86d2015-03-06 10:11:25 +00001188 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1189 InnerLoopHeaderBI->eraseFromParent();
1190
1191 // -------------Adjust loop latches-----------
1192 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1193 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1194 else
1195 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1196
1197 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1198 for (unsigned i = 0; i < NumSucc; ++i) {
1199 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1200 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1201 }
1202
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001203 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1204 // the value and remove this PHI node from inner loop.
1205 SmallVector<PHINode *, 8> LcssaVec;
1206 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1207 PHINode *LcssaPhi = cast<PHINode>(I);
1208 LcssaVec.push_back(LcssaPhi);
1209 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001210 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001211 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1212 P->replaceAllUsesWith(Incoming);
1213 P->eraseFromParent();
1214 }
1215
Karthik Bhat88db86d2015-03-06 10:11:25 +00001216 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1217 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1218 else
1219 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1220
1221 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1222 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1223 else
1224 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1225
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001226 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1227
Karthik Bhat88db86d2015-03-06 10:11:25 +00001228 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1229 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1230 } else {
1231 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1232 }
1233
1234 return true;
1235}
1236void LoopInterchangeTransform::adjustLoopPreheaders() {
1237
1238 // We have interchanged the preheaders so we need to interchange the data in
1239 // the preheader as well.
1240 // This is because the content of inner preheader was previously executed
1241 // inside the outer loop.
1242 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1243 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1244 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1245 BranchInst *InnerTermBI =
1246 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1247
Karthik Bhat88db86d2015-03-06 10:11:25 +00001248 // These instructions should now be executed inside the loop.
1249 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001250 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001251 // These instructions were not executed previously in the loop so move them to
1252 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001253 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001254}
1255
1256bool LoopInterchangeTransform::adjustLoopLinks() {
1257
1258 // Adjust all branches in the inner and outer loop.
1259 bool Changed = adjustLoopBranches();
1260 if (Changed)
1261 adjustLoopPreheaders();
1262 return Changed;
1263}
1264
1265char LoopInterchange::ID = 0;
1266INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1267 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001268INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001269INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001270INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001271INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001272INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001273INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001274INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1275
1276INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1277 "Interchanges loops for cache reuse", false, false)
1278
1279Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }