blob: 45d76fdb7c99a001b35b6f5fa5c7449e0192fe6f [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopInterchange.cpp - Loop interchange pass-------------------------===//
Karthik Bhat88db86d2015-03-06 10:11:25 +00002//
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
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000016#include "llvm/ADT/STLExtras.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000017#include "llvm/ADT/SmallVector.h"
Florian Hahn6e004332018-04-05 10:39:23 +000018#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000019#include "llvm/ADT/StringRef.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000020#include "llvm/Analysis/AliasAnalysis.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000021#include "llvm/Analysis/DependenceAnalysis.h"
22#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000023#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000024#include "llvm/Analysis/ScalarEvolution.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000025#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000026#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DiagnosticInfo.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000030#include "llvm/IR/Function.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000031#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/Type.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000037#include "llvm/Pass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000038#include "llvm/Support/Casting.h"
39#include "llvm/Support/CommandLine.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000040#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000041#include "llvm/Support/ErrorHandling.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000042#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000043#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000044#include "llvm/Transforms/Utils.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000047#include <cassert>
48#include <utility>
49#include <vector>
Davide Italiano9d8f6f82017-01-29 01:55:24 +000050
Karthik Bhat88db86d2015-03-06 10:11:25 +000051using namespace llvm;
52
53#define DEBUG_TYPE "loop-interchange"
54
Florian Hahn6e004332018-04-05 10:39:23 +000055STATISTIC(LoopsInterchanged, "Number of loops interchanged");
56
Chad Rosier72431892016-09-14 17:07:13 +000057static cl::opt<int> LoopInterchangeCostThreshold(
58 "loop-interchange-threshold", cl::init(0), cl::Hidden,
59 cl::desc("Interchange if you gain more than this number"));
60
Karthik Bhat88db86d2015-03-06 10:11:25 +000061namespace {
62
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000063using LoopVector = SmallVector<Loop *, 8>;
Karthik Bhat88db86d2015-03-06 10:11:25 +000064
65// TODO: Check if we can use a sparse matrix here.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000066using CharMatrix = std::vector<std::vector<char>>;
67
68} // end anonymous namespace
Karthik Bhat88db86d2015-03-06 10:11:25 +000069
70// Maximum number of dependencies that can be handled in the dependency matrix.
71static const unsigned MaxMemInstrCount = 100;
72
73// Maximum loop depth supported.
74static const unsigned MaxLoopNestDepth = 10;
75
Karthik Bhat88db86d2015-03-06 10:11:25 +000076#ifdef DUMP_DEP_MATRICIES
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000077static void printDepMatrix(CharMatrix &DepMatrix) {
Florian Hahnf66efd62017-07-24 11:41:30 +000078 for (auto &Row : DepMatrix) {
79 for (auto D : Row)
80 DEBUG(dbgs() << D << " ");
Karthik Bhat88db86d2015-03-06 10:11:25 +000081 DEBUG(dbgs() << "\n");
82 }
83}
84#endif
85
Karthik Bhat8210fdf2015-04-23 04:51:44 +000086static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000087 Loop *L, DependenceInfo *DI) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000088 using ValueVector = SmallVector<Value *, 16>;
89
Karthik Bhat88db86d2015-03-06 10:11:25 +000090 ValueVector MemInstr;
91
Karthik Bhat88db86d2015-03-06 10:11:25 +000092 // For each block.
Florian Hahnf66efd62017-07-24 11:41:30 +000093 for (BasicBlock *BB : L->blocks()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000094 // Scan the BB and collect legal loads and stores.
Florian Hahnf66efd62017-07-24 11:41:30 +000095 for (Instruction &I : *BB) {
Chad Rosier09c11092016-09-13 12:56:04 +000096 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000097 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000098 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000099 if (!Ld->isSimple())
100 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000101 MemInstr.push_back(&I);
102 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +0000103 if (!St->isSimple())
104 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000105 MemInstr.push_back(&I);
Chad Rosier09c11092016-09-13 12:56:04 +0000106 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000107 }
108 }
109
110 DEBUG(dbgs() << "Found " << MemInstr.size()
111 << " Loads and Stores to analyze\n");
112
113 ValueVector::iterator I, IE, J, JE;
114
115 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
116 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
117 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000118 Instruction *Src = cast<Instruction>(*I);
119 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000120 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000121 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000122 // Ignore Input dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000124 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000125 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000126 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000127 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
128 DEBUG(StringRef DepType =
129 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
130 dbgs() << "Found " << DepType
131 << " dependency between Src and Dst\n"
Chad Rosier90bcb912016-09-07 16:07:17 +0000132 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000133 unsigned Levels = D->getLevels();
134 char Direction;
135 for (unsigned II = 1; II <= Levels; ++II) {
136 const SCEV *Distance = D->getDistance(II);
137 const SCEVConstant *SCEVConst =
138 dyn_cast_or_null<SCEVConstant>(Distance);
139 if (SCEVConst) {
140 const ConstantInt *CI = SCEVConst->getValue();
141 if (CI->isNegative())
142 Direction = '<';
143 else if (CI->isZero())
144 Direction = '=';
145 else
146 Direction = '>';
147 Dep.push_back(Direction);
148 } else if (D->isScalar(II)) {
149 Direction = 'S';
150 Dep.push_back(Direction);
151 } else {
152 unsigned Dir = D->getDirection(II);
153 if (Dir == Dependence::DVEntry::LT ||
154 Dir == Dependence::DVEntry::LE)
155 Direction = '<';
156 else if (Dir == Dependence::DVEntry::GT ||
157 Dir == Dependence::DVEntry::GE)
158 Direction = '>';
159 else if (Dir == Dependence::DVEntry::EQ)
160 Direction = '=';
161 else
162 Direction = '*';
163 Dep.push_back(Direction);
164 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000165 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000166 while (Dep.size() != Level) {
167 Dep.push_back('I');
168 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000169
Chad Rosier00eb8db2016-09-21 19:16:47 +0000170 DepMatrix.push_back(Dep);
171 if (DepMatrix.size() > MaxMemInstrCount) {
172 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
173 << " dependencies inside loop\n");
174 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000175 }
176 }
177 }
178 }
179
Karthik Bhat88db86d2015-03-06 10:11:25 +0000180 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) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000213 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000214 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 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
224 return false;
225
226 if (InnerDep == OuterDep)
227 return true;
228
229 // It is legal to interchange if and only if after interchange no row has a
230 // '>' direction as the leftmost non-'='.
231
232 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
233 return true;
234
235 if (InnerDep == '<')
236 return true;
237
238 if (InnerDep == '>') {
239 // If OuterLoopId represents outermost loop then interchanging will make the
240 // 1st dependency as '>'
241 if (OuterLoopId == 0)
242 return false;
243
244 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
245 // interchanging will result in this row having an outermost non '='
246 // dependency of '>'
247 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
248 return true;
249 }
250
251 return false;
252}
253
254// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000255// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000256// if the direction matrix, after the same permutation is applied to its
257// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000258static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
259 unsigned InnerLoopId,
260 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000261 unsigned NumRows = DepMatrix.size();
262 // For each row check if it is valid to interchange.
263 for (unsigned Row = 0; Row < NumRows; ++Row) {
264 char InnerDep = DepMatrix[Row][InnerLoopId];
265 char OuterDep = DepMatrix[Row][OuterLoopId];
266 if (InnerDep == '*' || OuterDep == '*')
267 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000269 return false;
270 }
271 return true;
272}
273
274static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000275 DEBUG(dbgs() << "Calling populateWorklist on Func: "
276 << L.getHeader()->getParent()->getName() << " Loop: %"
277 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000278 LoopVector LoopList;
279 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000280 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
281 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000282 // The current loop has multiple subloops in it hence it is not tightly
283 // nested.
284 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000285 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000286 LoopList.clear();
287 return;
288 }
289 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000290 CurrentLoop = Vec->front();
291 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000292 }
293 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000294 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000295}
296
297static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
298 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
299 if (InnerIndexVar)
300 return InnerIndexVar;
301 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
302 return nullptr;
303 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
304 PHINode *PhiVar = cast<PHINode>(I);
305 Type *PhiTy = PhiVar->getType();
306 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
307 !PhiTy->isPointerTy())
308 return nullptr;
309 const SCEVAddRecExpr *AddRec =
310 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
311 if (!AddRec || !AddRec->isAffine())
312 continue;
313 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000314 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000315 continue;
316 // Found the induction variable.
317 // FIXME: Handle loops with more than one induction variable. Note that,
318 // currently, legality makes sure we have only one induction variable.
319 return PhiVar;
320 }
321 return nullptr;
322}
323
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000324namespace {
325
Karthik Bhat88db86d2015-03-06 10:11:25 +0000326/// LoopInterchangeLegality checks if it is legal to interchange the loop.
327class LoopInterchangeLegality {
328public:
329 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000330 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA,
331 OptimizationRemarkEmitter *ORE)
Justin Bogner843fb202015-12-15 19:40:57 +0000332 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000333 PreserveLCSSA(PreserveLCSSA), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000334
335 /// Check if the loops can be interchanged.
336 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
337 CharMatrix &DepMatrix);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000338
Karthik Bhat88db86d2015-03-06 10:11:25 +0000339 /// 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);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000355
Karthik Bhat88db86d2015-03-06 10:11:25 +0000356 Loop *OuterLoop;
357 Loop *InnerLoop;
358
Karthik Bhat88db86d2015-03-06 10:11:25 +0000359 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000360 LoopInfo *LI;
361 DominatorTree *DT;
362 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000363
Florian Hahnad993522017-07-15 13:13:19 +0000364 /// Interface to emit optimization remarks.
365 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000366
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000367 bool InnerLoopHasReduction = false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000368};
369
370/// LoopInterchangeProfitability checks if it is profitable to interchange the
371/// loop.
372class LoopInterchangeProfitability {
373public:
Florian Hahnad993522017-07-15 13:13:19 +0000374 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
375 OptimizationRemarkEmitter *ORE)
376 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000377
Vikram TV74b41112015-12-09 05:16:24 +0000378 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000379 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
380 CharMatrix &DepMatrix);
381
382private:
383 int getInstrOrderCost();
384
385 Loop *OuterLoop;
386 Loop *InnerLoop;
387
388 /// Scev analysis.
389 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000390
Florian Hahnad993522017-07-15 13:13:19 +0000391 /// Interface to emit optimization remarks.
392 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000393};
394
Vikram TV74b41112015-12-09 05:16:24 +0000395/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000396class LoopInterchangeTransform {
397public:
398 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
399 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000400 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000401 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000402 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000403 LoopExit(LoopNestExit),
404 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000405
406 /// Interchange OuterLoop and InnerLoop.
407 bool transform();
Florian Hahn831a7572018-04-05 09:48:45 +0000408 void restructureLoops(Loop *NewInner, Loop *NewOuter,
409 BasicBlock *OrigInnerPreHeader,
410 BasicBlock *OrigOuterPreHeader);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000411 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000412
413private:
414 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000415 void splitInnerLoopHeader();
416 bool adjustLoopLinks();
417 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000418 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000419 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
420 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000421
422 Loop *OuterLoop;
423 Loop *InnerLoop;
424
425 /// Scev analysis.
426 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000427
Karthik Bhat88db86d2015-03-06 10:11:25 +0000428 LoopInfo *LI;
429 DominatorTree *DT;
430 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000431 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000432};
433
Vikram TV74b41112015-12-09 05:16:24 +0000434// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000435struct LoopInterchange : public FunctionPass {
436 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000437 ScalarEvolution *SE = nullptr;
438 LoopInfo *LI = nullptr;
439 DependenceInfo *DI = nullptr;
440 DominatorTree *DT = nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000441 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000442
Florian Hahnad993522017-07-15 13:13:19 +0000443 /// Interface to emit optimization remarks.
444 OptimizationRemarkEmitter *ORE;
445
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000446 LoopInterchange() : FunctionPass(ID) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000447 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
448 }
449
450 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000451 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000452 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000453 AU.addRequired<DominatorTreeWrapperPass>();
454 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000455 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000456 AU.addRequiredID(LoopSimplifyID);
457 AU.addRequiredID(LCSSAID);
Florian Hahnad993522017-07-15 13:13:19 +0000458 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000459
460 AU.addPreserved<DominatorTreeWrapperPass>();
Florian Hahn831a7572018-04-05 09:48:45 +0000461 AU.addPreserved<LoopInfoWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000462 }
463
464 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000465 if (skipFunction(F))
466 return false;
467
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000468 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000469 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000470 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000471 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Florian Hahnad993522017-07-15 13:13:19 +0000472 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000473 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
474
Karthik Bhat88db86d2015-03-06 10:11:25 +0000475 // Build up a worklist of loop pairs to analyze.
476 SmallVector<LoopVector, 8> Worklist;
477
478 for (Loop *L : *LI)
479 populateWorklist(*L, Worklist);
480
Chad Rosiera4c42462016-09-12 13:24:47 +0000481 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000482 bool Changed = true;
483 while (!Worklist.empty()) {
484 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000485 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000486 }
487 return Changed;
488 }
489
490 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000491 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000492 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
493 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000494 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000495 return false;
496 }
497 if (L->getNumBackEdges() != 1) {
498 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
499 return false;
500 }
501 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000502 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000503 return false;
504 }
505 }
506 return true;
507 }
508
Benjamin Kramerc321e532016-06-08 19:09:22 +0000509 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000510 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000511 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000512 return LoopList.size() - 1;
513 }
514
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000515 bool processLoopList(LoopVector LoopList, Function &F) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000516 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000517 unsigned LoopNestDepth = LoopList.size();
518 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000519 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
520 return false;
521 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000522 if (LoopNestDepth > MaxLoopNestDepth) {
523 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
524 << MaxLoopNestDepth << "\n");
525 return false;
526 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000527 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000528 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000529 return false;
530 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000531
532 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
533
534 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000535 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000536 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000537 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000538 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000539 return false;
540 }
541#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000542 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000543 printDepMatrix(DependencyMatrix);
544#endif
545
Karthik Bhat88db86d2015-03-06 10:11:25 +0000546 // Since we currently do not handle LCSSA PHI's any failure in loop
547 // condition will now branch to LoopNestExit.
548 // TODO: This should be removed once we handle LCSSA PHI nodes.
549
550 // Get the Outermost loop exit.
Florian Hahn1da30c62018-04-25 09:35:54 +0000551 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
552 if (!LoopNestExit) {
553 DEBUG(dbgs() << "OuterMostLoop needs an unique exit block");
554 return false;
555 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000556
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000557 if (isa<PHINode>(LoopNestExit->begin())) {
558 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
559 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000560 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000561 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000562
563 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000564 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000565 for (unsigned i = SelecLoopId; i > 0; i--) {
566 bool Interchanged =
567 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
568 if (!Interchanged)
569 return Changed;
570 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000571 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000572
573 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000574 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000575#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000576 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000577 printDepMatrix(DependencyMatrix);
578#endif
579 Changed |= Interchanged;
580 }
581 return Changed;
582 }
583
584 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
585 unsigned OuterLoopId, BasicBlock *LoopNestExit,
586 std::vector<std::vector<char>> &DependencyMatrix) {
Chad Rosier13bc0d192016-09-07 18:15:12 +0000587 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000588 << " and OuterLoopId = " << OuterLoopId << "\n");
589 Loop *InnerLoop = LoopList[InnerLoopId];
590 Loop *OuterLoop = LoopList[OuterLoopId];
591
Justin Bogner843fb202015-12-15 19:40:57 +0000592 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
Florian Hahnad993522017-07-15 13:13:19 +0000593 PreserveLCSSA, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000594 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000595 DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000596 return false;
597 }
598 DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000599 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000600 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000601 DEBUG(dbgs() << "Interchanging loops not profitable.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000602 return false;
603 }
604
Vivek Pandya95906582017-10-11 17:12:59 +0000605 ORE->emit([&]() {
606 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
607 InnerLoop->getStartLoc(),
608 InnerLoop->getHeader())
609 << "Loop interchanged with enclosing loop.";
610 });
Florian Hahnad993522017-07-15 13:13:19 +0000611
Justin Bogner843fb202015-12-15 19:40:57 +0000612 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000613 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000614 LIT.transform();
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000615 DEBUG(dbgs() << "Loops interchanged.\n");
Florian Hahn6e004332018-04-05 10:39:23 +0000616 LoopsInterchanged++;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000617 return true;
618 }
619};
620
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000621} // end anonymous namespace
622
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000623bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000624 return llvm::none_of(Ins->users(), [=](User *U) -> bool {
David Majnemer0a16c222016-08-11 21:15:00 +0000625 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000626 RecurrenceDescriptor RD;
627 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000628 });
629}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000630
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000631bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
632 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000633 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000634 // Load corresponding to reduction PHI's are safe while concluding if
635 // tightly nested.
636 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
637 if (!areAllUsesReductions(L, InnerLoop))
638 return true;
639 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
640 return true;
641 }
642 return false;
643}
644
645bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
646 BasicBlock *BB) {
647 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
648 // Stores corresponding to reductions are safe while concluding if tightly
649 // nested.
650 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000651 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000652 return true;
653 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000654 return true;
655 }
656 return false;
657}
658
659bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
660 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
661 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
662 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
663
Chad Rosierf7c76f92016-09-21 13:28:41 +0000664 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000665
666 // A perfectly nested loop will not have any branch in between the outer and
667 // inner block i.e. outer header will branch to either inner preheader and
668 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000669 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000670 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000671 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000672 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000673
Florian Hahnf66efd62017-07-24 11:41:30 +0000674 for (BasicBlock *Succ : OuterLoopHeaderBI->successors())
675 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000676 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000677
Chad Rosierf7c76f92016-09-21 13:28:41 +0000678 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000679 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000680 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000681 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
682 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000683 return false;
684
Chad Rosierf7c76f92016-09-21 13:28:41 +0000685 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000686 // We have a perfect loop nest.
687 return true;
688}
689
Karthik Bhat88db86d2015-03-06 10:11:25 +0000690bool LoopInterchangeLegality::isLoopStructureUnderstood(
691 PHINode *InnerInduction) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000692 unsigned Num = InnerInduction->getNumOperands();
693 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
694 for (unsigned i = 0; i < Num; ++i) {
695 Value *Val = InnerInduction->getOperand(i);
696 if (isa<Constant>(Val))
697 continue;
698 Instruction *I = dyn_cast<Instruction>(Val);
699 if (!I)
700 return false;
701 // TODO: Handle triangular loops.
702 // e.g. for(int i=0;i<N;i++)
703 // for(int j=i;j<N;j++)
704 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
705 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
706 InnerLoopPreheader &&
707 !OuterLoop->isLoopInvariant(I)) {
708 return false;
709 }
710 }
711 return true;
712}
713
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000714bool LoopInterchangeLegality::findInductionAndReductions(
715 Loop *L, SmallVector<PHINode *, 8> &Inductions,
716 SmallVector<PHINode *, 8> &Reductions) {
717 if (!L->getLoopLatch() || !L->getLoopPredecessor())
718 return false;
719 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000720 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000721 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000722 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000723 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000724 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000725 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000726 Reductions.push_back(PHI);
727 else {
728 DEBUG(
729 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
730 return false;
731 }
732 }
733 return true;
734}
735
736static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
737 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
738 PHINode *PHI = cast<PHINode>(I);
739 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
740 if (PHI->getNumIncomingValues() > 1)
741 return false;
742 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
743 if (!Ins)
744 return false;
745 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
746 // exits lcssa phi else it would not be tightly nested.
747 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
748 return false;
749 }
750 return true;
751}
752
Karthik Bhat88db86d2015-03-06 10:11:25 +0000753// This function indicates the current limitations in the transform as a result
754// of which we do not proceed.
755bool LoopInterchangeLegality::currentLimitations() {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000756 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000757 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Florian Hahn1da30c62018-04-25 09:35:54 +0000758
759 // transform currently expects the loop latches to also be the exiting
760 // blocks.
761 if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
762 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
763 !isa<BranchInst>(InnerLoopLatch->getTerminator()) ||
764 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) {
765 DEBUG(dbgs() << "Loops where the latch is not the exiting block are not"
766 << " supported currently.\n");
767 ORE->emit([&]() {
768 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
769 OuterLoop->getStartLoc(),
770 OuterLoop->getHeader())
771 << "Loops where the latch is not the exiting block cannot be"
772 " interchange currently.";
773 });
774 return true;
775 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000776
777 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000778 SmallVector<PHINode *, 8> Inductions;
779 SmallVector<PHINode *, 8> Reductions;
Florian Hahn4eeff392017-07-03 15:32:00 +0000780 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
781 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes "
782 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000783 ORE->emit([&]() {
784 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
785 InnerLoop->getStartLoc(),
786 InnerLoop->getHeader())
787 << "Only inner loops with induction or reduction PHI nodes can be"
788 " interchange currently.";
789 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000790 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000791 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000792
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000793 // TODO: Currently we handle only loops with 1 induction variable.
794 if (Inductions.size() != 1) {
795 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
796 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000797 ORE->emit([&]() {
798 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
799 InnerLoop->getStartLoc(),
800 InnerLoop->getHeader())
801 << "Only inner loops with 1 induction variable can be "
802 "interchanged currently.";
803 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000804 return true;
805 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000806 if (Reductions.size() > 0)
807 InnerLoopHasReduction = true;
808
809 InnerInductionVar = Inductions.pop_back_val();
810 Reductions.clear();
Florian Hahn4eeff392017-07-03 15:32:00 +0000811 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
812 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes "
813 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000814 ORE->emit([&]() {
815 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
816 OuterLoop->getStartLoc(),
817 OuterLoop->getHeader())
818 << "Only outer loops with induction or reduction PHI nodes can be"
819 " interchanged currently.";
820 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000821 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000822 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000823
824 // Outer loop cannot have reduction because then loops will not be tightly
825 // nested.
Florian Hahn4eeff392017-07-03 15:32:00 +0000826 if (!Reductions.empty()) {
827 DEBUG(dbgs() << "Outer loops with reductions are not supported "
828 << "currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000829 ORE->emit([&]() {
830 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter",
831 OuterLoop->getStartLoc(),
832 OuterLoop->getHeader())
833 << "Outer loops with reductions cannot be interchangeed "
834 "currently.";
835 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000836 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000837 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000838 // TODO: Currently we handle only loops with 1 induction variable.
Florian Hahn4eeff392017-07-03 15:32:00 +0000839 if (Inductions.size() != 1) {
840 DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
841 << "supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000842 ORE->emit([&]() {
843 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
844 OuterLoop->getStartLoc(),
845 OuterLoop->getHeader())
846 << "Only outer loops with 1 induction variable can be "
847 "interchanged currently.";
848 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000849 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000850 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000851
852 // TODO: Triangular loops are not handled for now.
853 if (!isLoopStructureUnderstood(InnerInductionVar)) {
854 DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000855 ORE->emit([&]() {
856 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
857 InnerLoop->getStartLoc(),
858 InnerLoop->getHeader())
859 << "Inner loop structure not understood currently.";
860 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000861 return true;
862 }
863
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000864 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
Florian Hahn1da30c62018-04-25 09:35:54 +0000865 BasicBlock *OuterExit = OuterLoop->getExitBlock();
866 if (!containsSafePHI(OuterExit, true)) {
Florian Hahn4eeff392017-07-03 15:32:00 +0000867 DEBUG(dbgs() << "Can only handle LCSSA PHIs in outer loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000868 ORE->emit([&]() {
869 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuter",
870 OuterLoop->getStartLoc(),
871 OuterLoop->getHeader())
872 << "Only outer loops with LCSSA PHIs can be interchange "
873 "currently.";
874 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000875 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000876 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000877
Florian Hahn1da30c62018-04-25 09:35:54 +0000878 BasicBlock *InnerExit = InnerLoop->getExitBlock();
879 if (!containsSafePHI(InnerExit, false)) {
Florian Hahn4eeff392017-07-03 15:32:00 +0000880 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000881 ORE->emit([&]() {
882 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
883 InnerLoop->getStartLoc(),
884 InnerLoop->getHeader())
885 << "Only inner loops with LCSSA PHIs can be interchange "
886 "currently.";
887 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000888 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000889 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000890
891 // TODO: Current limitation: Since we split the inner loop latch at the point
892 // were induction variable is incremented (induction.next); We cannot have
893 // more than 1 user of induction.next since it would result in broken code
894 // after split.
895 // e.g.
896 // for(i=0;i<N;i++) {
897 // for(j = 0;j<M;j++) {
898 // A[j+1][i+2] = A[j][i]+k;
899 // }
900 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000901 Instruction *InnerIndexVarInc = nullptr;
902 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
903 InnerIndexVarInc =
904 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
905 else
906 InnerIndexVarInc =
907 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
908
Florian Hahn4eeff392017-07-03 15:32:00 +0000909 if (!InnerIndexVarInc) {
910 DEBUG(dbgs() << "Did not find an instruction to increment the induction "
911 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000912 ORE->emit([&]() {
913 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
914 InnerLoop->getStartLoc(),
915 InnerLoop->getHeader())
916 << "The inner loop does not increment the induction variable.";
917 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000918 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000919 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000920
Karthik Bhat88db86d2015-03-06 10:11:25 +0000921 // Since we split the inner loop latch on this induction variable. Make sure
922 // we do not have any instruction between the induction variable and branch
923 // instruction.
924
David Majnemerd7708772016-06-24 04:05:21 +0000925 bool FoundInduction = false;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000926 for (const Instruction &I : llvm::reverse(*InnerLoopLatch)) {
Florian Hahncd783452017-08-25 16:52:29 +0000927 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
928 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000929 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000930
Karthik Bhat88db86d2015-03-06 10:11:25 +0000931 // We found an instruction. If this is not induction variable then it is not
932 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000933 if (!I.isIdenticalTo(InnerIndexVarInc)) {
934 DEBUG(dbgs() << "Found unsupported instructions between induction "
935 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000936 ORE->emit([&]() {
937 return OptimizationRemarkMissed(
938 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
939 InnerLoop->getStartLoc(), InnerLoop->getHeader())
940 << "Found unsupported instruction between induction variable "
941 "increment and branch.";
942 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000943 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000944 }
David Majnemerd7708772016-06-24 04:05:21 +0000945
946 FoundInduction = true;
947 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000948 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000949 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000950 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000951 if (!FoundInduction) {
952 DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000953 ORE->emit([&]() {
954 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
955 InnerLoop->getStartLoc(),
956 InnerLoop->getHeader())
957 << "Did not find the induction variable.";
958 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000959 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000960 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000961 return false;
962}
963
964bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
965 unsigned OuterLoopId,
966 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000967 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
968 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000969 << " and OuterLoopId = " << OuterLoopId
970 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000971 ORE->emit([&]() {
972 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
973 InnerLoop->getStartLoc(),
974 InnerLoop->getHeader())
975 << "Cannot interchange loops due to dependences.";
976 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000977 return false;
978 }
979
Florian Hahn42840492017-07-31 09:00:52 +0000980 // Check if outer and inner loop contain legal instructions only.
981 for (auto *BB : OuterLoop->blocks())
982 for (Instruction &I : *BB)
983 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
984 // readnone functions do not prevent interchanging.
985 if (CI->doesNotReadMemory())
986 continue;
987 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged "
988 << "safely.");
Florian Hahn9467ccf2018-04-03 20:54:04 +0000989 ORE->emit([&]() {
990 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
991 CI->getDebugLoc(),
992 CI->getParent())
993 << "Cannot interchange loops due to call instruction.";
994 });
995
Florian Hahn42840492017-07-31 09:00:52 +0000996 return false;
997 }
998
Karthik Bhat88db86d2015-03-06 10:11:25 +0000999 // Create unique Preheaders if we already do not have one.
1000 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1001 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1002
1003 // Create a unique outer preheader -
1004 // 1) If OuterLoop preheader is not present.
1005 // 2) If OuterLoop Preheader is same as OuterLoop Header
1006 // 3) If OuterLoop Preheader is same as Header of the previous loop.
1007 // 4) If OuterLoop Preheader is Entry node.
1008 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
1009 isa<PHINode>(OuterLoopPreHeader->begin()) ||
1010 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001011 OuterLoopPreHeader =
1012 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001013 }
1014
1015 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
1016 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001017 InnerLoopPreHeader =
1018 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001019 }
1020
Karthik Bhat88db86d2015-03-06 10:11:25 +00001021 // TODO: The loops could not be interchanged due to current limitations in the
1022 // transform module.
1023 if (currentLimitations()) {
1024 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1025 return false;
1026 }
1027
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001028 // Check if the loops are tightly nested.
1029 if (!tightlyNested(OuterLoop, InnerLoop)) {
1030 DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001031 ORE->emit([&]() {
1032 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1033 InnerLoop->getStartLoc(),
1034 InnerLoop->getHeader())
1035 << "Cannot interchange loops because they are not tightly "
1036 "nested.";
1037 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001038 return false;
1039 }
1040
Karthik Bhat88db86d2015-03-06 10:11:25 +00001041 return true;
1042}
1043
1044int LoopInterchangeProfitability::getInstrOrderCost() {
1045 unsigned GoodOrder, BadOrder;
1046 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001047 for (BasicBlock *BB : InnerLoop->blocks()) {
1048 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001049 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1050 unsigned NumOp = GEP->getNumOperands();
1051 bool FoundInnerInduction = false;
1052 bool FoundOuterInduction = false;
1053 for (unsigned i = 0; i < NumOp; ++i) {
1054 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1055 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1056 if (!AR)
1057 continue;
1058
1059 // If we find the inner induction after an outer induction e.g.
1060 // for(int i=0;i<N;i++)
1061 // for(int j=0;j<N;j++)
1062 // A[i][j] = A[i-1][j-1]+k;
1063 // then it is a good order.
1064 if (AR->getLoop() == InnerLoop) {
1065 // We found an InnerLoop induction after OuterLoop induction. It is
1066 // a good order.
1067 FoundInnerInduction = true;
1068 if (FoundOuterInduction) {
1069 GoodOrder++;
1070 break;
1071 }
1072 }
1073 // If we find the outer induction after an inner induction e.g.
1074 // for(int i=0;i<N;i++)
1075 // for(int j=0;j<N;j++)
1076 // A[j][i] = A[j-1][i-1]+k;
1077 // then it is a bad order.
1078 if (AR->getLoop() == OuterLoop) {
1079 // We found an OuterLoop induction after InnerLoop induction. It is
1080 // a bad order.
1081 FoundOuterInduction = true;
1082 if (FoundInnerInduction) {
1083 BadOrder++;
1084 break;
1085 }
1086 }
1087 }
1088 }
1089 }
1090 }
1091 return GoodOrder - BadOrder;
1092}
1093
Chad Rosiere6b3a632016-09-14 17:12:30 +00001094static bool isProfitableForVectorization(unsigned InnerLoopId,
1095 unsigned OuterLoopId,
1096 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001097 // TODO: Improve this heuristic to catch more cases.
1098 // If the inner loop is loop independent or doesn't carry any dependency it is
1099 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001100 for (auto &Row : DepMatrix) {
1101 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001102 return false;
1103 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001104 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001105 return false;
1106 }
1107 // If outer loop has dependence and inner loop is loop independent then it is
1108 // profitable to interchange to enable parallelism.
Florian Hahnceee7882018-04-24 16:55:32 +00001109 // If there are no dependences, interchanging will not improve anything.
1110 return !DepMatrix.empty();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001111}
1112
1113bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1114 unsigned OuterLoopId,
1115 CharMatrix &DepMatrix) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001116 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001117 // e.g
1118 // 1) Construct dependency matrix and move the one with no loop carried dep
1119 // inside to enable vectorization.
1120
1121 // This is rough cost estimation algorithm. It counts the good and bad order
1122 // of induction variables in the instruction and allows reordering if number
1123 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001124 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001125 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001126 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001127 return true;
1128
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001129 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001130 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001131 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1132 return true;
1133
Vivek Pandya95906582017-10-11 17:12:59 +00001134 ORE->emit([&]() {
1135 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1136 InnerLoop->getStartLoc(),
1137 InnerLoop->getHeader())
1138 << "Interchanging loops is too costly (cost="
1139 << ore::NV("Cost", Cost) << ", threshold="
1140 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1141 << ") and it does not improve parallelism.";
1142 });
Florian Hahnad993522017-07-15 13:13:19 +00001143 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001144}
1145
1146void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1147 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001148 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
1149 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001150 if (*I == InnerLoop) {
1151 OuterLoop->removeChildLoop(I);
1152 return;
1153 }
1154 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001155 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001156}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001157
Florian Hahn831a7572018-04-05 09:48:45 +00001158/// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1159/// new inner and outer loop after interchanging: NewInner is the original
1160/// outer loop and NewOuter is the original inner loop.
1161///
1162/// Before interchanging, we have the following structure
1163/// Outer preheader
1164// Outer header
1165// Inner preheader
1166// Inner header
1167// Inner body
1168// Inner latch
1169// outer bbs
1170// Outer latch
1171//
1172// After interchanging:
1173// Inner preheader
1174// Inner header
1175// Outer preheader
1176// Outer header
1177// Inner body
1178// outer bbs
1179// Outer latch
1180// Inner latch
1181void LoopInterchangeTransform::restructureLoops(
1182 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1183 BasicBlock *OrigOuterPreHeader) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001184 Loop *OuterLoopParent = OuterLoop->getParentLoop();
Florian Hahn831a7572018-04-05 09:48:45 +00001185 // The original inner loop preheader moves from the new inner loop to
1186 // the parent loop, if there is one.
1187 NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1188 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1189
1190 // Switch the loop levels.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001191 if (OuterLoopParent) {
1192 // Remove the loop from its parent loop.
Florian Hahn831a7572018-04-05 09:48:45 +00001193 removeChildLoop(OuterLoopParent, NewInner);
1194 removeChildLoop(NewInner, NewOuter);
1195 OuterLoopParent->addChildLoop(NewOuter);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001196 } else {
Florian Hahn831a7572018-04-05 09:48:45 +00001197 removeChildLoop(NewInner, NewOuter);
1198 LI->changeTopLevelLoop(NewInner, NewOuter);
1199 }
1200 while (!NewOuter->empty())
1201 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1202 NewOuter->addChildLoop(NewInner);
1203
1204 // BBs from the original inner loop.
1205 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1206
1207 // Add BBs from the original outer loop to the original inner loop (excluding
1208 // BBs already in inner loop)
1209 for (BasicBlock *BB : NewInner->blocks())
1210 if (LI->getLoopFor(BB) == NewInner)
1211 NewOuter->addBlockEntry(BB);
1212
1213 // Now remove inner loop header and latch from the new inner loop and move
1214 // other BBs (the loop body) to the new inner loop.
1215 BasicBlock *OuterHeader = NewOuter->getHeader();
1216 BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1217 for (BasicBlock *BB : OrigInnerBBs) {
Florian Hahn744181852018-04-23 21:38:19 +00001218 // Nothing will change for BBs in child loops.
1219 if (LI->getLoopFor(BB) != NewOuter)
1220 continue;
Florian Hahn831a7572018-04-05 09:48:45 +00001221 // Remove the new outer loop header and latch from the new inner loop.
1222 if (BB == OuterHeader || BB == OuterLatch)
1223 NewInner->removeBlockFromLoop(BB);
1224 else
1225 LI->changeLoopFor(BB, NewInner);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001226 }
1227
Florian Hahn831a7572018-04-05 09:48:45 +00001228 // The preheader of the original outer loop becomes part of the new
1229 // outer loop.
1230 NewOuter->addBlockEntry(OrigOuterPreHeader);
1231 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001232}
1233
1234bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001235 bool Transformed = false;
1236 Instruction *InnerIndexVar;
1237
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001238 if (InnerLoop->getSubLoops().empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001239 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1240 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1241 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1242 if (!InductionPHI) {
1243 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1244 return false;
1245 }
1246
1247 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1248 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1249 else
1250 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1251
David Green907b60f2017-10-21 13:58:37 +00001252 // Ensure that InductionPHI is the first Phi node as required by
1253 // splitInnerLoopHeader
1254 if (&InductionPHI->getParent()->front() != InductionPHI)
1255 InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1256
Karthik Bhat88db86d2015-03-06 10:11:25 +00001257 // Split at the place were the induction variable is
1258 // incremented/decremented.
1259 // TODO: This splitting logic may not work always. Fix this.
1260 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001261 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001262
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001263 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001264 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001265 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001266 }
1267
1268 Transformed |= adjustLoopLinks();
1269 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001270 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001271 return false;
1272 }
1273
Karthik Bhat88db86d2015-03-06 10:11:25 +00001274 return true;
1275}
1276
Benjamin Kramer79442922015-03-06 18:59:14 +00001277void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001278 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001279 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001280 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001281}
1282
Karthik Bhat88db86d2015-03-06 10:11:25 +00001283void LoopInterchangeTransform::splitInnerLoopHeader() {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001284 // Split the inner loop header out. Here make sure that the reduction PHI's
1285 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001286 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001287 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Florian Hahne54a20e2018-02-12 11:10:58 +00001288 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001289 if (InnerLoopHasReduction) {
Florian Hahne54a20e2018-02-12 11:10:58 +00001290 // Adjust Reduction PHI's in the block. The induction PHI must be the first
1291 // PHI in InnerLoopHeader for this to work.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001292 SmallVector<PHINode *, 8> PHIVec;
Florian Hahne54a20e2018-02-12 11:10:58 +00001293 for (auto I = std::next(InnerLoopHeader->begin()); isa<PHINode>(I); ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001294 PHINode *PHI = dyn_cast<PHINode>(I);
1295 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1296 PHI->replaceAllUsesWith(V);
1297 PHIVec.push_back((PHI));
1298 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001299 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001300 P->eraseFromParent();
1301 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001302 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001303
1304 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001305 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001306}
1307
Benjamin Kramer79442922015-03-06 18:59:14 +00001308/// \brief Move all instructions except the terminator from FromBB right before
1309/// InsertBefore
1310static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1311 auto &ToList = InsertBefore->getParent()->getInstList();
1312 auto &FromList = FromBB->getInstList();
1313
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001314 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1315 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001316}
1317
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001318void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1319 BasicBlock *OldPred,
1320 BasicBlock *NewPred) {
1321 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1322 PHINode *PHI = cast<PHINode>(I);
1323 unsigned Num = PHI->getNumIncomingValues();
1324 for (unsigned i = 0; i < Num; ++i) {
1325 if (PHI->getIncomingBlock(i) == OldPred)
1326 PHI->setIncomingBlock(i, NewPred);
1327 }
1328 }
1329}
1330
Florian Hahnc6296fe2018-02-14 13:13:15 +00001331/// \brief Update BI to jump to NewBB instead of OldBB. Records updates to
1332/// the dominator tree in DTUpdates, if DT should be preserved.
1333static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1334 BasicBlock *NewBB,
1335 std::vector<DominatorTree::UpdateType> &DTUpdates) {
1336 assert(llvm::count_if(BI->successors(),
1337 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 &&
1338 "BI must jump to OldBB at most once.");
1339 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) {
1340 if (BI->getSuccessor(i) == OldBB) {
1341 BI->setSuccessor(i, NewBB);
1342
1343 DTUpdates.push_back(
1344 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1345 DTUpdates.push_back(
1346 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1347 break;
1348 }
1349 }
1350}
1351
Karthik Bhat88db86d2015-03-06 10:11:25 +00001352bool LoopInterchangeTransform::adjustLoopBranches() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001353 DEBUG(dbgs() << "adjustLoopBranches called\n");
Florian Hahnc6296fe2018-02-14 13:13:15 +00001354 std::vector<DominatorTree::UpdateType> DTUpdates;
1355
Karthik Bhat88db86d2015-03-06 10:11:25 +00001356 // Adjust the loop preheader
1357 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1358 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1359 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1360 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1361 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1362 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1363 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1364 BasicBlock *InnerLoopLatchPredecessor =
1365 InnerLoopLatch->getUniquePredecessor();
1366 BasicBlock *InnerLoopLatchSuccessor;
1367 BasicBlock *OuterLoopLatchSuccessor;
1368
1369 BranchInst *OuterLoopLatchBI =
1370 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1371 BranchInst *InnerLoopLatchBI =
1372 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1373 BranchInst *OuterLoopHeaderBI =
1374 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1375 BranchInst *InnerLoopHeaderBI =
1376 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1377
1378 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1379 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1380 !InnerLoopHeaderBI)
1381 return false;
1382
1383 BranchInst *InnerLoopLatchPredecessorBI =
1384 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1385 BranchInst *OuterLoopPredecessorBI =
1386 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1387
1388 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1389 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001390 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1391 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001392 return false;
1393
1394 // Adjust Loop Preheader and headers
Florian Hahnc6296fe2018-02-14 13:13:15 +00001395 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1396 InnerLoopPreHeader, DTUpdates);
1397 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates);
1398 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1399 InnerLoopHeaderSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001400
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001401 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001402 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001403 OuterLoopHeader);
1404
Florian Hahnc6296fe2018-02-14 13:13:15 +00001405 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1406 OuterLoopPreHeader, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001407
1408 // -------------Adjust loop latches-----------
1409 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1410 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1411 else
1412 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1413
Florian Hahnc6296fe2018-02-14 13:13:15 +00001414 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1415 InnerLoopLatchSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001416
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001417 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1418 // the value and remove this PHI node from inner loop.
1419 SmallVector<PHINode *, 8> LcssaVec;
1420 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1421 PHINode *LcssaPhi = cast<PHINode>(I);
1422 LcssaVec.push_back(LcssaPhi);
1423 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001424 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001425 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1426 P->replaceAllUsesWith(Incoming);
1427 P->eraseFromParent();
1428 }
1429
Karthik Bhat88db86d2015-03-06 10:11:25 +00001430 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1431 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1432 else
1433 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1434
Florian Hahnc6296fe2018-02-14 13:13:15 +00001435 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1436 OuterLoopLatchSuccessor, DTUpdates);
1437 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1438 DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001439
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001440 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1441
Florian Hahnc6296fe2018-02-14 13:13:15 +00001442 DT->applyUpdates(DTUpdates);
Florian Hahn831a7572018-04-05 09:48:45 +00001443 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1444 OuterLoopPreHeader);
1445
Karthik Bhat88db86d2015-03-06 10:11:25 +00001446 return true;
1447}
Karthik Bhat88db86d2015-03-06 10:11:25 +00001448
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001449void LoopInterchangeTransform::adjustLoopPreheaders() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001450 // We have interchanged the preheaders so we need to interchange the data in
1451 // the preheader as well.
1452 // This is because the content of inner preheader was previously executed
1453 // inside the outer loop.
1454 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1455 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1456 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1457 BranchInst *InnerTermBI =
1458 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1459
Karthik Bhat88db86d2015-03-06 10:11:25 +00001460 // These instructions should now be executed inside the loop.
1461 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001462 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001463 // These instructions were not executed previously in the loop so move them to
1464 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001465 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001466}
1467
1468bool LoopInterchangeTransform::adjustLoopLinks() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001469 // Adjust all branches in the inner and outer loop.
1470 bool Changed = adjustLoopBranches();
1471 if (Changed)
1472 adjustLoopPreheaders();
1473 return Changed;
1474}
1475
1476char LoopInterchange::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001477
Karthik Bhat88db86d2015-03-06 10:11:25 +00001478INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1479 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001480INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001481INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001482INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001483INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001484INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001485INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001486INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001487INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001488
1489INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1490 "Interchanges loops for cache reuse", false, false)
1491
1492Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }