Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 1 | //===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implement a loop-aware load elimination pass. |
| 11 | // |
| 12 | // It uses LoopAccessAnalysis to identify loop-carried dependences with a |
| 13 | // distance of one between stores and loads. These form the candidates for the |
| 14 | // transformation. The source value of each store then propagated to the user |
| 15 | // of the corresponding load. This makes the load dead. |
| 16 | // |
| 17 | // The pass can also version the loop and add memchecks in order to prove that |
| 18 | // may-aliasing stores can't change the value in memory before it's read by the |
| 19 | // load. |
| 20 | // |
| 21 | //===----------------------------------------------------------------------===// |
| 22 | |
| 23 | #include "llvm/ADT/Statistic.h" |
| 24 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
| 25 | #include "llvm/Analysis/LoopInfo.h" |
| 26 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 27 | #include "llvm/IR/Dominators.h" |
| 28 | #include "llvm/IR/Module.h" |
| 29 | #include "llvm/Pass.h" |
| 30 | #include "llvm/Support/Debug.h" |
Adam Nemet | efb2341 | 2016-03-10 23:54:39 +0000 | [diff] [blame] | 31 | #include "llvm/Transforms/Scalar.h" |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 32 | #include "llvm/Transforms/Utils/LoopVersioning.h" |
| 33 | #include <forward_list> |
| 34 | |
| 35 | #define LLE_OPTION "loop-load-elim" |
| 36 | #define DEBUG_TYPE LLE_OPTION |
| 37 | |
| 38 | using namespace llvm; |
| 39 | |
| 40 | static cl::opt<unsigned> CheckPerElim( |
| 41 | "runtime-check-per-loop-load-elim", cl::Hidden, |
| 42 | cl::desc("Max number of memchecks allowed per eliminated load on average"), |
| 43 | cl::init(1)); |
| 44 | |
Silviu Baranga | 2910a4f | 2015-11-09 13:26:09 +0000 | [diff] [blame] | 45 | static cl::opt<unsigned> LoadElimSCEVCheckThreshold( |
| 46 | "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden, |
| 47 | cl::desc("The maximum number of SCEV checks allowed for Loop " |
| 48 | "Load Elimination")); |
| 49 | |
| 50 | |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 51 | STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE"); |
| 52 | |
| 53 | namespace { |
| 54 | |
| 55 | /// \brief Represent a store-to-forwarding candidate. |
| 56 | struct StoreToLoadForwardingCandidate { |
| 57 | LoadInst *Load; |
| 58 | StoreInst *Store; |
| 59 | |
| 60 | StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store) |
| 61 | : Load(Load), Store(Store) {} |
| 62 | |
| 63 | /// \brief Return true if the dependence from the store to the load has a |
| 64 | /// distance of one. E.g. A[i+1] = A[i] |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 65 | bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE, |
| 66 | Loop *L) const { |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 67 | Value *LoadPtr = Load->getPointerOperand(); |
| 68 | Value *StorePtr = Store->getPointerOperand(); |
| 69 | Type *LoadPtrType = LoadPtr->getType(); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 70 | Type *LoadType = LoadPtrType->getPointerElementType(); |
| 71 | |
| 72 | assert(LoadPtrType->getPointerAddressSpace() == |
Adam Nemet | 7c94c9b | 2015-11-04 00:10:33 +0000 | [diff] [blame] | 73 | StorePtr->getType()->getPointerAddressSpace() && |
| 74 | LoadType == StorePtr->getType()->getPointerElementType() && |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 75 | "Should be a known dependence"); |
| 76 | |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 77 | // Currently we only support accesses with unit stride. FIXME: we should be |
| 78 | // able to handle non unit stirde as well as long as the stride is equal to |
| 79 | // the dependence distance. |
Denis Zobnin | 15d1e64 | 2016-05-10 05:55:16 +0000 | [diff] [blame^] | 80 | if (getPtrStride(PSE, LoadPtr, L) != 1 || |
| 81 | getPtrStride(PSE, StorePtr, L) != 1) |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 82 | return false; |
| 83 | |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 84 | auto &DL = Load->getParent()->getModule()->getDataLayout(); |
| 85 | unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType)); |
| 86 | |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 87 | auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr)); |
| 88 | auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr)); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 89 | |
| 90 | // We don't need to check non-wrapping here because forward/backward |
| 91 | // dependence wouldn't be valid if these weren't monotonic accesses. |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 92 | auto *Dist = cast<SCEVConstant>( |
| 93 | PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV)); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 94 | const APInt &Val = Dist->getAPInt(); |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 95 | return Val == TypeByteSize; |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 96 | } |
| 97 | |
| 98 | Value *getLoadPtr() const { return Load->getPointerOperand(); } |
| 99 | |
| 100 | #ifndef NDEBUG |
| 101 | friend raw_ostream &operator<<(raw_ostream &OS, |
| 102 | const StoreToLoadForwardingCandidate &Cand) { |
| 103 | OS << *Cand.Store << " -->\n"; |
| 104 | OS.indent(2) << *Cand.Load << "\n"; |
| 105 | return OS; |
| 106 | } |
| 107 | #endif |
| 108 | }; |
| 109 | |
| 110 | /// \brief Check if the store dominates all latches, so as long as there is no |
| 111 | /// intervening store this value will be loaded in the next iteration. |
| 112 | bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L, |
| 113 | DominatorTree *DT) { |
| 114 | SmallVector<BasicBlock *, 8> Latches; |
| 115 | L->getLoopLatches(Latches); |
| 116 | return std::all_of(Latches.begin(), Latches.end(), |
| 117 | [&](const BasicBlock *Latch) { |
| 118 | return DT->dominates(StoreBlock, Latch); |
| 119 | }); |
| 120 | } |
| 121 | |
| 122 | /// \brief The per-loop class that does most of the work. |
| 123 | class LoadEliminationForLoop { |
| 124 | public: |
| 125 | LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI, |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 126 | DominatorTree *DT) |
| 127 | : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.PSE) {} |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 128 | |
| 129 | /// \brief Look through the loop-carried and loop-independent dependences in |
| 130 | /// this loop and find store->load dependences. |
| 131 | /// |
| 132 | /// Note that no candidate is returned if LAA has failed to analyze the loop |
| 133 | /// (e.g. if it's not bottom-tested, contains volatile memops, etc.) |
| 134 | std::forward_list<StoreToLoadForwardingCandidate> |
| 135 | findStoreToLoadDependences(const LoopAccessInfo &LAI) { |
| 136 | std::forward_list<StoreToLoadForwardingCandidate> Candidates; |
| 137 | |
| 138 | const auto *Deps = LAI.getDepChecker().getDependences(); |
| 139 | if (!Deps) |
| 140 | return Candidates; |
| 141 | |
| 142 | // Find store->load dependences (consequently true dep). Both lexically |
| 143 | // forward and backward dependences qualify. Disqualify loads that have |
| 144 | // other unknown dependences. |
| 145 | |
| 146 | SmallSet<Instruction *, 4> LoadsWithUnknownDepedence; |
| 147 | |
| 148 | for (const auto &Dep : *Deps) { |
| 149 | Instruction *Source = Dep.getSource(LAI); |
| 150 | Instruction *Destination = Dep.getDestination(LAI); |
| 151 | |
| 152 | if (Dep.Type == MemoryDepChecker::Dependence::Unknown) { |
| 153 | if (isa<LoadInst>(Source)) |
| 154 | LoadsWithUnknownDepedence.insert(Source); |
| 155 | if (isa<LoadInst>(Destination)) |
| 156 | LoadsWithUnknownDepedence.insert(Destination); |
| 157 | continue; |
| 158 | } |
| 159 | |
| 160 | if (Dep.isBackward()) |
| 161 | // Note that the designations source and destination follow the program |
| 162 | // order, i.e. source is always first. (The direction is given by the |
| 163 | // DepType.) |
| 164 | std::swap(Source, Destination); |
| 165 | else |
| 166 | assert(Dep.isForward() && "Needs to be a forward dependence"); |
| 167 | |
| 168 | auto *Store = dyn_cast<StoreInst>(Source); |
| 169 | if (!Store) |
| 170 | continue; |
| 171 | auto *Load = dyn_cast<LoadInst>(Destination); |
| 172 | if (!Load) |
| 173 | continue; |
Adam Nemet | 7aba60c | 2016-03-24 17:59:26 +0000 | [diff] [blame] | 174 | |
| 175 | // Only progagate the value if they are of the same type. |
| 176 | if (Store->getPointerOperand()->getType() != |
| 177 | Load->getPointerOperand()->getType()) |
| 178 | continue; |
| 179 | |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 180 | Candidates.emplace_front(Load, Store); |
| 181 | } |
| 182 | |
| 183 | if (!LoadsWithUnknownDepedence.empty()) |
| 184 | Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) { |
| 185 | return LoadsWithUnknownDepedence.count(C.Load); |
| 186 | }); |
| 187 | |
| 188 | return Candidates; |
| 189 | } |
| 190 | |
| 191 | /// \brief Return the index of the instruction according to program order. |
| 192 | unsigned getInstrIndex(Instruction *Inst) { |
| 193 | auto I = InstOrder.find(Inst); |
| 194 | assert(I != InstOrder.end() && "No index for instruction"); |
| 195 | return I->second; |
| 196 | } |
| 197 | |
| 198 | /// \brief If a load has multiple candidates associated (i.e. different |
| 199 | /// stores), it means that it could be forwarding from multiple stores |
| 200 | /// depending on control flow. Remove these candidates. |
| 201 | /// |
| 202 | /// Here, we rely on LAA to include the relevant loop-independent dependences. |
| 203 | /// LAA is known to omit these in the very simple case when the read and the |
| 204 | /// write within an alias set always takes place using the *same* pointer. |
| 205 | /// |
| 206 | /// However, we know that this is not the case here, i.e. we can rely on LAA |
| 207 | /// to provide us with loop-independent dependences for the cases we're |
| 208 | /// interested. Consider the case for example where a loop-independent |
| 209 | /// dependece S1->S2 invalidates the forwarding S3->S2. |
| 210 | /// |
| 211 | /// A[i] = ... (S1) |
| 212 | /// ... = A[i] (S2) |
| 213 | /// A[i+1] = ... (S3) |
| 214 | /// |
| 215 | /// LAA will perform dependence analysis here because there are two |
| 216 | /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]). |
| 217 | void removeDependencesFromMultipleStores( |
| 218 | std::forward_list<StoreToLoadForwardingCandidate> &Candidates) { |
| 219 | // If Store is nullptr it means that we have multiple stores forwarding to |
| 220 | // this store. |
| 221 | typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *> |
| 222 | LoadToSingleCandT; |
| 223 | LoadToSingleCandT LoadToSingleCand; |
| 224 | |
| 225 | for (const auto &Cand : Candidates) { |
| 226 | bool NewElt; |
| 227 | LoadToSingleCandT::iterator Iter; |
| 228 | |
| 229 | std::tie(Iter, NewElt) = |
| 230 | LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand)); |
| 231 | if (!NewElt) { |
| 232 | const StoreToLoadForwardingCandidate *&OtherCand = Iter->second; |
| 233 | // Already multiple stores forward to this load. |
| 234 | if (OtherCand == nullptr) |
| 235 | continue; |
| 236 | |
Adam Nemet | efc091f | 2016-02-29 23:21:12 +0000 | [diff] [blame] | 237 | // Handle the very basic case when the two stores are in the same block |
| 238 | // so deciding which one forwards is easy. The later one forwards as |
| 239 | // long as they both have a dependence distance of one to the load. |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 240 | if (Cand.Store->getParent() == OtherCand->Store->getParent() && |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 241 | Cand.isDependenceDistanceOfOne(PSE, L) && |
| 242 | OtherCand->isDependenceDistanceOfOne(PSE, L)) { |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 243 | // They are in the same block, the later one will forward to the load. |
| 244 | if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store)) |
| 245 | OtherCand = &Cand; |
| 246 | } else |
| 247 | OtherCand = nullptr; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) { |
| 252 | if (LoadToSingleCand[Cand.Load] != &Cand) { |
| 253 | DEBUG(dbgs() << "Removing from candidates: \n" << Cand |
| 254 | << " The load may have multiple stores forwarding to " |
| 255 | << "it\n"); |
| 256 | return true; |
| 257 | } |
| 258 | return false; |
| 259 | }); |
| 260 | } |
| 261 | |
| 262 | /// \brief Given two pointers operations by their RuntimePointerChecking |
| 263 | /// indices, return true if they require an alias check. |
| 264 | /// |
| 265 | /// We need a check if one is a pointer for a candidate load and the other is |
| 266 | /// a pointer for a possibly intervening store. |
| 267 | bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2, |
| 268 | const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath, |
| 269 | const std::set<Value *> &CandLoadPtrs) { |
| 270 | Value *Ptr1 = |
| 271 | LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue; |
| 272 | Value *Ptr2 = |
| 273 | LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue; |
| 274 | return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) || |
| 275 | (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1))); |
| 276 | } |
| 277 | |
| 278 | /// \brief Return pointers that are possibly written to on the path from a |
| 279 | /// forwarding store to a load. |
| 280 | /// |
| 281 | /// These pointers need to be alias-checked against the forwarding candidates. |
| 282 | SmallSet<Value *, 4> findPointersWrittenOnForwardingPath( |
| 283 | const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) { |
| 284 | // From FirstStore to LastLoad neither of the elimination candidate loads |
| 285 | // should overlap with any of the stores. |
| 286 | // |
| 287 | // E.g.: |
| 288 | // |
| 289 | // st1 C[i] |
| 290 | // ld1 B[i] <-------, |
| 291 | // ld0 A[i] <----, | * LastLoad |
| 292 | // ... | | |
| 293 | // st2 E[i] | | |
| 294 | // st3 B[i+1] -- | -' * FirstStore |
| 295 | // st0 A[i+1] ---' |
| 296 | // st4 D[i] |
| 297 | // |
| 298 | // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with |
| 299 | // ld0. |
| 300 | |
| 301 | LoadInst *LastLoad = |
| 302 | std::max_element(Candidates.begin(), Candidates.end(), |
| 303 | [&](const StoreToLoadForwardingCandidate &A, |
| 304 | const StoreToLoadForwardingCandidate &B) { |
| 305 | return getInstrIndex(A.Load) < getInstrIndex(B.Load); |
| 306 | }) |
| 307 | ->Load; |
| 308 | StoreInst *FirstStore = |
| 309 | std::min_element(Candidates.begin(), Candidates.end(), |
| 310 | [&](const StoreToLoadForwardingCandidate &A, |
| 311 | const StoreToLoadForwardingCandidate &B) { |
| 312 | return getInstrIndex(A.Store) < |
| 313 | getInstrIndex(B.Store); |
| 314 | }) |
| 315 | ->Store; |
| 316 | |
| 317 | // We're looking for stores after the first forwarding store until the end |
| 318 | // of the loop, then from the beginning of the loop until the last |
| 319 | // forwarded-to load. Collect the pointer for the stores. |
| 320 | SmallSet<Value *, 4> PtrsWrittenOnFwdingPath; |
| 321 | |
| 322 | auto InsertStorePtr = [&](Instruction *I) { |
| 323 | if (auto *S = dyn_cast<StoreInst>(I)) |
| 324 | PtrsWrittenOnFwdingPath.insert(S->getPointerOperand()); |
| 325 | }; |
| 326 | const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions(); |
| 327 | std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1, |
| 328 | MemInstrs.end(), InsertStorePtr); |
| 329 | std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)], |
| 330 | InsertStorePtr); |
| 331 | |
| 332 | return PtrsWrittenOnFwdingPath; |
| 333 | } |
| 334 | |
| 335 | /// \brief Determine the pointer alias checks to prove that there are no |
| 336 | /// intervening stores. |
| 337 | SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks( |
| 338 | const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) { |
| 339 | |
| 340 | SmallSet<Value *, 4> PtrsWrittenOnFwdingPath = |
| 341 | findPointersWrittenOnForwardingPath(Candidates); |
| 342 | |
| 343 | // Collect the pointers of the candidate loads. |
| 344 | // FIXME: SmallSet does not work with std::inserter. |
| 345 | std::set<Value *> CandLoadPtrs; |
| 346 | std::transform(Candidates.begin(), Candidates.end(), |
| 347 | std::inserter(CandLoadPtrs, CandLoadPtrs.begin()), |
| 348 | std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr)); |
| 349 | |
| 350 | const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks(); |
| 351 | SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks; |
| 352 | |
| 353 | std::copy_if(AllChecks.begin(), AllChecks.end(), std::back_inserter(Checks), |
| 354 | [&](const RuntimePointerChecking::PointerCheck &Check) { |
| 355 | for (auto PtrIdx1 : Check.first->Members) |
| 356 | for (auto PtrIdx2 : Check.second->Members) |
| 357 | if (needsChecking(PtrIdx1, PtrIdx2, |
| 358 | PtrsWrittenOnFwdingPath, CandLoadPtrs)) |
| 359 | return true; |
| 360 | return false; |
| 361 | }); |
| 362 | |
| 363 | DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n"); |
| 364 | DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks)); |
| 365 | |
| 366 | return Checks; |
| 367 | } |
| 368 | |
| 369 | /// \brief Perform the transformation for a candidate. |
| 370 | void |
| 371 | propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand, |
| 372 | SCEVExpander &SEE) { |
| 373 | // |
| 374 | // loop: |
| 375 | // %x = load %gep_i |
| 376 | // = ... %x |
| 377 | // store %y, %gep_i_plus_1 |
| 378 | // |
| 379 | // => |
| 380 | // |
| 381 | // ph: |
| 382 | // %x.initial = load %gep_0 |
| 383 | // loop: |
| 384 | // %x.storeforward = phi [%x.initial, %ph] [%y, %loop] |
| 385 | // %x = load %gep_i <---- now dead |
| 386 | // = ... %x.storeforward |
| 387 | // store %y, %gep_i_plus_1 |
| 388 | |
| 389 | Value *Ptr = Cand.Load->getPointerOperand(); |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 390 | auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr)); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 391 | auto *PH = L->getLoopPreheader(); |
| 392 | Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(), |
| 393 | PH->getTerminator()); |
| 394 | Value *Initial = |
| 395 | new LoadInst(InitialPtr, "load_initial", PH->getTerminator()); |
| 396 | PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded", |
Duncan P. N. Exon Smith | 83c4b68 | 2015-11-07 00:01:16 +0000 | [diff] [blame] | 397 | &L->getHeader()->front()); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 398 | PHI->addIncoming(Initial, PH); |
| 399 | PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch()); |
| 400 | |
| 401 | Cand.Load->replaceAllUsesWith(PHI); |
| 402 | } |
| 403 | |
| 404 | /// \brief Top-level driver for each loop: find store->load forwarding |
| 405 | /// candidates, add run-time checks and perform transformation. |
| 406 | bool processLoop() { |
| 407 | DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName() |
| 408 | << "\" checking " << *L << "\n"); |
| 409 | // Look for store-to-load forwarding cases across the |
| 410 | // backedge. E.g.: |
| 411 | // |
| 412 | // loop: |
| 413 | // %x = load %gep_i |
| 414 | // = ... %x |
| 415 | // store %y, %gep_i_plus_1 |
| 416 | // |
| 417 | // => |
| 418 | // |
| 419 | // ph: |
| 420 | // %x.initial = load %gep_0 |
| 421 | // loop: |
| 422 | // %x.storeforward = phi [%x.initial, %ph] [%y, %loop] |
| 423 | // %x = load %gep_i <---- now dead |
| 424 | // = ... %x.storeforward |
| 425 | // store %y, %gep_i_plus_1 |
| 426 | |
| 427 | // First start with store->load dependences. |
| 428 | auto StoreToLoadDependences = findStoreToLoadDependences(LAI); |
| 429 | if (StoreToLoadDependences.empty()) |
| 430 | return false; |
| 431 | |
| 432 | // Generate an index for each load and store according to the original |
| 433 | // program order. This will be used later. |
| 434 | InstOrder = LAI.getDepChecker().generateInstructionOrderMap(); |
| 435 | |
| 436 | // To keep things simple for now, remove those where the load is potentially |
| 437 | // fed by multiple stores. |
| 438 | removeDependencesFromMultipleStores(StoreToLoadDependences); |
| 439 | if (StoreToLoadDependences.empty()) |
| 440 | return false; |
| 441 | |
| 442 | // Filter the candidates further. |
| 443 | SmallVector<StoreToLoadForwardingCandidate, 4> Candidates; |
| 444 | unsigned NumForwarding = 0; |
| 445 | for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) { |
| 446 | DEBUG(dbgs() << "Candidate " << Cand); |
Adam Nemet | 83be06e | 2016-02-29 22:53:59 +0000 | [diff] [blame] | 447 | |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 448 | // Make sure that the stored values is available everywhere in the loop in |
| 449 | // the next iteration. |
| 450 | if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT)) |
| 451 | continue; |
| 452 | |
| 453 | // Check whether the SCEV difference is the same as the induction step, |
| 454 | // thus we load the value in the next iteration. |
Adam Nemet | 660748c | 2016-03-09 20:47:55 +0000 | [diff] [blame] | 455 | if (!Cand.isDependenceDistanceOfOne(PSE, L)) |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 456 | continue; |
| 457 | |
| 458 | ++NumForwarding; |
| 459 | DEBUG(dbgs() |
| 460 | << NumForwarding |
| 461 | << ". Valid store-to-load forwarding across the loop backedge\n"); |
| 462 | Candidates.push_back(Cand); |
| 463 | } |
| 464 | if (Candidates.empty()) |
| 465 | return false; |
| 466 | |
| 467 | // Check intervening may-alias stores. These need runtime checks for alias |
| 468 | // disambiguation. |
| 469 | SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks = |
| 470 | collectMemchecks(Candidates); |
| 471 | |
| 472 | // Too many checks are likely to outweigh the benefits of forwarding. |
| 473 | if (Checks.size() > Candidates.size() * CheckPerElim) { |
| 474 | DEBUG(dbgs() << "Too many run-time checks needed.\n"); |
| 475 | return false; |
| 476 | } |
| 477 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 478 | if (LAI.PSE.getUnionPredicate().getComplexity() > |
| 479 | LoadElimSCEVCheckThreshold) { |
Silviu Baranga | 2910a4f | 2015-11-09 13:26:09 +0000 | [diff] [blame] | 480 | DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n"); |
| 481 | return false; |
| 482 | } |
| 483 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 484 | if (!Checks.empty() || !LAI.PSE.getUnionPredicate().isAlwaysTrue()) { |
Adam Nemet | 9455c1d | 2016-02-05 01:14:05 +0000 | [diff] [blame] | 485 | if (L->getHeader()->getParent()->optForSize()) { |
| 486 | DEBUG(dbgs() << "Versioning is needed but not allowed when optimizing " |
| 487 | "for size.\n"); |
| 488 | return false; |
| 489 | } |
| 490 | |
| 491 | // Point of no-return, start the transformation. First, version the loop |
| 492 | // if necessary. |
| 493 | |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 494 | LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false); |
Silviu Baranga | 2910a4f | 2015-11-09 13:26:09 +0000 | [diff] [blame] | 495 | LV.setAliasChecks(std::move(Checks)); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 496 | LV.setSCEVChecks(LAI.PSE.getUnionPredicate()); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 497 | LV.versionLoop(); |
| 498 | } |
| 499 | |
| 500 | // Next, propagate the value stored by the store to the users of the load. |
| 501 | // Also for the first iteration, generate the initial value of the load. |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 502 | SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(), |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 503 | "storeforward"); |
| 504 | for (const auto &Cand : Candidates) |
| 505 | propagateStoredValueToLoadUsers(Cand, SEE); |
| 506 | NumLoopLoadEliminted += NumForwarding; |
| 507 | |
| 508 | return true; |
| 509 | } |
| 510 | |
| 511 | private: |
| 512 | Loop *L; |
| 513 | |
| 514 | /// \brief Maps the load/store instructions to their index according to |
| 515 | /// program order. |
| 516 | DenseMap<Instruction *, unsigned> InstOrder; |
| 517 | |
| 518 | // Analyses used. |
| 519 | LoopInfo *LI; |
| 520 | const LoopAccessInfo &LAI; |
| 521 | DominatorTree *DT; |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 522 | PredicatedScalarEvolution PSE; |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 523 | }; |
| 524 | |
| 525 | /// \brief The pass. Most of the work is delegated to the per-loop |
| 526 | /// LoadEliminationForLoop class. |
| 527 | class LoopLoadElimination : public FunctionPass { |
| 528 | public: |
| 529 | LoopLoadElimination() : FunctionPass(ID) { |
| 530 | initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry()); |
| 531 | } |
| 532 | |
| 533 | bool runOnFunction(Function &F) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 534 | if (skipFunction(F)) |
| 535 | return false; |
| 536 | |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 537 | auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 538 | auto *LAA = &getAnalysis<LoopAccessAnalysis>(); |
| 539 | auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 540 | |
| 541 | // Build up a worklist of inner-loops to vectorize. This is necessary as the |
| 542 | // act of distributing a loop creates new loops and can invalidate iterators |
| 543 | // across the loops. |
| 544 | SmallVector<Loop *, 8> Worklist; |
| 545 | |
| 546 | for (Loop *TopLevelLoop : *LI) |
| 547 | for (Loop *L : depth_first(TopLevelLoop)) |
| 548 | // We only handle inner-most loops. |
| 549 | if (L->empty()) |
| 550 | Worklist.push_back(L); |
| 551 | |
| 552 | // Now walk the identified inner loops. |
| 553 | bool Changed = false; |
| 554 | for (Loop *L : Worklist) { |
| 555 | const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap()); |
| 556 | // The actual work is performed by LoadEliminationForLoop. |
Silviu Baranga | 86de80d | 2015-12-10 11:07:18 +0000 | [diff] [blame] | 557 | LoadEliminationForLoop LEL(L, LI, LAI, DT); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 558 | Changed |= LEL.processLoop(); |
| 559 | } |
| 560 | |
| 561 | // Process each loop nest in the function. |
| 562 | return Changed; |
| 563 | } |
| 564 | |
| 565 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Adam Nemet | efb2341 | 2016-03-10 23:54:39 +0000 | [diff] [blame] | 566 | AU.addRequiredID(LoopSimplifyID); |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 567 | AU.addRequired<LoopInfoWrapperPass>(); |
| 568 | AU.addPreserved<LoopInfoWrapperPass>(); |
| 569 | AU.addRequired<LoopAccessAnalysis>(); |
| 570 | AU.addRequired<ScalarEvolutionWrapperPass>(); |
| 571 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 572 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 573 | } |
| 574 | |
| 575 | static char ID; |
| 576 | }; |
| 577 | } |
| 578 | |
| 579 | char LoopLoadElimination::ID; |
| 580 | static const char LLE_name[] = "Loop Load Elimination"; |
| 581 | |
| 582 | INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false) |
| 583 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 584 | INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis) |
| 585 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 586 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) |
Adam Nemet | efb2341 | 2016-03-10 23:54:39 +0000 | [diff] [blame] | 587 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
Adam Nemet | e54a4fa | 2015-11-03 23:50:08 +0000 | [diff] [blame] | 588 | INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false) |
| 589 | |
| 590 | namespace llvm { |
| 591 | FunctionPass *createLoopLoadEliminationPass() { |
| 592 | return new LoopLoadElimination(); |
| 593 | } |
| 594 | } |