Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1 | //===- LoopInterchange.cpp - Loop interchange pass-------------------------===// |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This Pass handles loop interchange transform. |
| 10 | // This pass interchanges loops to provide a more cache-friendly memory access |
| 11 | // patterns. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/STLExtras.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/SmallVector.h" |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/StringRef.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/DependenceAnalysis.h" |
| 20 | #include "llvm/Analysis/LoopInfo.h" |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/LoopPass.h" |
Adam Nemet | 0965da2 | 2017-10-09 23:19:02 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/ScalarEvolution.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 25 | #include "llvm/IR/BasicBlock.h" |
| 26 | #include "llvm/IR/Constants.h" |
| 27 | #include "llvm/IR/DiagnosticInfo.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Dominators.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Function.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 30 | #include "llvm/IR/InstrTypes.h" |
| 31 | #include "llvm/IR/Instruction.h" |
| 32 | #include "llvm/IR/Instructions.h" |
| 33 | #include "llvm/IR/Type.h" |
| 34 | #include "llvm/IR/User.h" |
| 35 | #include "llvm/IR/Value.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 36 | #include "llvm/Pass.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 37 | #include "llvm/Support/Casting.h" |
| 38 | #include "llvm/Support/CommandLine.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 40 | #include "llvm/Support/ErrorHandling.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 41 | #include "llvm/Support/raw_ostream.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Scalar.h" |
David Blaikie | a373d18 | 2018-03-28 17:44:36 +0000 | [diff] [blame] | 43 | #include "llvm/Transforms/Utils.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 46 | #include <cassert> |
| 47 | #include <utility> |
| 48 | #include <vector> |
Davide Italiano | 9d8f6f8 | 2017-01-29 01:55:24 +0000 | [diff] [blame] | 49 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 50 | using namespace llvm; |
| 51 | |
| 52 | #define DEBUG_TYPE "loop-interchange" |
| 53 | |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 54 | STATISTIC(LoopsInterchanged, "Number of loops interchanged"); |
| 55 | |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 56 | static cl::opt<int> LoopInterchangeCostThreshold( |
| 57 | "loop-interchange-threshold", cl::init(0), cl::Hidden, |
| 58 | cl::desc("Interchange if you gain more than this number")); |
| 59 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 60 | namespace { |
| 61 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 62 | using LoopVector = SmallVector<Loop *, 8>; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 63 | |
| 64 | // TODO: Check if we can use a sparse matrix here. |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 65 | using CharMatrix = std::vector<std::vector<char>>; |
| 66 | |
| 67 | } // end anonymous namespace |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 68 | |
| 69 | // Maximum number of dependencies that can be handled in the dependency matrix. |
| 70 | static const unsigned MaxMemInstrCount = 100; |
| 71 | |
| 72 | // Maximum loop depth supported. |
| 73 | static const unsigned MaxLoopNestDepth = 10; |
| 74 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 75 | #ifdef DUMP_DEP_MATRICIES |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 76 | static void printDepMatrix(CharMatrix &DepMatrix) { |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 77 | for (auto &Row : DepMatrix) { |
| 78 | for (auto D : Row) |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 79 | LLVM_DEBUG(dbgs() << D << " "); |
| 80 | LLVM_DEBUG(dbgs() << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 81 | } |
| 82 | } |
| 83 | #endif |
| 84 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 85 | static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 86 | Loop *L, DependenceInfo *DI) { |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 87 | using ValueVector = SmallVector<Value *, 16>; |
| 88 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 89 | ValueVector MemInstr; |
| 90 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 91 | // For each block. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 92 | for (BasicBlock *BB : L->blocks()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 93 | // Scan the BB and collect legal loads and stores. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 94 | for (Instruction &I : *BB) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 95 | if (!isa<Instruction>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 96 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 97 | if (auto *Ld = dyn_cast<LoadInst>(&I)) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 98 | if (!Ld->isSimple()) |
| 99 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 100 | MemInstr.push_back(&I); |
| 101 | } else if (auto *St = dyn_cast<StoreInst>(&I)) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 102 | if (!St->isSimple()) |
| 103 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 104 | MemInstr.push_back(&I); |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 105 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 106 | } |
| 107 | } |
| 108 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 109 | LLVM_DEBUG(dbgs() << "Found " << MemInstr.size() |
| 110 | << " Loads and Stores to analyze\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 111 | |
| 112 | ValueVector::iterator I, IE, J, JE; |
| 113 | |
| 114 | for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { |
| 115 | for (J = I, JE = MemInstr.end(); J != JE; ++J) { |
| 116 | std::vector<char> Dep; |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 117 | Instruction *Src = cast<Instruction>(*I); |
| 118 | Instruction *Dst = cast<Instruction>(*J); |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 119 | if (Src == Dst) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 120 | continue; |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 121 | // Ignore Input dependencies. |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 122 | if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 123 | continue; |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 124 | // Track Output, Flow, and Anti dependencies. |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 125 | if (auto D = DI->depends(Src, Dst, true)) { |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 126 | assert(D->isOrdered() && "Expected an output, flow or anti dep."); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 127 | LLVM_DEBUG(StringRef DepType = |
| 128 | D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; |
| 129 | dbgs() << "Found " << DepType |
| 130 | << " dependency between Src and Dst\n" |
| 131 | << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 132 | unsigned Levels = D->getLevels(); |
| 133 | char Direction; |
| 134 | for (unsigned II = 1; II <= Levels; ++II) { |
| 135 | const SCEV *Distance = D->getDistance(II); |
| 136 | const SCEVConstant *SCEVConst = |
| 137 | dyn_cast_or_null<SCEVConstant>(Distance); |
| 138 | if (SCEVConst) { |
| 139 | const ConstantInt *CI = SCEVConst->getValue(); |
| 140 | if (CI->isNegative()) |
| 141 | Direction = '<'; |
| 142 | else if (CI->isZero()) |
| 143 | Direction = '='; |
| 144 | else |
| 145 | Direction = '>'; |
| 146 | Dep.push_back(Direction); |
| 147 | } else if (D->isScalar(II)) { |
| 148 | Direction = 'S'; |
| 149 | Dep.push_back(Direction); |
| 150 | } else { |
| 151 | unsigned Dir = D->getDirection(II); |
| 152 | if (Dir == Dependence::DVEntry::LT || |
| 153 | Dir == Dependence::DVEntry::LE) |
| 154 | Direction = '<'; |
| 155 | else if (Dir == Dependence::DVEntry::GT || |
| 156 | Dir == Dependence::DVEntry::GE) |
| 157 | Direction = '>'; |
| 158 | else if (Dir == Dependence::DVEntry::EQ) |
| 159 | Direction = '='; |
| 160 | else |
| 161 | Direction = '*'; |
| 162 | Dep.push_back(Direction); |
| 163 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 164 | } |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 165 | while (Dep.size() != Level) { |
| 166 | Dep.push_back('I'); |
| 167 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 168 | |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 169 | DepMatrix.push_back(Dep); |
| 170 | if (DepMatrix.size() > MaxMemInstrCount) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 171 | LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount |
| 172 | << " dependencies inside loop\n"); |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 173 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 174 | } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 179 | return true; |
| 180 | } |
| 181 | |
| 182 | // A loop is moved from index 'from' to an index 'to'. Update the Dependence |
| 183 | // matrix by exchanging the two columns. |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 184 | static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, |
| 185 | unsigned ToIndx) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 186 | unsigned numRows = DepMatrix.size(); |
| 187 | for (unsigned i = 0; i < numRows; ++i) { |
| 188 | char TmpVal = DepMatrix[i][ToIndx]; |
| 189 | DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; |
| 190 | DepMatrix[i][FromIndx] = TmpVal; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is |
| 195 | // '>' |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 196 | static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, |
| 197 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 198 | for (unsigned i = 0; i <= Column; ++i) { |
| 199 | if (DepMatrix[Row][i] == '<') |
| 200 | return false; |
| 201 | if (DepMatrix[Row][i] == '>') |
| 202 | return true; |
| 203 | } |
| 204 | // All dependencies were '=','S' or 'I' |
| 205 | return false; |
| 206 | } |
| 207 | |
| 208 | // 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] | 209 | static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, |
| 210 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 211 | for (unsigned i = 0; i < Column; ++i) { |
Chandler Carruth | fca1ff0 | 2016-11-03 16:39:25 +0000 | [diff] [blame] | 212 | if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 213 | DepMatrix[Row][i] != 'I') |
| 214 | return false; |
| 215 | } |
| 216 | return true; |
| 217 | } |
| 218 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 219 | static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, |
| 220 | unsigned OuterLoopId, char InnerDep, |
| 221 | char OuterDep) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 222 | if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) |
| 223 | return false; |
| 224 | |
| 225 | if (InnerDep == OuterDep) |
| 226 | return true; |
| 227 | |
| 228 | // It is legal to interchange if and only if after interchange no row has a |
| 229 | // '>' direction as the leftmost non-'='. |
| 230 | |
| 231 | if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') |
| 232 | return true; |
| 233 | |
| 234 | if (InnerDep == '<') |
| 235 | return true; |
| 236 | |
| 237 | if (InnerDep == '>') { |
| 238 | // If OuterLoopId represents outermost loop then interchanging will make the |
| 239 | // 1st dependency as '>' |
| 240 | if (OuterLoopId == 0) |
| 241 | return false; |
| 242 | |
| 243 | // If all dependencies before OuterloopId are '=','S'or 'I'. Then |
| 244 | // interchanging will result in this row having an outermost non '=' |
| 245 | // dependency of '>' |
| 246 | if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) |
| 247 | return true; |
| 248 | } |
| 249 | |
| 250 | return false; |
| 251 | } |
| 252 | |
| 253 | // Checks if it is legal to interchange 2 loops. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 254 | // [Theorem] A permutation of the loops in a perfect nest is legal if and only |
Chad Rosier | 61683a2 | 2016-09-13 13:08:53 +0000 | [diff] [blame] | 255 | // if the direction matrix, after the same permutation is applied to its |
| 256 | // columns, has no ">" direction as the leftmost non-"=" direction in any row. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 257 | static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, |
| 258 | unsigned InnerLoopId, |
| 259 | unsigned OuterLoopId) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 260 | unsigned NumRows = DepMatrix.size(); |
| 261 | // For each row check if it is valid to interchange. |
| 262 | for (unsigned Row = 0; Row < NumRows; ++Row) { |
| 263 | char InnerDep = DepMatrix[Row][InnerLoopId]; |
| 264 | char OuterDep = DepMatrix[Row][OuterLoopId]; |
| 265 | if (InnerDep == '*' || OuterDep == '*') |
| 266 | return false; |
Chad Rosier | 61683a2 | 2016-09-13 13:08:53 +0000 | [diff] [blame] | 267 | if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 268 | return false; |
| 269 | } |
| 270 | return true; |
| 271 | } |
| 272 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 273 | static LoopVector populateWorklist(Loop &L) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 274 | LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: " |
| 275 | << L.getHeader()->getParent()->getName() << " Loop: %" |
| 276 | << L.getHeader()->getName() << '\n'); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 277 | LoopVector LoopList; |
| 278 | Loop *CurrentLoop = &L; |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 279 | const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); |
| 280 | while (!Vec->empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 281 | // The current loop has multiple subloops in it hence it is not tightly |
| 282 | // nested. |
| 283 | // Discard all loops above it added into Worklist. |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 284 | if (Vec->size() != 1) |
| 285 | return {}; |
| 286 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 287 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 288 | CurrentLoop = Vec->front(); |
| 289 | Vec = &CurrentLoop->getSubLoops(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 290 | } |
| 291 | LoopList.push_back(CurrentLoop); |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 292 | return LoopList; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 293 | } |
| 294 | |
Kit Barton | 987fdfd | 2019-05-23 20:53:05 +0000 | [diff] [blame] | 295 | static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { |
| 296 | PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); |
| 297 | if (InnerIndexVar) |
| 298 | return InnerIndexVar; |
| 299 | if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) |
| 300 | return nullptr; |
| 301 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 302 | PHINode *PhiVar = cast<PHINode>(I); |
| 303 | Type *PhiTy = PhiVar->getType(); |
| 304 | if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && |
| 305 | !PhiTy->isPointerTy()) |
| 306 | return nullptr; |
| 307 | const SCEVAddRecExpr *AddRec = |
| 308 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); |
| 309 | if (!AddRec || !AddRec->isAffine()) |
| 310 | continue; |
| 311 | const SCEV *Step = AddRec->getStepRecurrence(*SE); |
| 312 | if (!isa<SCEVConstant>(Step)) |
| 313 | continue; |
| 314 | // Found the induction variable. |
| 315 | // FIXME: Handle loops with more than one induction variable. Note that, |
| 316 | // currently, legality makes sure we have only one induction variable. |
| 317 | return PhiVar; |
| 318 | } |
| 319 | return nullptr; |
| 320 | } |
| 321 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 322 | namespace { |
| 323 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 324 | /// LoopInterchangeLegality checks if it is legal to interchange the loop. |
| 325 | class LoopInterchangeLegality { |
| 326 | public: |
| 327 | LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 328 | OptimizationRemarkEmitter *ORE) |
Florian Hahn | c51d088 | 2018-09-06 10:41:01 +0000 | [diff] [blame] | 329 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 330 | |
| 331 | /// Check if the loops can be interchanged. |
| 332 | bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, |
| 333 | CharMatrix &DepMatrix); |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 334 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 335 | /// Check if the loop structure is understood. We do not handle triangular |
| 336 | /// loops for now. |
| 337 | bool isLoopStructureUnderstood(PHINode *InnerInductionVar); |
| 338 | |
| 339 | bool currentLimitations(); |
| 340 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 341 | const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const { |
| 342 | return OuterInnerReductions; |
| 343 | } |
| 344 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 345 | private: |
| 346 | bool tightlyNested(Loop *Outer, Loop *Inner); |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 347 | bool containsUnsafeInstructions(BasicBlock *BB); |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 348 | |
| 349 | /// Discover induction and reduction PHIs in the header of \p L. Induction |
| 350 | /// PHIs are added to \p Inductions, reductions are added to |
| 351 | /// OuterInnerReductions. When the outer loop is passed, the inner loop needs |
| 352 | /// to be passed as \p InnerLoop. |
| 353 | bool findInductionAndReductions(Loop *L, |
| 354 | SmallVector<PHINode *, 8> &Inductions, |
| 355 | Loop *InnerLoop); |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 356 | |
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; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 361 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 362 | /// Interface to emit optimization remarks. |
| 363 | OptimizationRemarkEmitter *ORE; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 364 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 365 | /// Set of reduction PHIs taking part of a reduction across the inner and |
| 366 | /// outer loop. |
| 367 | SmallPtrSet<PHINode *, 4> OuterInnerReductions; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 368 | }; |
| 369 | |
| 370 | /// LoopInterchangeProfitability checks if it is profitable to interchange the |
| 371 | /// loop. |
| 372 | class LoopInterchangeProfitability { |
| 373 | public: |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 374 | LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 375 | OptimizationRemarkEmitter *ORE) |
| 376 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 377 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 378 | /// Check if the loop interchange is profitable. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 379 | bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, |
| 380 | CharMatrix &DepMatrix); |
| 381 | |
| 382 | private: |
| 383 | int getInstrOrderCost(); |
| 384 | |
| 385 | Loop *OuterLoop; |
| 386 | Loop *InnerLoop; |
| 387 | |
| 388 | /// Scev analysis. |
| 389 | ScalarEvolution *SE; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 390 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 391 | /// Interface to emit optimization remarks. |
| 392 | OptimizationRemarkEmitter *ORE; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 393 | }; |
| 394 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 395 | /// LoopInterchangeTransform interchanges the loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 396 | class LoopInterchangeTransform { |
| 397 | public: |
| 398 | LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 399 | LoopInfo *LI, DominatorTree *DT, |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 400 | BasicBlock *LoopNestExit, |
| 401 | const LoopInterchangeLegality &LIL) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 402 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 403 | LoopExit(LoopNestExit), LIL(LIL) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 404 | |
| 405 | /// Interchange OuterLoop and InnerLoop. |
| 406 | bool transform(); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 407 | void restructureLoops(Loop *NewInner, Loop *NewOuter, |
| 408 | BasicBlock *OrigInnerPreHeader, |
| 409 | BasicBlock *OrigOuterPreHeader); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 410 | void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 411 | |
| 412 | private: |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 413 | void splitInnerLoopHeader(); |
| 414 | bool adjustLoopLinks(); |
| 415 | void adjustLoopPreheaders(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 416 | bool adjustLoopBranches(); |
| 417 | |
| 418 | Loop *OuterLoop; |
| 419 | Loop *InnerLoop; |
| 420 | |
| 421 | /// Scev analysis. |
| 422 | ScalarEvolution *SE; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 423 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 424 | LoopInfo *LI; |
| 425 | DominatorTree *DT; |
| 426 | BasicBlock *LoopExit; |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 427 | |
| 428 | const LoopInterchangeLegality &LIL; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 429 | }; |
| 430 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 431 | // Main LoopInterchange Pass. |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 432 | struct LoopInterchange : public LoopPass { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 433 | static char ID; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 434 | ScalarEvolution *SE = nullptr; |
| 435 | LoopInfo *LI = nullptr; |
| 436 | DependenceInfo *DI = nullptr; |
| 437 | DominatorTree *DT = nullptr; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 438 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 439 | /// Interface to emit optimization remarks. |
| 440 | OptimizationRemarkEmitter *ORE; |
| 441 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 442 | LoopInterchange() : LoopPass(ID) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 443 | initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); |
| 444 | } |
| 445 | |
| 446 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 447 | AU.addRequired<DependenceAnalysisWrapperPass>(); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 448 | AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 449 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 450 | getLoopAnalysisUsage(AU); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 451 | } |
| 452 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 453 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 454 | if (skipLoop(L) || L->getParentLoop()) |
Florian Hahn | 8d72ecc | 2018-09-28 10:20:07 +0000 | [diff] [blame] | 455 | return false; |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 456 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 457 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 458 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 459 | DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 460 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 461 | ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 462 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 463 | return processLoopList(populateWorklist(*L)); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 464 | } |
| 465 | |
| 466 | bool isComputableLoopNest(LoopVector LoopList) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 467 | for (Loop *L : LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 468 | const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); |
| 469 | if (ExitCountOuter == SE->getCouldNotCompute()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 470 | LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 471 | return false; |
| 472 | } |
| 473 | if (L->getNumBackEdges() != 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 474 | LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 475 | return false; |
| 476 | } |
| 477 | if (!L->getExitingBlock()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 478 | LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 479 | return false; |
| 480 | } |
| 481 | } |
| 482 | return true; |
| 483 | } |
| 484 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 485 | unsigned selectLoopForInterchange(const LoopVector &LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 486 | // 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] | 487 | // on the dependence matrix. Currently we select the innermost loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 488 | return LoopList.size() - 1; |
| 489 | } |
| 490 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 491 | bool processLoopList(LoopVector LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 492 | bool Changed = false; |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 493 | unsigned LoopNestDepth = LoopList.size(); |
| 494 | if (LoopNestDepth < 2) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 495 | LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 496 | return false; |
| 497 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 498 | if (LoopNestDepth > MaxLoopNestDepth) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 499 | LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than " |
| 500 | << MaxLoopNestDepth << "\n"); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 501 | return false; |
| 502 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 503 | if (!isComputableLoopNest(LoopList)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 504 | LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 505 | return false; |
| 506 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 507 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 508 | LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth |
| 509 | << "\n"); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 510 | |
| 511 | CharMatrix DependencyMatrix; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 512 | Loop *OuterMostLoop = *(LoopList.begin()); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 513 | if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 514 | OuterMostLoop, DI)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 515 | LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 516 | return false; |
| 517 | } |
| 518 | #ifdef DUMP_DEP_MATRICIES |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 519 | LLVM_DEBUG(dbgs() << "Dependence before interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 520 | printDepMatrix(DependencyMatrix); |
| 521 | #endif |
| 522 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 523 | // Get the Outermost loop exit. |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 524 | BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); |
| 525 | if (!LoopNestExit) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 526 | LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 527 | return false; |
| 528 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 529 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 530 | unsigned SelecLoopId = selectLoopForInterchange(LoopList); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 531 | // Move the selected loop outwards to the best possible position. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 532 | for (unsigned i = SelecLoopId; i > 0; i--) { |
| 533 | bool Interchanged = |
| 534 | processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); |
| 535 | if (!Interchanged) |
| 536 | return Changed; |
| 537 | // Loops interchanged reflect the same in LoopList |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 538 | std::swap(LoopList[i - 1], LoopList[i]); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 539 | |
| 540 | // Update the DependencyMatrix |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 541 | interChangeDependencies(DependencyMatrix, i, i - 1); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 542 | #ifdef DUMP_DEP_MATRICIES |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 543 | LLVM_DEBUG(dbgs() << "Dependence after interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 544 | printDepMatrix(DependencyMatrix); |
| 545 | #endif |
| 546 | Changed |= Interchanged; |
| 547 | } |
| 548 | return Changed; |
| 549 | } |
| 550 | |
| 551 | bool processLoop(LoopVector LoopList, unsigned InnerLoopId, |
| 552 | unsigned OuterLoopId, BasicBlock *LoopNestExit, |
| 553 | std::vector<std::vector<char>> &DependencyMatrix) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 554 | LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId |
| 555 | << " and OuterLoopId = " << OuterLoopId << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 556 | Loop *InnerLoop = LoopList[InnerLoopId]; |
| 557 | Loop *OuterLoop = LoopList[OuterLoopId]; |
| 558 | |
Florian Hahn | c51d088 | 2018-09-06 10:41:01 +0000 | [diff] [blame] | 559 | LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 560 | if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 561 | LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 562 | return false; |
| 563 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 564 | LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n"); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 565 | LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 566 | if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 567 | LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 568 | return false; |
| 569 | } |
| 570 | |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 571 | ORE->emit([&]() { |
| 572 | return OptimizationRemark(DEBUG_TYPE, "Interchanged", |
| 573 | InnerLoop->getStartLoc(), |
| 574 | InnerLoop->getHeader()) |
| 575 | << "Loop interchanged with enclosing loop."; |
| 576 | }); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 577 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 578 | LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit, |
| 579 | LIL); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 580 | LIT.transform(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 581 | LLVM_DEBUG(dbgs() << "Loops interchanged.\n"); |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 582 | LoopsInterchanged++; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 583 | return true; |
| 584 | } |
| 585 | }; |
| 586 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 587 | } // end anonymous namespace |
| 588 | |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 589 | bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) { |
| 590 | return any_of(*BB, [](const Instruction &I) { |
| 591 | return I.mayHaveSideEffects() || I.mayReadFromMemory(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 592 | }); |
| 593 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 594 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 595 | bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { |
| 596 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 597 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 598 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 599 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 600 | LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 601 | |
| 602 | // A perfectly nested loop will not have any branch in between the outer and |
| 603 | // inner block i.e. outer header will branch to either inner preheader and |
| 604 | // outerloop latch. |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 605 | BranchInst *OuterLoopHeaderBI = |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 606 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 607 | if (!OuterLoopHeaderBI) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 608 | return false; |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 609 | |
Chandler Carruth | 96fc1de | 2018-08-26 08:41:15 +0000 | [diff] [blame] | 610 | for (BasicBlock *Succ : successors(OuterLoopHeaderBI)) |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 611 | if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() && |
| 612 | Succ != OuterLoopLatch) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 613 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 614 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 615 | LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 616 | // 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] | 617 | // and outer loop latch doesn't contain any unsafe instructions. |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 618 | if (containsUnsafeInstructions(OuterLoopHeader) || |
| 619 | containsUnsafeInstructions(OuterLoopLatch)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 620 | return false; |
| 621 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 622 | LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 623 | // We have a perfect loop nest. |
| 624 | return true; |
| 625 | } |
| 626 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 627 | bool LoopInterchangeLegality::isLoopStructureUnderstood( |
| 628 | PHINode *InnerInduction) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 629 | unsigned Num = InnerInduction->getNumOperands(); |
| 630 | BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); |
| 631 | for (unsigned i = 0; i < Num; ++i) { |
| 632 | Value *Val = InnerInduction->getOperand(i); |
| 633 | if (isa<Constant>(Val)) |
| 634 | continue; |
| 635 | Instruction *I = dyn_cast<Instruction>(Val); |
| 636 | if (!I) |
| 637 | return false; |
| 638 | // TODO: Handle triangular loops. |
| 639 | // e.g. for(int i=0;i<N;i++) |
| 640 | // for(int j=i;j<N;j++) |
| 641 | unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); |
| 642 | if (InnerInduction->getIncomingBlock(IncomBlockIndx) == |
| 643 | InnerLoopPreheader && |
| 644 | !OuterLoop->isLoopInvariant(I)) { |
| 645 | return false; |
| 646 | } |
| 647 | } |
| 648 | return true; |
| 649 | } |
| 650 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 651 | // If SV is a LCSSA PHI node with a single incoming value, return the incoming |
| 652 | // value. |
| 653 | static Value *followLCSSA(Value *SV) { |
| 654 | PHINode *PHI = dyn_cast<PHINode>(SV); |
| 655 | if (!PHI) |
| 656 | return SV; |
| 657 | |
| 658 | if (PHI->getNumIncomingValues() != 1) |
| 659 | return SV; |
| 660 | return followLCSSA(PHI->getIncomingValue(0)); |
| 661 | } |
| 662 | |
| 663 | // Check V's users to see if it is involved in a reduction in L. |
| 664 | static PHINode *findInnerReductionPhi(Loop *L, Value *V) { |
| 665 | for (Value *User : V->users()) { |
| 666 | if (PHINode *PHI = dyn_cast<PHINode>(User)) { |
| 667 | if (PHI->getNumIncomingValues() == 1) |
| 668 | continue; |
| 669 | RecurrenceDescriptor RD; |
| 670 | if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) |
| 671 | return PHI; |
| 672 | return nullptr; |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | return nullptr; |
| 677 | } |
| 678 | |
| 679 | bool LoopInterchangeLegality::findInductionAndReductions( |
| 680 | Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 681 | if (!L->getLoopLatch() || !L->getLoopPredecessor()) |
| 682 | return false; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 683 | for (PHINode &PHI : L->getHeader()->phis()) { |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 684 | RecurrenceDescriptor RD; |
James Molloy | 1bbf15c | 2015-08-27 09:53:00 +0000 | [diff] [blame] | 685 | InductionDescriptor ID; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 686 | if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) |
| 687 | Inductions.push_back(&PHI); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 688 | else { |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 689 | // PHIs in inner loops need to be part of a reduction in the outer loop, |
| 690 | // discovered when checking the PHIs of the outer loop earlier. |
| 691 | if (!InnerLoop) { |
| 692 | if (OuterInnerReductions.find(&PHI) == OuterInnerReductions.end()) { |
| 693 | LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions " |
| 694 | "across the outer loop.\n"); |
| 695 | return false; |
| 696 | } |
| 697 | } else { |
| 698 | assert(PHI.getNumIncomingValues() == 2 && |
| 699 | "Phis in loop header should have exactly 2 incoming values"); |
| 700 | // Check if we have a PHI node in the outer loop that has a reduction |
| 701 | // result from the inner loop as an incoming value. |
| 702 | Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch())); |
| 703 | PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V); |
| 704 | if (!InnerRedPhi || |
| 705 | !llvm::any_of(InnerRedPhi->incoming_values(), |
| 706 | [&PHI](Value *V) { return V == &PHI; })) { |
| 707 | LLVM_DEBUG( |
| 708 | dbgs() |
| 709 | << "Failed to recognize PHI as an induction or reduction.\n"); |
| 710 | return false; |
| 711 | } |
| 712 | OuterInnerReductions.insert(&PHI); |
| 713 | OuterInnerReductions.insert(InnerRedPhi); |
| 714 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 715 | } |
| 716 | } |
| 717 | return true; |
| 718 | } |
| 719 | |
| 720 | static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 721 | for (PHINode &PHI : Block->phis()) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 722 | // Reduction lcssa phi will have only 1 incoming block that from loop latch. |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 723 | if (PHI.getNumIncomingValues() > 1) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 724 | return false; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 725 | Instruction *Ins = dyn_cast<Instruction>(PHI.getIncomingValue(0)); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 726 | if (!Ins) |
| 727 | return false; |
| 728 | // Incoming value for lcssa phi's in outer loop exit can only be inner loop |
| 729 | // exits lcssa phi else it would not be tightly nested. |
| 730 | if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) |
| 731 | return false; |
| 732 | } |
| 733 | return true; |
| 734 | } |
| 735 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 736 | // This function indicates the current limitations in the transform as a result |
| 737 | // of which we do not proceed. |
| 738 | bool LoopInterchangeLegality::currentLimitations() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 739 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 740 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 741 | |
| 742 | // transform currently expects the loop latches to also be the exiting |
| 743 | // blocks. |
| 744 | if (InnerLoop->getExitingBlock() != InnerLoopLatch || |
| 745 | OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || |
| 746 | !isa<BranchInst>(InnerLoopLatch->getTerminator()) || |
| 747 | !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 748 | LLVM_DEBUG( |
| 749 | dbgs() << "Loops where the latch is not the exiting block are not" |
| 750 | << " supported currently.\n"); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 751 | ORE->emit([&]() { |
| 752 | return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", |
| 753 | OuterLoop->getStartLoc(), |
| 754 | OuterLoop->getHeader()) |
| 755 | << "Loops where the latch is not the exiting block cannot be" |
| 756 | " interchange currently."; |
| 757 | }); |
| 758 | return true; |
| 759 | } |
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; |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 763 | if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) { |
| 764 | LLVM_DEBUG( |
| 765 | dbgs() << "Only outer loops with induction or reduction PHI nodes " |
| 766 | << "are supported currently.\n"); |
| 767 | ORE->emit([&]() { |
| 768 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", |
| 769 | OuterLoop->getStartLoc(), |
| 770 | OuterLoop->getHeader()) |
| 771 | << "Only outer loops with induction or reduction PHI nodes can be" |
| 772 | " interchanged currently."; |
| 773 | }); |
| 774 | return true; |
| 775 | } |
| 776 | |
| 777 | // TODO: Currently we handle only loops with 1 induction variable. |
| 778 | if (Inductions.size() != 1) { |
| 779 | LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not " |
| 780 | << "supported currently.\n"); |
| 781 | ORE->emit([&]() { |
| 782 | return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter", |
| 783 | OuterLoop->getStartLoc(), |
| 784 | OuterLoop->getHeader()) |
| 785 | << "Only outer loops with 1 induction variable can be " |
| 786 | "interchanged currently."; |
| 787 | }); |
| 788 | return true; |
| 789 | } |
| 790 | |
| 791 | Inductions.clear(); |
| 792 | if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 793 | LLVM_DEBUG( |
| 794 | dbgs() << "Only inner loops with induction or reduction PHI nodes " |
| 795 | << "are supported currently.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 796 | ORE->emit([&]() { |
| 797 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", |
| 798 | InnerLoop->getStartLoc(), |
| 799 | InnerLoop->getHeader()) |
| 800 | << "Only inner loops with induction or reduction PHI nodes can be" |
| 801 | " interchange currently."; |
| 802 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 803 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 804 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 805 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 806 | // TODO: Currently we handle only loops with 1 induction variable. |
| 807 | if (Inductions.size() != 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 808 | LLVM_DEBUG( |
| 809 | dbgs() << "We currently only support loops with 1 induction variable." |
| 810 | << "Failed to interchange due to current limitation\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 811 | ORE->emit([&]() { |
| 812 | return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner", |
| 813 | InnerLoop->getStartLoc(), |
| 814 | InnerLoop->getHeader()) |
| 815 | << "Only inner loops with 1 induction variable can be " |
| 816 | "interchanged currently."; |
| 817 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 818 | return true; |
| 819 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 820 | InnerInductionVar = Inductions.pop_back_val(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 821 | |
| 822 | // TODO: Triangular loops are not handled for now. |
| 823 | if (!isLoopStructureUnderstood(InnerInductionVar)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 824 | LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 825 | ORE->emit([&]() { |
| 826 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", |
| 827 | InnerLoop->getStartLoc(), |
| 828 | InnerLoop->getHeader()) |
| 829 | << "Inner loop structure not understood currently."; |
| 830 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 831 | return true; |
| 832 | } |
| 833 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 834 | // TODO: We only handle LCSSA PHI's corresponding to reduction for now. |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 835 | BasicBlock *InnerExit = InnerLoop->getExitBlock(); |
| 836 | if (!containsSafePHI(InnerExit, false)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 837 | LLVM_DEBUG( |
| 838 | dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 839 | ORE->emit([&]() { |
| 840 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner", |
| 841 | InnerLoop->getStartLoc(), |
| 842 | InnerLoop->getHeader()) |
| 843 | << "Only inner loops with LCSSA PHIs can be interchange " |
| 844 | "currently."; |
| 845 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 846 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 847 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 848 | |
| 849 | // TODO: Current limitation: Since we split the inner loop latch at the point |
| 850 | // were induction variable is incremented (induction.next); We cannot have |
| 851 | // more than 1 user of induction.next since it would result in broken code |
| 852 | // after split. |
| 853 | // e.g. |
| 854 | // for(i=0;i<N;i++) { |
| 855 | // for(j = 0;j<M;j++) { |
| 856 | // A[j+1][i+2] = A[j][i]+k; |
| 857 | // } |
| 858 | // } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 859 | Instruction *InnerIndexVarInc = nullptr; |
| 860 | if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) |
| 861 | InnerIndexVarInc = |
| 862 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); |
| 863 | else |
| 864 | InnerIndexVarInc = |
| 865 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); |
| 866 | |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 867 | if (!InnerIndexVarInc) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 868 | LLVM_DEBUG( |
| 869 | dbgs() << "Did not find an instruction to increment the induction " |
| 870 | << "variable.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 871 | ORE->emit([&]() { |
| 872 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner", |
| 873 | InnerLoop->getStartLoc(), |
| 874 | InnerLoop->getHeader()) |
| 875 | << "The inner loop does not increment the induction variable."; |
| 876 | }); |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 877 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 878 | } |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 879 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 880 | // Since we split the inner loop latch on this induction variable. Make sure |
| 881 | // we do not have any instruction between the induction variable and branch |
| 882 | // instruction. |
| 883 | |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 884 | bool FoundInduction = false; |
Florian Hahn | fd2bc11 | 2018-04-26 10:26:17 +0000 | [diff] [blame] | 885 | for (const Instruction &I : |
| 886 | llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) { |
Florian Hahn | cd78345 | 2017-08-25 16:52:29 +0000 | [diff] [blame] | 887 | if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) || |
| 888 | isa<ZExtInst>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 889 | continue; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 890 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 891 | // We found an instruction. If this is not induction variable then it is not |
| 892 | // safe to split this loop latch. |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 893 | if (!I.isIdenticalTo(InnerIndexVarInc)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 894 | LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction " |
| 895 | << "variable increment and branch.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 896 | ORE->emit([&]() { |
| 897 | return OptimizationRemarkMissed( |
| 898 | DEBUG_TYPE, "UnsupportedInsBetweenInduction", |
| 899 | InnerLoop->getStartLoc(), InnerLoop->getHeader()) |
| 900 | << "Found unsupported instruction between induction variable " |
| 901 | "increment and branch."; |
| 902 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 903 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 904 | } |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 905 | |
| 906 | FoundInduction = true; |
| 907 | break; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 908 | } |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 909 | // 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] | 910 | // current limitation. |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 911 | if (!FoundInduction) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 912 | LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 913 | ORE->emit([&]() { |
| 914 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable", |
| 915 | InnerLoop->getStartLoc(), |
| 916 | InnerLoop->getHeader()) |
| 917 | << "Did not find the induction variable."; |
| 918 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 919 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 920 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 921 | return false; |
| 922 | } |
| 923 | |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 924 | // We currently support LCSSA PHI nodes in the outer loop exit, if their |
| 925 | // incoming values do not come from the outer loop latch or if the |
| 926 | // outer loop latch has a single predecessor. In that case, the value will |
| 927 | // be available if both the inner and outer loop conditions are true, which |
| 928 | // will still be true after interchanging. If we have multiple predecessor, |
| 929 | // that may not be the case, e.g. because the outer loop latch may be executed |
| 930 | // if the inner loop is not executed. |
| 931 | static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { |
| 932 | BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); |
| 933 | for (PHINode &PHI : LoopNestExit->phis()) { |
| 934 | // FIXME: We currently are not able to detect floating point reductions |
| 935 | // and have to use floating point PHIs as a proxy to prevent |
| 936 | // interchanging in the presence of floating point reductions. |
| 937 | if (PHI.getType()->isFloatingPointTy()) |
| 938 | return false; |
| 939 | for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { |
| 940 | Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); |
| 941 | if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) |
| 942 | continue; |
| 943 | |
| 944 | // The incoming value is defined in the outer loop latch. Currently we |
| 945 | // only support that in case the outer loop latch has a single predecessor. |
| 946 | // This guarantees that the outer loop latch is executed if and only if |
| 947 | // the inner loop is executed (because tightlyNested() guarantees that the |
| 948 | // outer loop header only branches to the inner loop or the outer loop |
| 949 | // latch). |
| 950 | // FIXME: We could weaken this logic and allow multiple predecessors, |
| 951 | // if the values are produced outside the loop latch. We would need |
| 952 | // additional logic to update the PHI nodes in the exit block as |
| 953 | // well. |
| 954 | if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) |
| 955 | return false; |
| 956 | } |
| 957 | } |
| 958 | return true; |
| 959 | } |
| 960 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 961 | bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, |
| 962 | unsigned OuterLoopId, |
| 963 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 964 | if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 965 | LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId |
| 966 | << " and OuterLoopId = " << OuterLoopId |
| 967 | << " due to dependence\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 968 | ORE->emit([&]() { |
| 969 | return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", |
| 970 | InnerLoop->getStartLoc(), |
| 971 | InnerLoop->getHeader()) |
| 972 | << "Cannot interchange loops due to dependences."; |
| 973 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 974 | return false; |
| 975 | } |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 976 | // Check if outer and inner loop contain legal instructions only. |
| 977 | for (auto *BB : OuterLoop->blocks()) |
Florian Hahn | fd2bc11 | 2018-04-26 10:26:17 +0000 | [diff] [blame] | 978 | for (Instruction &I : BB->instructionsWithoutDebug()) |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 979 | if (CallInst *CI = dyn_cast<CallInst>(&I)) { |
| 980 | // readnone functions do not prevent interchanging. |
| 981 | if (CI->doesNotReadMemory()) |
| 982 | continue; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 983 | LLVM_DEBUG( |
| 984 | dbgs() << "Loops with call instructions cannot be interchanged " |
| 985 | << "safely."); |
Florian Hahn | 9467ccf | 2018-04-03 20:54:04 +0000 | [diff] [blame] | 986 | ORE->emit([&]() { |
| 987 | return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", |
| 988 | CI->getDebugLoc(), |
| 989 | CI->getParent()) |
| 990 | << "Cannot interchange loops due to call instruction."; |
| 991 | }); |
| 992 | |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 993 | return false; |
| 994 | } |
| 995 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 996 | // TODO: The loops could not be interchanged due to current limitations in the |
| 997 | // transform module. |
| 998 | if (currentLimitations()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 999 | LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1000 | return false; |
| 1001 | } |
| 1002 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1003 | // Check if the loops are tightly nested. |
| 1004 | if (!tightlyNested(OuterLoop, InnerLoop)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1005 | LLVM_DEBUG(dbgs() << "Loops not tightly nested\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1006 | ORE->emit([&]() { |
| 1007 | return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", |
| 1008 | InnerLoop->getStartLoc(), |
| 1009 | InnerLoop->getHeader()) |
| 1010 | << "Cannot interchange loops because they are not tightly " |
| 1011 | "nested."; |
| 1012 | }); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1013 | return false; |
| 1014 | } |
| 1015 | |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 1016 | if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1017 | LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 1018 | ORE->emit([&]() { |
| 1019 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", |
| 1020 | OuterLoop->getStartLoc(), |
| 1021 | OuterLoop->getHeader()) |
| 1022 | << "Found unsupported PHI node in loop exit."; |
| 1023 | }); |
| 1024 | return false; |
| 1025 | } |
| 1026 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1027 | return true; |
| 1028 | } |
| 1029 | |
| 1030 | int LoopInterchangeProfitability::getInstrOrderCost() { |
| 1031 | unsigned GoodOrder, BadOrder; |
| 1032 | BadOrder = GoodOrder = 0; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1033 | for (BasicBlock *BB : InnerLoop->blocks()) { |
| 1034 | for (Instruction &Ins : *BB) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1035 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { |
| 1036 | unsigned NumOp = GEP->getNumOperands(); |
| 1037 | bool FoundInnerInduction = false; |
| 1038 | bool FoundOuterInduction = false; |
| 1039 | for (unsigned i = 0; i < NumOp; ++i) { |
| 1040 | const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); |
| 1041 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); |
| 1042 | if (!AR) |
| 1043 | continue; |
| 1044 | |
| 1045 | // If we find the inner induction after an outer induction e.g. |
| 1046 | // for(int i=0;i<N;i++) |
| 1047 | // for(int j=0;j<N;j++) |
| 1048 | // A[i][j] = A[i-1][j-1]+k; |
| 1049 | // then it is a good order. |
| 1050 | if (AR->getLoop() == InnerLoop) { |
| 1051 | // We found an InnerLoop induction after OuterLoop induction. It is |
| 1052 | // a good order. |
| 1053 | FoundInnerInduction = true; |
| 1054 | if (FoundOuterInduction) { |
| 1055 | GoodOrder++; |
| 1056 | break; |
| 1057 | } |
| 1058 | } |
| 1059 | // If we find the outer induction after an inner induction e.g. |
| 1060 | // for(int i=0;i<N;i++) |
| 1061 | // for(int j=0;j<N;j++) |
| 1062 | // A[j][i] = A[j-1][i-1]+k; |
| 1063 | // then it is a bad order. |
| 1064 | if (AR->getLoop() == OuterLoop) { |
| 1065 | // We found an OuterLoop induction after InnerLoop induction. It is |
| 1066 | // a bad order. |
| 1067 | FoundOuterInduction = true; |
| 1068 | if (FoundInnerInduction) { |
| 1069 | BadOrder++; |
| 1070 | break; |
| 1071 | } |
| 1072 | } |
| 1073 | } |
| 1074 | } |
| 1075 | } |
| 1076 | } |
| 1077 | return GoodOrder - BadOrder; |
| 1078 | } |
| 1079 | |
Chad Rosier | e6b3a63 | 2016-09-14 17:12:30 +0000 | [diff] [blame] | 1080 | static bool isProfitableForVectorization(unsigned InnerLoopId, |
| 1081 | unsigned OuterLoopId, |
| 1082 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1083 | // TODO: Improve this heuristic to catch more cases. |
| 1084 | // If the inner loop is loop independent or doesn't carry any dependency it is |
| 1085 | // profitable to move this to outer position. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1086 | for (auto &Row : DepMatrix) { |
| 1087 | if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1088 | return false; |
| 1089 | // TODO: We need to improve this heuristic. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1090 | if (Row[OuterLoopId] != '=') |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1091 | return false; |
| 1092 | } |
| 1093 | // If outer loop has dependence and inner loop is loop independent then it is |
| 1094 | // profitable to interchange to enable parallelism. |
Florian Hahn | ceee788 | 2018-04-24 16:55:32 +0000 | [diff] [blame] | 1095 | // If there are no dependences, interchanging will not improve anything. |
| 1096 | return !DepMatrix.empty(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1097 | } |
| 1098 | |
| 1099 | bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, |
| 1100 | unsigned OuterLoopId, |
| 1101 | CharMatrix &DepMatrix) { |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1102 | // TODO: Add better profitability checks. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1103 | // e.g |
| 1104 | // 1) Construct dependency matrix and move the one with no loop carried dep |
| 1105 | // inside to enable vectorization. |
| 1106 | |
| 1107 | // This is rough cost estimation algorithm. It counts the good and bad order |
| 1108 | // of induction variables in the instruction and allows reordering if number |
| 1109 | // of bad orders is more than good. |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 1110 | int Cost = getInstrOrderCost(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1111 | LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n"); |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 1112 | if (Cost < -LoopInterchangeCostThreshold) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1113 | return true; |
| 1114 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1115 | // 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] | 1116 | // we can move this loop outside to improve parallelism. |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1117 | if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) |
| 1118 | return true; |
| 1119 | |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1120 | ORE->emit([&]() { |
| 1121 | return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", |
| 1122 | InnerLoop->getStartLoc(), |
| 1123 | InnerLoop->getHeader()) |
| 1124 | << "Interchanging loops is too costly (cost=" |
| 1125 | << ore::NV("Cost", Cost) << ", threshold=" |
| 1126 | << ore::NV("Threshold", LoopInterchangeCostThreshold) |
| 1127 | << ") and it does not improve parallelism."; |
| 1128 | }); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1129 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1130 | } |
| 1131 | |
| 1132 | void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, |
| 1133 | Loop *InnerLoop) { |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 1134 | for (Loop *L : *OuterLoop) |
| 1135 | if (L == InnerLoop) { |
| 1136 | OuterLoop->removeChildLoop(L); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1137 | return; |
| 1138 | } |
Benjamin Kramer | 8ceb323 | 2015-10-25 22:28:27 +0000 | [diff] [blame] | 1139 | llvm_unreachable("Couldn't find loop"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1140 | } |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 1141 | |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1142 | /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the |
| 1143 | /// new inner and outer loop after interchanging: NewInner is the original |
| 1144 | /// outer loop and NewOuter is the original inner loop. |
| 1145 | /// |
| 1146 | /// Before interchanging, we have the following structure |
| 1147 | /// Outer preheader |
| 1148 | // Outer header |
| 1149 | // Inner preheader |
| 1150 | // Inner header |
| 1151 | // Inner body |
| 1152 | // Inner latch |
| 1153 | // outer bbs |
| 1154 | // Outer latch |
| 1155 | // |
| 1156 | // After interchanging: |
| 1157 | // Inner preheader |
| 1158 | // Inner header |
| 1159 | // Outer preheader |
| 1160 | // Outer header |
| 1161 | // Inner body |
| 1162 | // outer bbs |
| 1163 | // Outer latch |
| 1164 | // Inner latch |
| 1165 | void LoopInterchangeTransform::restructureLoops( |
| 1166 | Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, |
| 1167 | BasicBlock *OrigOuterPreHeader) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1168 | Loop *OuterLoopParent = OuterLoop->getParentLoop(); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1169 | // The original inner loop preheader moves from the new inner loop to |
| 1170 | // the parent loop, if there is one. |
| 1171 | NewInner->removeBlockFromLoop(OrigInnerPreHeader); |
| 1172 | LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); |
| 1173 | |
| 1174 | // Switch the loop levels. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1175 | if (OuterLoopParent) { |
| 1176 | // Remove the loop from its parent loop. |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1177 | removeChildLoop(OuterLoopParent, NewInner); |
| 1178 | removeChildLoop(NewInner, NewOuter); |
| 1179 | OuterLoopParent->addChildLoop(NewOuter); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1180 | } else { |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1181 | removeChildLoop(NewInner, NewOuter); |
| 1182 | LI->changeTopLevelLoop(NewInner, NewOuter); |
| 1183 | } |
| 1184 | while (!NewOuter->empty()) |
| 1185 | NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); |
| 1186 | NewOuter->addChildLoop(NewInner); |
| 1187 | |
| 1188 | // BBs from the original inner loop. |
| 1189 | SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); |
| 1190 | |
| 1191 | // Add BBs from the original outer loop to the original inner loop (excluding |
| 1192 | // BBs already in inner loop) |
| 1193 | for (BasicBlock *BB : NewInner->blocks()) |
| 1194 | if (LI->getLoopFor(BB) == NewInner) |
| 1195 | NewOuter->addBlockEntry(BB); |
| 1196 | |
| 1197 | // Now remove inner loop header and latch from the new inner loop and move |
| 1198 | // other BBs (the loop body) to the new inner loop. |
| 1199 | BasicBlock *OuterHeader = NewOuter->getHeader(); |
| 1200 | BasicBlock *OuterLatch = NewOuter->getLoopLatch(); |
| 1201 | for (BasicBlock *BB : OrigInnerBBs) { |
Florian Hahn | 74418185 | 2018-04-23 21:38:19 +0000 | [diff] [blame] | 1202 | // Nothing will change for BBs in child loops. |
| 1203 | if (LI->getLoopFor(BB) != NewOuter) |
| 1204 | continue; |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1205 | // Remove the new outer loop header and latch from the new inner loop. |
| 1206 | if (BB == OuterHeader || BB == OuterLatch) |
| 1207 | NewInner->removeBlockFromLoop(BB); |
| 1208 | else |
| 1209 | LI->changeLoopFor(BB, NewInner); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1210 | } |
| 1211 | |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1212 | // The preheader of the original outer loop becomes part of the new |
| 1213 | // outer loop. |
| 1214 | NewOuter->addBlockEntry(OrigOuterPreHeader); |
| 1215 | LI->changeLoopFor(OrigOuterPreHeader, NewOuter); |
Florian Hahn | 3afb974 | 2018-09-14 07:50:20 +0000 | [diff] [blame] | 1216 | |
| 1217 | // Tell SE that we move the loops around. |
| 1218 | SE->forgetLoop(NewOuter); |
| 1219 | SE->forgetLoop(NewInner); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1220 | } |
| 1221 | |
| 1222 | bool LoopInterchangeTransform::transform() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1223 | bool Transformed = false; |
| 1224 | Instruction *InnerIndexVar; |
| 1225 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1226 | if (InnerLoop->getSubLoops().empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1227 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
Florian Hahn | e496121 | 2019-09-11 08:23:23 +0000 | [diff] [blame^] | 1228 | LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n"); |
Kit Barton | 987fdfd | 2019-05-23 20:53:05 +0000 | [diff] [blame] | 1229 | PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1230 | if (!InductionPHI) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1231 | LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1232 | return false; |
| 1233 | } |
| 1234 | |
| 1235 | if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) |
| 1236 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); |
| 1237 | else |
| 1238 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); |
| 1239 | |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1240 | // Ensure that InductionPHI is the first Phi node. |
David Green | 907b60f | 2017-10-21 13:58:37 +0000 | [diff] [blame] | 1241 | if (&InductionPHI->getParent()->front() != InductionPHI) |
| 1242 | InductionPHI->moveBefore(&InductionPHI->getParent()->front()); |
| 1243 | |
Florian Hahn | e496121 | 2019-09-11 08:23:23 +0000 | [diff] [blame^] | 1244 | // Create a new latch block for the inner loop. We split at the |
| 1245 | // current latch's terminator and then move the condition and all |
| 1246 | // operands that are not either loop-invariant or the induction PHI into the |
| 1247 | // new latch block. |
| 1248 | BasicBlock *NewLatch = |
| 1249 | SplitBlock(InnerLoop->getLoopLatch(), |
| 1250 | InnerLoop->getLoopLatch()->getTerminator(), DT, LI); |
| 1251 | |
| 1252 | SmallSetVector<Instruction *, 4> WorkList; |
| 1253 | unsigned i = 0; |
| 1254 | auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() { |
| 1255 | for (; i < WorkList.size(); i++) { |
| 1256 | // Duplicate instruction and move it the new latch. Update uses that |
| 1257 | // have been moved. |
| 1258 | Instruction *NewI = WorkList[i]->clone(); |
| 1259 | NewI->insertBefore(NewLatch->getFirstNonPHI()); |
| 1260 | assert(!NewI->mayHaveSideEffects() && |
| 1261 | "Moving instructions with side-effects may change behavior of " |
| 1262 | "the loop nest!"); |
| 1263 | for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end(); |
| 1264 | UI != UE;) { |
| 1265 | Use &U = *UI++; |
| 1266 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1267 | if (!InnerLoop->contains(UserI->getParent()) || |
| 1268 | UserI->getParent() == NewLatch || UserI == InductionPHI) |
| 1269 | U.set(NewI); |
| 1270 | } |
| 1271 | // Add operands of moved instruction to the worklist, except if they are |
| 1272 | // outside the inner loop or are the induction PHI. |
| 1273 | for (Value *Op : WorkList[i]->operands()) { |
| 1274 | Instruction *OpI = dyn_cast<Instruction>(Op); |
| 1275 | if (!OpI || |
| 1276 | this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop || |
| 1277 | OpI == InductionPHI) |
| 1278 | continue; |
| 1279 | WorkList.insert(OpI); |
| 1280 | } |
| 1281 | } |
| 1282 | }; |
| 1283 | |
| 1284 | // FIXME: Should we interchange when we have a constant condition? |
| 1285 | Instruction *CondI = dyn_cast<Instruction>( |
| 1286 | cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator()) |
| 1287 | ->getCondition()); |
| 1288 | if (CondI) |
| 1289 | WorkList.insert(CondI); |
| 1290 | MoveInstructions(); |
| 1291 | WorkList.insert(cast<Instruction>(InnerIndexVar)); |
| 1292 | MoveInstructions(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1293 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1294 | // Splits the inner loops phi nodes out into a separate basic block. |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1295 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1296 | SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); |
| 1297 | LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1298 | } |
| 1299 | |
| 1300 | Transformed |= adjustLoopLinks(); |
| 1301 | if (!Transformed) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1302 | LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1303 | return false; |
| 1304 | } |
| 1305 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1306 | return true; |
| 1307 | } |
| 1308 | |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1309 | /// \brief Move all instructions except the terminator from FromBB right before |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1310 | /// InsertBefore |
| 1311 | static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { |
| 1312 | auto &ToList = InsertBefore->getParent()->getInstList(); |
| 1313 | auto &FromList = FromBB->getInstList(); |
| 1314 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1315 | ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), |
| 1316 | FromBB->getTerminator()->getIterator()); |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1317 | } |
| 1318 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 1319 | /// Update BI to jump to NewBB instead of OldBB. Records updates to |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1320 | /// the dominator tree in DTUpdates, if DT should be preserved. |
| 1321 | static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, |
| 1322 | BasicBlock *NewBB, |
| 1323 | std::vector<DominatorTree::UpdateType> &DTUpdates) { |
Chandler Carruth | 96fc1de | 2018-08-26 08:41:15 +0000 | [diff] [blame] | 1324 | assert(llvm::count_if(successors(BI), |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1325 | [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 && |
| 1326 | "BI must jump to OldBB at most once."); |
| 1327 | for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) { |
| 1328 | if (BI->getSuccessor(i) == OldBB) { |
| 1329 | BI->setSuccessor(i, NewBB); |
| 1330 | |
| 1331 | DTUpdates.push_back( |
| 1332 | {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); |
| 1333 | DTUpdates.push_back( |
| 1334 | {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); |
| 1335 | break; |
| 1336 | } |
| 1337 | } |
| 1338 | } |
| 1339 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1340 | // Move Lcssa PHIs to the right place. |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1341 | static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, |
| 1342 | BasicBlock *InnerLatch, BasicBlock *OuterHeader, |
| 1343 | BasicBlock *OuterLatch, BasicBlock *OuterExit) { |
| 1344 | |
| 1345 | // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are |
| 1346 | // defined either in the header or latch. Those blocks will become header and |
| 1347 | // latch of the new outer loop, and the only possible users can PHI nodes |
| 1348 | // in the exit block of the loop nest or the outer loop header (reduction |
| 1349 | // PHIs, in that case, the incoming value must be defined in the inner loop |
| 1350 | // header). We can just substitute the user with the incoming value and remove |
| 1351 | // the PHI. |
| 1352 | for (PHINode &P : make_early_inc_range(InnerExit->phis())) { |
| 1353 | assert(P.getNumIncomingValues() == 1 && |
| 1354 | "Only loops with a single exit are supported!"); |
| 1355 | |
| 1356 | // Incoming values are guaranteed be instructions currently. |
| 1357 | auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch)); |
| 1358 | // Skip phis with incoming values from the inner loop body, excluding the |
| 1359 | // header and latch. |
| 1360 | if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader) |
| 1361 | continue; |
| 1362 | |
| 1363 | assert(all_of(P.users(), |
| 1364 | [OuterHeader, OuterExit, IncI, InnerHeader](User *U) { |
| 1365 | return (cast<PHINode>(U)->getParent() == OuterHeader && |
| 1366 | IncI->getParent() == InnerHeader) || |
| 1367 | cast<PHINode>(U)->getParent() == OuterExit; |
| 1368 | }) && |
| 1369 | "Can only replace phis iff the uses are in the loop nest exit or " |
| 1370 | "the incoming value is defined in the inner header (it will " |
| 1371 | "dominate all loop blocks after interchanging)"); |
| 1372 | P.replaceAllUsesWith(IncI); |
| 1373 | P.eraseFromParent(); |
| 1374 | } |
| 1375 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1376 | SmallVector<PHINode *, 8> LcssaInnerExit; |
| 1377 | for (PHINode &P : InnerExit->phis()) |
| 1378 | LcssaInnerExit.push_back(&P); |
| 1379 | |
| 1380 | SmallVector<PHINode *, 8> LcssaInnerLatch; |
| 1381 | for (PHINode &P : InnerLatch->phis()) |
| 1382 | LcssaInnerLatch.push_back(&P); |
| 1383 | |
| 1384 | // Lcssa PHIs for values used outside the inner loop are in InnerExit. |
| 1385 | // If a PHI node has users outside of InnerExit, it has a use outside the |
| 1386 | // interchanged loop and we have to preserve it. We move these to |
| 1387 | // InnerLatch, which will become the new exit block for the innermost |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1388 | // loop after interchanging. |
| 1389 | for (PHINode *P : LcssaInnerExit) |
| 1390 | P->moveBefore(InnerLatch->getFirstNonPHI()); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1391 | |
| 1392 | // If the inner loop latch contains LCSSA PHIs, those come from a child loop |
| 1393 | // and we have to move them to the new inner latch. |
| 1394 | for (PHINode *P : LcssaInnerLatch) |
| 1395 | P->moveBefore(InnerExit->getFirstNonPHI()); |
| 1396 | |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1397 | // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have |
| 1398 | // incoming values from the outer latch or header, we have to add a new PHI |
| 1399 | // in the inner loop latch, which became the exit block of the outer loop, |
| 1400 | // after interchanging. |
| 1401 | if (OuterExit) { |
| 1402 | for (PHINode &P : OuterExit->phis()) { |
| 1403 | if (P.getNumIncomingValues() != 1) |
| 1404 | continue; |
| 1405 | // Skip Phis with incoming values not defined in the outer loop's header |
| 1406 | // and latch. Also skip incoming phis defined in the latch. Those should |
| 1407 | // already have been updated. |
| 1408 | auto I = dyn_cast<Instruction>(P.getIncomingValue(0)); |
| 1409 | if (!I || ((I->getParent() != OuterLatch || isa<PHINode>(I)) && |
| 1410 | I->getParent() != OuterHeader)) |
| 1411 | continue; |
| 1412 | |
| 1413 | PHINode *NewPhi = dyn_cast<PHINode>(P.clone()); |
| 1414 | NewPhi->setIncomingValue(0, P.getIncomingValue(0)); |
| 1415 | NewPhi->setIncomingBlock(0, OuterLatch); |
| 1416 | NewPhi->insertBefore(InnerLatch->getFirstNonPHI()); |
| 1417 | P.setIncomingValue(0, NewPhi); |
| 1418 | } |
| 1419 | } |
| 1420 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1421 | // Now adjust the incoming blocks for the LCSSA PHIs. |
| 1422 | // For PHIs moved from Inner's exit block, we need to replace Inner's latch |
| 1423 | // with the new latch. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1424 | InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1425 | } |
| 1426 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1427 | bool LoopInterchangeTransform::adjustLoopBranches() { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1428 | LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n"); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1429 | std::vector<DominatorTree::UpdateType> DTUpdates; |
| 1430 | |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1431 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1432 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1433 | |
| 1434 | assert(OuterLoopPreHeader != OuterLoop->getHeader() && |
| 1435 | InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader && |
| 1436 | InnerLoopPreHeader && "Guaranteed by loop-simplify form"); |
| 1437 | // Ensure that both preheaders do not contain PHI nodes and have single |
| 1438 | // predecessors. This allows us to move them easily. We use |
| 1439 | // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing |
| 1440 | // preheaders do not satisfy those conditions. |
| 1441 | if (isa<PHINode>(OuterLoopPreHeader->begin()) || |
| 1442 | !OuterLoopPreHeader->getUniquePredecessor()) |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 1443 | OuterLoopPreHeader = |
| 1444 | InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true); |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1445 | if (InnerLoopPreHeader == OuterLoop->getHeader()) |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 1446 | InnerLoopPreHeader = |
| 1447 | InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true); |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1448 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1449 | // Adjust the loop preheader |
| 1450 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1451 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1452 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 1453 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1454 | BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); |
| 1455 | BasicBlock *InnerLoopLatchPredecessor = |
| 1456 | InnerLoopLatch->getUniquePredecessor(); |
| 1457 | BasicBlock *InnerLoopLatchSuccessor; |
| 1458 | BasicBlock *OuterLoopLatchSuccessor; |
| 1459 | |
| 1460 | BranchInst *OuterLoopLatchBI = |
| 1461 | dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); |
| 1462 | BranchInst *InnerLoopLatchBI = |
| 1463 | dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); |
| 1464 | BranchInst *OuterLoopHeaderBI = |
| 1465 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 1466 | BranchInst *InnerLoopHeaderBI = |
| 1467 | dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); |
| 1468 | |
| 1469 | if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || |
| 1470 | !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || |
| 1471 | !InnerLoopHeaderBI) |
| 1472 | return false; |
| 1473 | |
| 1474 | BranchInst *InnerLoopLatchPredecessorBI = |
| 1475 | dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); |
| 1476 | BranchInst *OuterLoopPredecessorBI = |
| 1477 | dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); |
| 1478 | |
| 1479 | if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) |
| 1480 | return false; |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1481 | BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); |
| 1482 | if (!InnerLoopHeaderSuccessor) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1483 | return false; |
| 1484 | |
| 1485 | // Adjust Loop Preheader and headers |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1486 | updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, |
| 1487 | InnerLoopPreHeader, DTUpdates); |
| 1488 | updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates); |
| 1489 | updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, |
| 1490 | InnerLoopHeaderSuccessor, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1491 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1492 | // Adjust reduction PHI's now that the incoming block has changed. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1493 | InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader, |
| 1494 | OuterLoopHeader); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1495 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1496 | updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, |
| 1497 | OuterLoopPreHeader, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1498 | |
| 1499 | // -------------Adjust loop latches----------- |
| 1500 | if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) |
| 1501 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); |
| 1502 | else |
| 1503 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); |
| 1504 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1505 | updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, |
| 1506 | InnerLoopLatchSuccessor, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1507 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1508 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1509 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) |
| 1510 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); |
| 1511 | else |
| 1512 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); |
| 1513 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1514 | updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, |
| 1515 | OuterLoopLatchSuccessor, DTUpdates); |
| 1516 | updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, |
| 1517 | DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1518 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1519 | DT->applyUpdates(DTUpdates); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1520 | restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, |
| 1521 | OuterLoopPreHeader); |
| 1522 | |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1523 | moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch, |
| 1524 | OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock()); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1525 | // For PHIs in the exit block of the outer loop, outer's latch has been |
| 1526 | // replaced by Inners'. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1527 | OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1528 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 1529 | // Now update the reduction PHIs in the inner and outer loop headers. |
| 1530 | SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs; |
| 1531 | for (PHINode &PHI : drop_begin(InnerLoopHeader->phis(), 1)) |
| 1532 | InnerLoopPHIs.push_back(cast<PHINode>(&PHI)); |
| 1533 | for (PHINode &PHI : drop_begin(OuterLoopHeader->phis(), 1)) |
| 1534 | OuterLoopPHIs.push_back(cast<PHINode>(&PHI)); |
| 1535 | |
| 1536 | auto &OuterInnerReductions = LIL.getOuterInnerReductions(); |
| 1537 | (void)OuterInnerReductions; |
| 1538 | |
| 1539 | // Now move the remaining reduction PHIs from outer to inner loop header and |
| 1540 | // vice versa. The PHI nodes must be part of a reduction across the inner and |
| 1541 | // outer loop and all the remains to do is and updating the incoming blocks. |
| 1542 | for (PHINode *PHI : OuterLoopPHIs) { |
| 1543 | PHI->moveBefore(InnerLoopHeader->getFirstNonPHI()); |
| 1544 | assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && |
| 1545 | "Expected a reduction PHI node"); |
| 1546 | } |
| 1547 | for (PHINode *PHI : InnerLoopPHIs) { |
| 1548 | PHI->moveBefore(OuterLoopHeader->getFirstNonPHI()); |
| 1549 | assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && |
| 1550 | "Expected a reduction PHI node"); |
| 1551 | } |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1552 | |
| 1553 | // Update the incoming blocks for moved PHI nodes. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1554 | OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader); |
| 1555 | OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch); |
| 1556 | InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader); |
| 1557 | InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1558 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1559 | return true; |
| 1560 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1561 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1562 | void LoopInterchangeTransform::adjustLoopPreheaders() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1563 | // We have interchanged the preheaders so we need to interchange the data in |
| 1564 | // the preheader as well. |
| 1565 | // This is because the content of inner preheader was previously executed |
| 1566 | // inside the outer loop. |
| 1567 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1568 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1569 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1570 | BranchInst *InnerTermBI = |
| 1571 | cast<BranchInst>(InnerLoopPreHeader->getTerminator()); |
| 1572 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1573 | // These instructions should now be executed inside the loop. |
| 1574 | // Move instruction into a new block after outer header. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1575 | moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1576 | // These instructions were not executed previously in the loop so move them to |
| 1577 | // the older inner loop preheader. |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1578 | moveBBContents(OuterLoopPreHeader, InnerTermBI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1579 | } |
| 1580 | |
| 1581 | bool LoopInterchangeTransform::adjustLoopLinks() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1582 | // Adjust all branches in the inner and outer loop. |
| 1583 | bool Changed = adjustLoopBranches(); |
| 1584 | if (Changed) |
| 1585 | adjustLoopPreheaders(); |
| 1586 | return Changed; |
| 1587 | } |
| 1588 | |
| 1589 | char LoopInterchange::ID = 0; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1590 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1591 | INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", |
| 1592 | "Interchanges loops for cache reuse", false, false) |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 1593 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 1594 | INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1595 | INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1596 | |
| 1597 | INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", |
| 1598 | "Interchanges loops for cache reuse", false, false) |
| 1599 | |
| 1600 | Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } |