Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1 | //===- 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 Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 18 | #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 Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Dominators.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Function.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 33 | #include "llvm/IR/InstIterator.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 34 | #include "llvm/IR/IntrinsicInst.h" |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Module.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 36 | #include "llvm/Pass.h" |
| 37 | #include "llvm/Support/Debug.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 38 | #include "llvm/Support/raw_ostream.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Scalar.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 41 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 42 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 43 | using namespace llvm; |
| 44 | |
| 45 | #define DEBUG_TYPE "loop-interchange" |
| 46 | |
| 47 | namespace { |
| 48 | |
| 49 | typedef SmallVector<Loop *, 8> LoopVector; |
| 50 | |
| 51 | // TODO: Check if we can use a sparse matrix here. |
| 52 | typedef std::vector<std::vector<char>> CharMatrix; |
| 53 | |
| 54 | // Maximum number of dependencies that can be handled in the dependency matrix. |
| 55 | static const unsigned MaxMemInstrCount = 100; |
| 56 | |
| 57 | // Maximum loop depth supported. |
| 58 | static const unsigned MaxLoopNestDepth = 10; |
| 59 | |
| 60 | struct LoopInterchange; |
| 61 | |
| 62 | #ifdef DUMP_DEP_MATRICIES |
| 63 | void 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 Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 73 | static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 74 | Loop *L, DependenceInfo *DI) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 75 | 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 Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame^] | 90 | if (!isa<Instruction>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 91 | return false; |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame^] | 92 | 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 Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 101 | } |
| 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 Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame^] | 112 | Instruction *Src = cast<Instruction>(*I); |
| 113 | Instruction *Dst = cast<Instruction>(*J); |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 114 | if (Src == Dst) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 115 | continue; |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 116 | if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 117 | continue; |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 118 | 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 Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 121 | if (D->isFlow()) { |
| 122 | // TODO: Handle Flow dependence.Check if it is sufficient to populate |
| 123 | // the Dependence Matrix with the direction reversed. |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 124 | DEBUG(dbgs() << "Flow dependence not handled\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 125 | return false; |
| 126 | } |
| 127 | if (D->isAnti()) { |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 128 | DEBUG(dbgs() << "Found Anti dependence\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 129 | 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 TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 177 | // We don't have a DepMatrix to check legality return false. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 178 | 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. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 185 | static void interChangeDepedencies(CharMatrix &DepMatrix, unsigned FromIndx, |
| 186 | unsigned ToIndx) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 187 | 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 Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 197 | static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, |
| 198 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 199 | 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 Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 210 | static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, |
| 211 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 212 | 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 Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 220 | static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, |
| 221 | unsigned OuterLoopId, char InnerDep, |
| 222 | char OuterDep) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 223 | |
| 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 Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 256 | // [Theorem] A permutation of the loops in a perfect nest is legal if and only |
| 257 | // if |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 258 | // the direction matrix, after the same permutation is applied to its columns, |
| 259 | // has no ">" direction as the leftmost non-"=" direction in any row. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 260 | static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, |
| 261 | unsigned InnerLoopId, |
| 262 | unsigned OuterLoopId) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 263 | |
| 264 | unsigned NumRows = DepMatrix.size(); |
| 265 | // For each row check if it is valid to interchange. |
| 266 | for (unsigned Row = 0; Row < NumRows; ++Row) { |
| 267 | char InnerDep = DepMatrix[Row][InnerLoopId]; |
| 268 | char OuterDep = DepMatrix[Row][OuterLoopId]; |
| 269 | if (InnerDep == '*' || OuterDep == '*') |
| 270 | return false; |
| 271 | else if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, |
| 272 | OuterDep)) |
| 273 | return false; |
| 274 | } |
| 275 | return true; |
| 276 | } |
| 277 | |
| 278 | static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) { |
| 279 | |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 280 | DEBUG(dbgs() << "Calling populateWorklist on Func: " |
| 281 | << L.getHeader()->getParent()->getName() << " Loop: %" |
| 282 | << L.getHeader()->getName() << '\n'); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 283 | LoopVector LoopList; |
| 284 | Loop *CurrentLoop = &L; |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 285 | const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); |
| 286 | while (!Vec->empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 287 | // The current loop has multiple subloops in it hence it is not tightly |
| 288 | // nested. |
| 289 | // Discard all loops above it added into Worklist. |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 290 | if (Vec->size() != 1) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 291 | LoopList.clear(); |
| 292 | return; |
| 293 | } |
| 294 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 295 | CurrentLoop = Vec->front(); |
| 296 | Vec = &CurrentLoop->getSubLoops(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 297 | } |
| 298 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 299 | V.push_back(std::move(LoopList)); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 300 | } |
| 301 | |
| 302 | static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { |
| 303 | PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); |
| 304 | if (InnerIndexVar) |
| 305 | return InnerIndexVar; |
| 306 | if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) |
| 307 | return nullptr; |
| 308 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 309 | PHINode *PhiVar = cast<PHINode>(I); |
| 310 | Type *PhiTy = PhiVar->getType(); |
| 311 | if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && |
| 312 | !PhiTy->isPointerTy()) |
| 313 | return nullptr; |
| 314 | const SCEVAddRecExpr *AddRec = |
| 315 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); |
| 316 | if (!AddRec || !AddRec->isAffine()) |
| 317 | continue; |
| 318 | const SCEV *Step = AddRec->getStepRecurrence(*SE); |
| 319 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); |
| 320 | if (!C) |
| 321 | continue; |
| 322 | // Found the induction variable. |
| 323 | // FIXME: Handle loops with more than one induction variable. Note that, |
| 324 | // currently, legality makes sure we have only one induction variable. |
| 325 | return PhiVar; |
| 326 | } |
| 327 | return nullptr; |
| 328 | } |
| 329 | |
| 330 | /// LoopInterchangeLegality checks if it is legal to interchange the loop. |
| 331 | class LoopInterchangeLegality { |
| 332 | public: |
| 333 | LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 334 | LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA) |
| 335 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
| 336 | PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 337 | |
| 338 | /// Check if the loops can be interchanged. |
| 339 | bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, |
| 340 | CharMatrix &DepMatrix); |
| 341 | /// Check if the loop structure is understood. We do not handle triangular |
| 342 | /// loops for now. |
| 343 | bool isLoopStructureUnderstood(PHINode *InnerInductionVar); |
| 344 | |
| 345 | bool currentLimitations(); |
| 346 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 347 | bool hasInnerLoopReduction() { return InnerLoopHasReduction; } |
| 348 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 349 | private: |
| 350 | bool tightlyNested(Loop *Outer, Loop *Inner); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 351 | bool containsUnsafeInstructionsInHeader(BasicBlock *BB); |
| 352 | bool areAllUsesReductions(Instruction *Ins, Loop *L); |
| 353 | bool containsUnsafeInstructionsInLatch(BasicBlock *BB); |
| 354 | bool findInductionAndReductions(Loop *L, |
| 355 | SmallVector<PHINode *, 8> &Inductions, |
| 356 | SmallVector<PHINode *, 8> &Reductions); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 357 | Loop *OuterLoop; |
| 358 | Loop *InnerLoop; |
| 359 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 360 | ScalarEvolution *SE; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 361 | LoopInfo *LI; |
| 362 | DominatorTree *DT; |
| 363 | bool PreserveLCSSA; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 364 | |
| 365 | bool InnerLoopHasReduction; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 366 | }; |
| 367 | |
| 368 | /// LoopInterchangeProfitability checks if it is profitable to interchange the |
| 369 | /// loop. |
| 370 | class LoopInterchangeProfitability { |
| 371 | public: |
| 372 | LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE) |
| 373 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {} |
| 374 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 375 | /// Check if the loop interchange is profitable. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 376 | bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, |
| 377 | CharMatrix &DepMatrix); |
| 378 | |
| 379 | private: |
| 380 | int getInstrOrderCost(); |
| 381 | |
| 382 | Loop *OuterLoop; |
| 383 | Loop *InnerLoop; |
| 384 | |
| 385 | /// Scev analysis. |
| 386 | ScalarEvolution *SE; |
| 387 | }; |
| 388 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 389 | /// LoopInterchangeTransform interchanges the loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 390 | class LoopInterchangeTransform { |
| 391 | public: |
| 392 | LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 393 | LoopInfo *LI, DominatorTree *DT, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 394 | BasicBlock *LoopNestExit, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 395 | bool InnerLoopContainsReductions) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 396 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 397 | LoopExit(LoopNestExit), |
| 398 | InnerLoopHasReduction(InnerLoopContainsReductions) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 399 | |
| 400 | /// Interchange OuterLoop and InnerLoop. |
| 401 | bool transform(); |
| 402 | void restructureLoops(Loop *InnerLoop, Loop *OuterLoop); |
| 403 | void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 404 | |
| 405 | private: |
| 406 | void splitInnerLoopLatch(Instruction *); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 407 | void splitInnerLoopHeader(); |
| 408 | bool adjustLoopLinks(); |
| 409 | void adjustLoopPreheaders(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 410 | bool adjustLoopBranches(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 411 | void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, |
| 412 | BasicBlock *NewPred); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 413 | |
| 414 | Loop *OuterLoop; |
| 415 | Loop *InnerLoop; |
| 416 | |
| 417 | /// Scev analysis. |
| 418 | ScalarEvolution *SE; |
| 419 | LoopInfo *LI; |
| 420 | DominatorTree *DT; |
| 421 | BasicBlock *LoopExit; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 422 | bool InnerLoopHasReduction; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 423 | }; |
| 424 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 425 | // Main LoopInterchange Pass. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 426 | struct LoopInterchange : public FunctionPass { |
| 427 | static char ID; |
| 428 | ScalarEvolution *SE; |
| 429 | LoopInfo *LI; |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 430 | DependenceInfo *DI; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 431 | DominatorTree *DT; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 432 | bool PreserveLCSSA; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 433 | LoopInterchange() |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 434 | : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 435 | initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); |
| 436 | } |
| 437 | |
| 438 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 439 | AU.addRequired<ScalarEvolutionWrapperPass>(); |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 440 | AU.addRequired<AAResultsWrapperPass>(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 441 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 442 | AU.addRequired<LoopInfoWrapperPass>(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 443 | AU.addRequired<DependenceAnalysisWrapperPass>(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 444 | AU.addRequiredID(LoopSimplifyID); |
| 445 | AU.addRequiredID(LCSSAID); |
| 446 | } |
| 447 | |
| 448 | bool runOnFunction(Function &F) override { |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 449 | if (skipFunction(F)) |
| 450 | return false; |
| 451 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 452 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 453 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 454 | DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 455 | auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
| 456 | DT = DTWP ? &DTWP->getDomTree() : nullptr; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 457 | PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); |
| 458 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 459 | // Build up a worklist of loop pairs to analyze. |
| 460 | SmallVector<LoopVector, 8> Worklist; |
| 461 | |
| 462 | for (Loop *L : *LI) |
| 463 | populateWorklist(*L, Worklist); |
| 464 | |
Chad Rosier | a4c4246 | 2016-09-12 13:24:47 +0000 | [diff] [blame] | 465 | DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 466 | bool Changed = true; |
| 467 | while (!Worklist.empty()) { |
| 468 | LoopVector LoopList = Worklist.pop_back_val(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 469 | Changed = processLoopList(LoopList, F); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 470 | } |
| 471 | return Changed; |
| 472 | } |
| 473 | |
| 474 | bool isComputableLoopNest(LoopVector LoopList) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 475 | for (Loop *L : LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 476 | const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); |
| 477 | if (ExitCountOuter == SE->getCouldNotCompute()) { |
| 478 | DEBUG(dbgs() << "Couldn't compute Backedge count\n"); |
| 479 | return false; |
| 480 | } |
| 481 | if (L->getNumBackEdges() != 1) { |
| 482 | DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); |
| 483 | return false; |
| 484 | } |
| 485 | if (!L->getExitingBlock()) { |
| 486 | DEBUG(dbgs() << "Loop Doesn't have unique exit block\n"); |
| 487 | return false; |
| 488 | } |
| 489 | } |
| 490 | return true; |
| 491 | } |
| 492 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 493 | unsigned selectLoopForInterchange(const LoopVector &LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 494 | // TODO: Add a better heuristic to select the loop to be interchanged based |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 495 | // on the dependence matrix. Currently we select the innermost loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 496 | return LoopList.size() - 1; |
| 497 | } |
| 498 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 499 | bool processLoopList(LoopVector LoopList, Function &F) { |
| 500 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 501 | bool Changed = false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 502 | CharMatrix DependencyMatrix; |
| 503 | if (LoopList.size() < 2) { |
| 504 | DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); |
| 505 | return false; |
| 506 | } |
| 507 | if (!isComputableLoopNest(LoopList)) { |
Chad Rosier | a4c4246 | 2016-09-12 13:24:47 +0000 | [diff] [blame] | 508 | DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 509 | return false; |
| 510 | } |
| 511 | Loop *OuterMostLoop = *(LoopList.begin()); |
| 512 | |
| 513 | DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size() |
| 514 | << "\n"); |
| 515 | |
| 516 | if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(), |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 517 | OuterMostLoop, DI)) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 518 | DEBUG(dbgs() << "Populating Dependency matrix failed\n"); |
| 519 | return false; |
| 520 | } |
| 521 | #ifdef DUMP_DEP_MATRICIES |
| 522 | DEBUG(dbgs() << "Dependence before inter change \n"); |
| 523 | printDepMatrix(DependencyMatrix); |
| 524 | #endif |
| 525 | |
| 526 | BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch(); |
| 527 | BranchInst *OuterMostLoopLatchBI = |
| 528 | dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator()); |
| 529 | if (!OuterMostLoopLatchBI) |
| 530 | return false; |
| 531 | |
| 532 | // Since we currently do not handle LCSSA PHI's any failure in loop |
| 533 | // condition will now branch to LoopNestExit. |
| 534 | // TODO: This should be removed once we handle LCSSA PHI nodes. |
| 535 | |
| 536 | // Get the Outermost loop exit. |
| 537 | BasicBlock *LoopNestExit; |
| 538 | if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader()) |
| 539 | LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1); |
| 540 | else |
| 541 | LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0); |
| 542 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 543 | if (isa<PHINode>(LoopNestExit->begin())) { |
| 544 | DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now " |
| 545 | "since on failure all loops branch to loop nest exit.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 546 | return false; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 547 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 548 | |
| 549 | unsigned SelecLoopId = selectLoopForInterchange(LoopList); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 550 | // Move the selected loop outwards to the best possible position. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 551 | for (unsigned i = SelecLoopId; i > 0; i--) { |
| 552 | bool Interchanged = |
| 553 | processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); |
| 554 | if (!Interchanged) |
| 555 | return Changed; |
| 556 | // Loops interchanged reflect the same in LoopList |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 557 | std::swap(LoopList[i - 1], LoopList[i]); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 558 | |
| 559 | // Update the DependencyMatrix |
| 560 | interChangeDepedencies(DependencyMatrix, i, i - 1); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 561 | DT->recalculate(F); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 562 | #ifdef DUMP_DEP_MATRICIES |
| 563 | DEBUG(dbgs() << "Dependence after inter change \n"); |
| 564 | printDepMatrix(DependencyMatrix); |
| 565 | #endif |
| 566 | Changed |= Interchanged; |
| 567 | } |
| 568 | return Changed; |
| 569 | } |
| 570 | |
| 571 | bool processLoop(LoopVector LoopList, unsigned InnerLoopId, |
| 572 | unsigned OuterLoopId, BasicBlock *LoopNestExit, |
| 573 | std::vector<std::vector<char>> &DependencyMatrix) { |
| 574 | |
Chad Rosier | 13bc0d19 | 2016-09-07 18:15:12 +0000 | [diff] [blame] | 575 | DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 576 | << " and OuterLoopId = " << OuterLoopId << "\n"); |
| 577 | Loop *InnerLoop = LoopList[InnerLoopId]; |
| 578 | Loop *OuterLoop = LoopList[OuterLoopId]; |
| 579 | |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 580 | LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, |
| 581 | PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 582 | if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
| 583 | DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n"); |
| 584 | return false; |
| 585 | } |
| 586 | DEBUG(dbgs() << "Loops are legal to interchange\n"); |
| 587 | LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE); |
| 588 | if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
| 589 | DEBUG(dbgs() << "Interchanging Loops not profitable\n"); |
| 590 | return false; |
| 591 | } |
| 592 | |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 593 | LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 594 | LoopNestExit, LIL.hasInnerLoopReduction()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 595 | LIT.transform(); |
| 596 | DEBUG(dbgs() << "Loops interchanged\n"); |
| 597 | return true; |
| 598 | } |
| 599 | }; |
| 600 | |
| 601 | } // end of namespace |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 602 | bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { |
David Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 603 | return none_of(Ins->users(), [=](User *U) -> bool { |
| 604 | auto *UserIns = dyn_cast<PHINode>(U); |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 605 | RecurrenceDescriptor RD; |
| 606 | return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 607 | }); |
| 608 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 609 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 610 | bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( |
| 611 | BasicBlock *BB) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 612 | for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 613 | // Load corresponding to reduction PHI's are safe while concluding if |
| 614 | // tightly nested. |
| 615 | if (LoadInst *L = dyn_cast<LoadInst>(I)) { |
| 616 | if (!areAllUsesReductions(L, InnerLoop)) |
| 617 | return true; |
| 618 | } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) |
| 619 | return true; |
| 620 | } |
| 621 | return false; |
| 622 | } |
| 623 | |
| 624 | bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( |
| 625 | BasicBlock *BB) { |
| 626 | for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 627 | // Stores corresponding to reductions are safe while concluding if tightly |
| 628 | // nested. |
| 629 | if (StoreInst *L = dyn_cast<StoreInst>(I)) { |
| 630 | PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0)); |
| 631 | if (!PHI) |
| 632 | return true; |
| 633 | } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 634 | return true; |
| 635 | } |
| 636 | return false; |
| 637 | } |
| 638 | |
| 639 | bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { |
| 640 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 641 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 642 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 643 | |
| 644 | DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n"); |
| 645 | |
| 646 | // A perfectly nested loop will not have any branch in between the outer and |
| 647 | // inner block i.e. outer header will branch to either inner preheader and |
| 648 | // outerloop latch. |
| 649 | BranchInst *outerLoopHeaderBI = |
| 650 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 651 | if (!outerLoopHeaderBI) |
| 652 | return false; |
| 653 | unsigned num = outerLoopHeaderBI->getNumSuccessors(); |
| 654 | for (unsigned i = 0; i < num; i++) { |
| 655 | if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader && |
| 656 | outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch) |
| 657 | return false; |
| 658 | } |
| 659 | |
| 660 | DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n"); |
| 661 | // We do not have any basic block in between now make sure the outer header |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 662 | // and outer loop latch doesn't contain any unsafe instructions. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 663 | if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || |
| 664 | containsUnsafeInstructionsInLatch(OuterLoopLatch)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 665 | return false; |
| 666 | |
| 667 | DEBUG(dbgs() << "Loops are perfectly nested \n"); |
| 668 | // We have a perfect loop nest. |
| 669 | return true; |
| 670 | } |
| 671 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 672 | |
| 673 | bool LoopInterchangeLegality::isLoopStructureUnderstood( |
| 674 | PHINode *InnerInduction) { |
| 675 | |
| 676 | unsigned Num = InnerInduction->getNumOperands(); |
| 677 | BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); |
| 678 | for (unsigned i = 0; i < Num; ++i) { |
| 679 | Value *Val = InnerInduction->getOperand(i); |
| 680 | if (isa<Constant>(Val)) |
| 681 | continue; |
| 682 | Instruction *I = dyn_cast<Instruction>(Val); |
| 683 | if (!I) |
| 684 | return false; |
| 685 | // TODO: Handle triangular loops. |
| 686 | // e.g. for(int i=0;i<N;i++) |
| 687 | // for(int j=i;j<N;j++) |
| 688 | unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); |
| 689 | if (InnerInduction->getIncomingBlock(IncomBlockIndx) == |
| 690 | InnerLoopPreheader && |
| 691 | !OuterLoop->isLoopInvariant(I)) { |
| 692 | return false; |
| 693 | } |
| 694 | } |
| 695 | return true; |
| 696 | } |
| 697 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 698 | bool LoopInterchangeLegality::findInductionAndReductions( |
| 699 | Loop *L, SmallVector<PHINode *, 8> &Inductions, |
| 700 | SmallVector<PHINode *, 8> &Reductions) { |
| 701 | if (!L->getLoopLatch() || !L->getLoopPredecessor()) |
| 702 | return false; |
| 703 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 704 | RecurrenceDescriptor RD; |
James Molloy | 1bbf15c | 2015-08-27 09:53:00 +0000 | [diff] [blame] | 705 | InductionDescriptor ID; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 706 | PHINode *PHI = cast<PHINode>(I); |
Elena Demikhovsky | 376a18b | 2016-07-24 07:24:54 +0000 | [diff] [blame] | 707 | if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID)) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 708 | Inductions.push_back(PHI); |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 709 | else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 710 | Reductions.push_back(PHI); |
| 711 | else { |
| 712 | DEBUG( |
| 713 | dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); |
| 714 | return false; |
| 715 | } |
| 716 | } |
| 717 | return true; |
| 718 | } |
| 719 | |
| 720 | static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { |
| 721 | for (auto I = Block->begin(); isa<PHINode>(I); ++I) { |
| 722 | PHINode *PHI = cast<PHINode>(I); |
| 723 | // Reduction lcssa phi will have only 1 incoming block that from loop latch. |
| 724 | if (PHI->getNumIncomingValues() > 1) |
| 725 | return false; |
| 726 | Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); |
| 727 | if (!Ins) |
| 728 | return false; |
| 729 | // Incoming value for lcssa phi's in outer loop exit can only be inner loop |
| 730 | // exits lcssa phi else it would not be tightly nested. |
| 731 | if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) |
| 732 | return false; |
| 733 | } |
| 734 | return true; |
| 735 | } |
| 736 | |
| 737 | static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock, |
| 738 | BasicBlock *LoopHeader) { |
| 739 | if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) { |
| 740 | unsigned Num = BI->getNumSuccessors(); |
| 741 | assert(Num == 2); |
| 742 | for (unsigned i = 0; i < Num; ++i) { |
| 743 | if (BI->getSuccessor(i) == LoopHeader) |
| 744 | continue; |
| 745 | return BI->getSuccessor(i); |
| 746 | } |
| 747 | } |
| 748 | return nullptr; |
| 749 | } |
| 750 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 751 | // This function indicates the current limitations in the transform as a result |
| 752 | // of which we do not proceed. |
| 753 | bool LoopInterchangeLegality::currentLimitations() { |
| 754 | |
| 755 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 756 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 757 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 758 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 759 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 760 | |
| 761 | PHINode *InnerInductionVar; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 762 | SmallVector<PHINode *, 8> Inductions; |
| 763 | SmallVector<PHINode *, 8> Reductions; |
| 764 | if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 765 | return true; |
| 766 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 767 | // TODO: Currently we handle only loops with 1 induction variable. |
| 768 | if (Inductions.size() != 1) { |
| 769 | DEBUG(dbgs() << "We currently only support loops with 1 induction variable." |
| 770 | << "Failed to interchange due to current limitation\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 771 | return true; |
| 772 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 773 | if (Reductions.size() > 0) |
| 774 | InnerLoopHasReduction = true; |
| 775 | |
| 776 | InnerInductionVar = Inductions.pop_back_val(); |
| 777 | Reductions.clear(); |
| 778 | if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) |
| 779 | return true; |
| 780 | |
| 781 | // Outer loop cannot have reduction because then loops will not be tightly |
| 782 | // nested. |
| 783 | if (!Reductions.empty()) |
| 784 | return true; |
| 785 | // TODO: Currently we handle only loops with 1 induction variable. |
| 786 | if (Inductions.size() != 1) |
| 787 | return true; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 788 | |
| 789 | // TODO: Triangular loops are not handled for now. |
| 790 | if (!isLoopStructureUnderstood(InnerInductionVar)) { |
| 791 | DEBUG(dbgs() << "Loop structure not understood by pass\n"); |
| 792 | return true; |
| 793 | } |
| 794 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 795 | // TODO: We only handle LCSSA PHI's corresponding to reduction for now. |
| 796 | BasicBlock *LoopExitBlock = |
| 797 | getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader); |
| 798 | if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 799 | return true; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 800 | |
| 801 | LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader); |
| 802 | if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 803 | return true; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 804 | |
| 805 | // TODO: Current limitation: Since we split the inner loop latch at the point |
| 806 | // were induction variable is incremented (induction.next); We cannot have |
| 807 | // more than 1 user of induction.next since it would result in broken code |
| 808 | // after split. |
| 809 | // e.g. |
| 810 | // for(i=0;i<N;i++) { |
| 811 | // for(j = 0;j<M;j++) { |
| 812 | // A[j+1][i+2] = A[j][i]+k; |
| 813 | // } |
| 814 | // } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 815 | Instruction *InnerIndexVarInc = nullptr; |
| 816 | if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) |
| 817 | InnerIndexVarInc = |
| 818 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); |
| 819 | else |
| 820 | InnerIndexVarInc = |
| 821 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); |
| 822 | |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 823 | if (!InnerIndexVarInc) |
| 824 | return true; |
| 825 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 826 | // Since we split the inner loop latch on this induction variable. Make sure |
| 827 | // we do not have any instruction between the induction variable and branch |
| 828 | // instruction. |
| 829 | |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 830 | bool FoundInduction = false; |
| 831 | for (const Instruction &I : reverse(*InnerLoopLatch)) { |
| 832 | if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 833 | continue; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 834 | // We found an instruction. If this is not induction variable then it is not |
| 835 | // safe to split this loop latch. |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 836 | if (!I.isIdenticalTo(InnerIndexVarInc)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 837 | return true; |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 838 | |
| 839 | FoundInduction = true; |
| 840 | break; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 841 | } |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 842 | // The loop latch ended and we didn't find the induction variable return as |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 843 | // current limitation. |
| 844 | if (!FoundInduction) |
| 845 | return true; |
| 846 | |
| 847 | return false; |
| 848 | } |
| 849 | |
| 850 | bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, |
| 851 | unsigned OuterLoopId, |
| 852 | CharMatrix &DepMatrix) { |
| 853 | |
| 854 | if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { |
| 855 | DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId |
| 856 | << "and OuterLoopId = " << OuterLoopId |
| 857 | << "due to dependence\n"); |
| 858 | return false; |
| 859 | } |
| 860 | |
| 861 | // Create unique Preheaders if we already do not have one. |
| 862 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 863 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 864 | |
| 865 | // Create a unique outer preheader - |
| 866 | // 1) If OuterLoop preheader is not present. |
| 867 | // 2) If OuterLoop Preheader is same as OuterLoop Header |
| 868 | // 3) If OuterLoop Preheader is same as Header of the previous loop. |
| 869 | // 4) If OuterLoop Preheader is Entry node. |
| 870 | if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || |
| 871 | isa<PHINode>(OuterLoopPreHeader->begin()) || |
| 872 | !OuterLoopPreHeader->getUniquePredecessor()) { |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 873 | OuterLoopPreHeader = |
| 874 | InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 875 | } |
| 876 | |
| 877 | if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || |
| 878 | InnerLoopPreHeader == OuterLoop->getHeader()) { |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 879 | InnerLoopPreHeader = |
| 880 | InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 881 | } |
| 882 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 883 | // TODO: The loops could not be interchanged due to current limitations in the |
| 884 | // transform module. |
| 885 | if (currentLimitations()) { |
| 886 | DEBUG(dbgs() << "Not legal because of current transform limitation\n"); |
| 887 | return false; |
| 888 | } |
| 889 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 890 | // Check if the loops are tightly nested. |
| 891 | if (!tightlyNested(OuterLoop, InnerLoop)) { |
| 892 | DEBUG(dbgs() << "Loops not tightly nested\n"); |
| 893 | return false; |
| 894 | } |
| 895 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 896 | return true; |
| 897 | } |
| 898 | |
| 899 | int LoopInterchangeProfitability::getInstrOrderCost() { |
| 900 | unsigned GoodOrder, BadOrder; |
| 901 | BadOrder = GoodOrder = 0; |
| 902 | for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end(); |
| 903 | BI != BE; ++BI) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 904 | for (Instruction &Ins : **BI) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 905 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { |
| 906 | unsigned NumOp = GEP->getNumOperands(); |
| 907 | bool FoundInnerInduction = false; |
| 908 | bool FoundOuterInduction = false; |
| 909 | for (unsigned i = 0; i < NumOp; ++i) { |
| 910 | const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); |
| 911 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); |
| 912 | if (!AR) |
| 913 | continue; |
| 914 | |
| 915 | // If we find the inner induction after an outer induction e.g. |
| 916 | // for(int i=0;i<N;i++) |
| 917 | // for(int j=0;j<N;j++) |
| 918 | // A[i][j] = A[i-1][j-1]+k; |
| 919 | // then it is a good order. |
| 920 | if (AR->getLoop() == InnerLoop) { |
| 921 | // We found an InnerLoop induction after OuterLoop induction. It is |
| 922 | // a good order. |
| 923 | FoundInnerInduction = true; |
| 924 | if (FoundOuterInduction) { |
| 925 | GoodOrder++; |
| 926 | break; |
| 927 | } |
| 928 | } |
| 929 | // If we find the outer induction after an inner induction e.g. |
| 930 | // for(int i=0;i<N;i++) |
| 931 | // for(int j=0;j<N;j++) |
| 932 | // A[j][i] = A[j-1][i-1]+k; |
| 933 | // then it is a bad order. |
| 934 | if (AR->getLoop() == OuterLoop) { |
| 935 | // We found an OuterLoop induction after InnerLoop induction. It is |
| 936 | // a bad order. |
| 937 | FoundOuterInduction = true; |
| 938 | if (FoundInnerInduction) { |
| 939 | BadOrder++; |
| 940 | break; |
| 941 | } |
| 942 | } |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | } |
| 947 | return GoodOrder - BadOrder; |
| 948 | } |
| 949 | |
Benjamin Kramer | f044d3f | 2015-03-09 16:23:46 +0000 | [diff] [blame] | 950 | static bool isProfitabileForVectorization(unsigned InnerLoopId, |
| 951 | unsigned OuterLoopId, |
| 952 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 953 | // TODO: Improve this heuristic to catch more cases. |
| 954 | // If the inner loop is loop independent or doesn't carry any dependency it is |
| 955 | // profitable to move this to outer position. |
| 956 | unsigned Row = DepMatrix.size(); |
| 957 | for (unsigned i = 0; i < Row; ++i) { |
| 958 | if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I') |
| 959 | return false; |
| 960 | // TODO: We need to improve this heuristic. |
| 961 | if (DepMatrix[i][OuterLoopId] != '=') |
| 962 | return false; |
| 963 | } |
| 964 | // If outer loop has dependence and inner loop is loop independent then it is |
| 965 | // profitable to interchange to enable parallelism. |
| 966 | return true; |
| 967 | } |
| 968 | |
| 969 | bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, |
| 970 | unsigned OuterLoopId, |
| 971 | CharMatrix &DepMatrix) { |
| 972 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 973 | // TODO: Add better profitability checks. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 974 | // e.g |
| 975 | // 1) Construct dependency matrix and move the one with no loop carried dep |
| 976 | // inside to enable vectorization. |
| 977 | |
| 978 | // This is rough cost estimation algorithm. It counts the good and bad order |
| 979 | // of induction variables in the instruction and allows reordering if number |
| 980 | // of bad orders is more than good. |
| 981 | int Cost = 0; |
| 982 | Cost += getInstrOrderCost(); |
| 983 | DEBUG(dbgs() << "Cost = " << Cost << "\n"); |
| 984 | if (Cost < 0) |
| 985 | return true; |
| 986 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 987 | // It is not profitable as per current cache profitability model. But check if |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 988 | // we can move this loop outside to improve parallelism. |
| 989 | bool ImprovesPar = |
| 990 | isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix); |
| 991 | return ImprovesPar; |
| 992 | } |
| 993 | |
| 994 | void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, |
| 995 | Loop *InnerLoop) { |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 996 | for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; |
| 997 | ++I) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 998 | if (*I == InnerLoop) { |
| 999 | OuterLoop->removeChildLoop(I); |
| 1000 | return; |
| 1001 | } |
| 1002 | } |
Benjamin Kramer | 8ceb323 | 2015-10-25 22:28:27 +0000 | [diff] [blame] | 1003 | llvm_unreachable("Couldn't find loop"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1004 | } |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 1005 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1006 | void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop, |
| 1007 | Loop *OuterLoop) { |
| 1008 | Loop *OuterLoopParent = OuterLoop->getParentLoop(); |
| 1009 | if (OuterLoopParent) { |
| 1010 | // Remove the loop from its parent loop. |
| 1011 | removeChildLoop(OuterLoopParent, OuterLoop); |
| 1012 | removeChildLoop(OuterLoop, InnerLoop); |
| 1013 | OuterLoopParent->addChildLoop(InnerLoop); |
| 1014 | } else { |
| 1015 | removeChildLoop(OuterLoop, InnerLoop); |
| 1016 | LI->changeTopLevelLoop(OuterLoop, InnerLoop); |
| 1017 | } |
| 1018 | |
Andrew Kaylor | 08c5f1e | 2015-04-24 17:39:16 +0000 | [diff] [blame] | 1019 | while (!InnerLoop->empty()) |
| 1020 | OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin())); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1021 | |
| 1022 | InnerLoop->addChildLoop(OuterLoop); |
| 1023 | } |
| 1024 | |
| 1025 | bool LoopInterchangeTransform::transform() { |
| 1026 | |
| 1027 | DEBUG(dbgs() << "transform\n"); |
| 1028 | bool Transformed = false; |
| 1029 | Instruction *InnerIndexVar; |
| 1030 | |
| 1031 | if (InnerLoop->getSubLoops().size() == 0) { |
| 1032 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1033 | DEBUG(dbgs() << "Calling Split Inner Loop\n"); |
| 1034 | PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); |
| 1035 | if (!InductionPHI) { |
| 1036 | DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); |
| 1037 | return false; |
| 1038 | } |
| 1039 | |
| 1040 | if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) |
| 1041 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); |
| 1042 | else |
| 1043 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); |
| 1044 | |
| 1045 | // |
| 1046 | // Split at the place were the induction variable is |
| 1047 | // incremented/decremented. |
| 1048 | // TODO: This splitting logic may not work always. Fix this. |
| 1049 | splitInnerLoopLatch(InnerIndexVar); |
| 1050 | DEBUG(dbgs() << "splitInnerLoopLatch Done\n"); |
| 1051 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1052 | // Splits the inner loops phi nodes out into a separate basic block. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1053 | splitInnerLoopHeader(); |
| 1054 | DEBUG(dbgs() << "splitInnerLoopHeader Done\n"); |
| 1055 | } |
| 1056 | |
| 1057 | Transformed |= adjustLoopLinks(); |
| 1058 | if (!Transformed) { |
| 1059 | DEBUG(dbgs() << "adjustLoopLinks Failed\n"); |
| 1060 | return false; |
| 1061 | } |
| 1062 | |
| 1063 | restructureLoops(InnerLoop, OuterLoop); |
| 1064 | return true; |
| 1065 | } |
| 1066 | |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1067 | void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1068 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1069 | BasicBlock *InnerLoopLatchPred = InnerLoopLatch; |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1070 | InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1071 | } |
| 1072 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1073 | void LoopInterchangeTransform::splitInnerLoopHeader() { |
| 1074 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1075 | // Split the inner loop header out. Here make sure that the reduction PHI's |
| 1076 | // stay in the innerloop body. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1077 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1078 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1079 | if (InnerLoopHasReduction) { |
| 1080 | // FIXME: Check if the induction PHI will always be the first PHI. |
| 1081 | BasicBlock *New = InnerLoopHeader->splitBasicBlock( |
| 1082 | ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split"); |
| 1083 | if (LI) |
| 1084 | if (Loop *L = LI->getLoopFor(InnerLoopHeader)) |
| 1085 | L->addBasicBlockToLoop(New, *LI); |
| 1086 | |
| 1087 | // Adjust Reduction PHI's in the block. |
| 1088 | SmallVector<PHINode *, 8> PHIVec; |
| 1089 | for (auto I = New->begin(); isa<PHINode>(I); ++I) { |
| 1090 | PHINode *PHI = dyn_cast<PHINode>(I); |
| 1091 | Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); |
| 1092 | PHI->replaceAllUsesWith(V); |
| 1093 | PHIVec.push_back((PHI)); |
| 1094 | } |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1095 | for (PHINode *P : PHIVec) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1096 | P->eraseFromParent(); |
| 1097 | } |
| 1098 | } else { |
| 1099 | SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); |
| 1100 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1101 | |
| 1102 | DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " |
| 1103 | "InnerLoopHeader \n"); |
| 1104 | } |
| 1105 | |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1106 | /// \brief Move all instructions except the terminator from FromBB right before |
| 1107 | /// InsertBefore |
| 1108 | static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { |
| 1109 | auto &ToList = InsertBefore->getParent()->getInstList(); |
| 1110 | auto &FromList = FromBB->getInstList(); |
| 1111 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1112 | ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), |
| 1113 | FromBB->getTerminator()->getIterator()); |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1114 | } |
| 1115 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1116 | void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, |
| 1117 | BasicBlock *OldPred, |
| 1118 | BasicBlock *NewPred) { |
| 1119 | for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { |
| 1120 | PHINode *PHI = cast<PHINode>(I); |
| 1121 | unsigned Num = PHI->getNumIncomingValues(); |
| 1122 | for (unsigned i = 0; i < Num; ++i) { |
| 1123 | if (PHI->getIncomingBlock(i) == OldPred) |
| 1124 | PHI->setIncomingBlock(i, NewPred); |
| 1125 | } |
| 1126 | } |
| 1127 | } |
| 1128 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1129 | bool LoopInterchangeTransform::adjustLoopBranches() { |
| 1130 | |
| 1131 | DEBUG(dbgs() << "adjustLoopBranches called\n"); |
| 1132 | // Adjust the loop preheader |
| 1133 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1134 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1135 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 1136 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 1137 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1138 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1139 | BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); |
| 1140 | BasicBlock *InnerLoopLatchPredecessor = |
| 1141 | InnerLoopLatch->getUniquePredecessor(); |
| 1142 | BasicBlock *InnerLoopLatchSuccessor; |
| 1143 | BasicBlock *OuterLoopLatchSuccessor; |
| 1144 | |
| 1145 | BranchInst *OuterLoopLatchBI = |
| 1146 | dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); |
| 1147 | BranchInst *InnerLoopLatchBI = |
| 1148 | dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); |
| 1149 | BranchInst *OuterLoopHeaderBI = |
| 1150 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 1151 | BranchInst *InnerLoopHeaderBI = |
| 1152 | dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); |
| 1153 | |
| 1154 | if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || |
| 1155 | !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || |
| 1156 | !InnerLoopHeaderBI) |
| 1157 | return false; |
| 1158 | |
| 1159 | BranchInst *InnerLoopLatchPredecessorBI = |
| 1160 | dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); |
| 1161 | BranchInst *OuterLoopPredecessorBI = |
| 1162 | dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); |
| 1163 | |
| 1164 | if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) |
| 1165 | return false; |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1166 | BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); |
| 1167 | if (!InnerLoopHeaderSuccessor) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1168 | return false; |
| 1169 | |
| 1170 | // Adjust Loop Preheader and headers |
| 1171 | |
| 1172 | unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors(); |
| 1173 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1174 | if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader) |
| 1175 | OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader); |
| 1176 | } |
| 1177 | |
| 1178 | NumSucc = OuterLoopHeaderBI->getNumSuccessors(); |
| 1179 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1180 | if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch) |
| 1181 | OuterLoopHeaderBI->setSuccessor(i, LoopExit); |
| 1182 | else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1183 | OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1184 | } |
| 1185 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1186 | // Adjust reduction PHI's now that the incoming block has changed. |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1187 | updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1188 | OuterLoopHeader); |
| 1189 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1190 | BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI); |
| 1191 | InnerLoopHeaderBI->eraseFromParent(); |
| 1192 | |
| 1193 | // -------------Adjust loop latches----------- |
| 1194 | if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) |
| 1195 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); |
| 1196 | else |
| 1197 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); |
| 1198 | |
| 1199 | NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors(); |
| 1200 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1201 | if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch) |
| 1202 | InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor); |
| 1203 | } |
| 1204 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1205 | // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with |
| 1206 | // the value and remove this PHI node from inner loop. |
| 1207 | SmallVector<PHINode *, 8> LcssaVec; |
| 1208 | for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { |
| 1209 | PHINode *LcssaPhi = cast<PHINode>(I); |
| 1210 | LcssaVec.push_back(LcssaPhi); |
| 1211 | } |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1212 | for (PHINode *P : LcssaVec) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1213 | Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); |
| 1214 | P->replaceAllUsesWith(Incoming); |
| 1215 | P->eraseFromParent(); |
| 1216 | } |
| 1217 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1218 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) |
| 1219 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); |
| 1220 | else |
| 1221 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); |
| 1222 | |
| 1223 | if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor) |
| 1224 | InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor); |
| 1225 | else |
| 1226 | InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor); |
| 1227 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1228 | updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); |
| 1229 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1230 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) { |
| 1231 | OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch); |
| 1232 | } else { |
| 1233 | OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch); |
| 1234 | } |
| 1235 | |
| 1236 | return true; |
| 1237 | } |
| 1238 | void LoopInterchangeTransform::adjustLoopPreheaders() { |
| 1239 | |
| 1240 | // We have interchanged the preheaders so we need to interchange the data in |
| 1241 | // the preheader as well. |
| 1242 | // This is because the content of inner preheader was previously executed |
| 1243 | // inside the outer loop. |
| 1244 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1245 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1246 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1247 | BranchInst *InnerTermBI = |
| 1248 | cast<BranchInst>(InnerLoopPreHeader->getTerminator()); |
| 1249 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1250 | // These instructions should now be executed inside the loop. |
| 1251 | // Move instruction into a new block after outer header. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1252 | moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1253 | // These instructions were not executed previously in the loop so move them to |
| 1254 | // the older inner loop preheader. |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1255 | moveBBContents(OuterLoopPreHeader, InnerTermBI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1256 | } |
| 1257 | |
| 1258 | bool LoopInterchangeTransform::adjustLoopLinks() { |
| 1259 | |
| 1260 | // Adjust all branches in the inner and outer loop. |
| 1261 | bool Changed = adjustLoopBranches(); |
| 1262 | if (Changed) |
| 1263 | adjustLoopPreheaders(); |
| 1264 | return Changed; |
| 1265 | } |
| 1266 | |
| 1267 | char LoopInterchange::ID = 0; |
| 1268 | INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", |
| 1269 | "Interchanges loops for cache reuse", false, false) |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 1270 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 1271 | INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1272 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1273 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1274 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
Easwaran Raman | e12c487 | 2016-06-09 19:44:46 +0000 | [diff] [blame] | 1275 | INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1276 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 1277 | |
| 1278 | INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", |
| 1279 | "Interchanges loops for cache reuse", false, false) |
| 1280 | |
| 1281 | Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } |