blob: 8fb580183e307a0e0117af70f466aec1199b2af1 [file] [log] [blame]
Adam Nemete54a4fa2015-11-03 23:50:08 +00001//===- 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
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DepthFirstIterator.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000028#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000029#include "llvm/ADT/STLExtras.h"
Eli Friedman02d48be2016-09-16 17:58:07 +000030#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000031#include "llvm/Analysis/LoopAccessAnalysis.h"
32#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000033#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000034#include "llvm/Analysis/ScalarEvolutionExpander.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000035#include "llvm/Analysis/ScalarEvolutionExpressions.h"
36#include "llvm/IR/DataLayout.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000037#include "llvm/IR/Dominators.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000038#include "llvm/IR/Instructions.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000039#include "llvm/IR/Module.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000042#include "llvm/Pass.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000043#include "llvm/Support/Casting.h"
44#include "llvm/Support/CommandLine.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000045#include "llvm/Support/Debug.h"
Adam Nemetefb23412016-03-10 23:54:39 +000046#include "llvm/Transforms/Scalar.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000047#include "llvm/Transforms/Utils/LoopVersioning.h"
48#include <forward_list>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000049#include <cassert>
50#include <algorithm>
51#include <set>
52#include <tuple>
53#include <utility>
Adam Nemete54a4fa2015-11-03 23:50:08 +000054
55#define LLE_OPTION "loop-load-elim"
56#define DEBUG_TYPE LLE_OPTION
57
58using namespace llvm;
59
60static cl::opt<unsigned> CheckPerElim(
61 "runtime-check-per-loop-load-elim", cl::Hidden,
62 cl::desc("Max number of memchecks allowed per eliminated load on average"),
63 cl::init(1));
64
Silviu Baranga2910a4f2015-11-09 13:26:09 +000065static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
66 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
67 cl::desc("The maximum number of SCEV checks allowed for Loop "
68 "Load Elimination"));
69
Adam Nemete54a4fa2015-11-03 23:50:08 +000070STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
71
72namespace {
73
74/// \brief Represent a store-to-forwarding candidate.
75struct StoreToLoadForwardingCandidate {
76 LoadInst *Load;
77 StoreInst *Store;
78
79 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
80 : Load(Load), Store(Store) {}
81
82 /// \brief Return true if the dependence from the store to the load has a
83 /// distance of one. E.g. A[i+1] = A[i]
Adam Nemet660748c2016-03-09 20:47:55 +000084 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
85 Loop *L) const {
Adam Nemete54a4fa2015-11-03 23:50:08 +000086 Value *LoadPtr = Load->getPointerOperand();
87 Value *StorePtr = Store->getPointerOperand();
88 Type *LoadPtrType = LoadPtr->getType();
Adam Nemete54a4fa2015-11-03 23:50:08 +000089 Type *LoadType = LoadPtrType->getPointerElementType();
90
91 assert(LoadPtrType->getPointerAddressSpace() ==
Adam Nemet7c94c9b2015-11-04 00:10:33 +000092 StorePtr->getType()->getPointerAddressSpace() &&
93 LoadType == StorePtr->getType()->getPointerElementType() &&
Adam Nemete54a4fa2015-11-03 23:50:08 +000094 "Should be a known dependence");
95
Adam Nemet660748c2016-03-09 20:47:55 +000096 // Currently we only support accesses with unit stride. FIXME: we should be
97 // able to handle non unit stirde as well as long as the stride is equal to
98 // the dependence distance.
Denis Zobnin15d1e642016-05-10 05:55:16 +000099 if (getPtrStride(PSE, LoadPtr, L) != 1 ||
100 getPtrStride(PSE, StorePtr, L) != 1)
Adam Nemet660748c2016-03-09 20:47:55 +0000101 return false;
102
Adam Nemete54a4fa2015-11-03 23:50:08 +0000103 auto &DL = Load->getParent()->getModule()->getDataLayout();
104 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
105
Silviu Baranga86de80d2015-12-10 11:07:18 +0000106 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
107 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000108
109 // We don't need to check non-wrapping here because forward/backward
110 // dependence wouldn't be valid if these weren't monotonic accesses.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000111 auto *Dist = cast<SCEVConstant>(
112 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000113 const APInt &Val = Dist->getAPInt();
Adam Nemet660748c2016-03-09 20:47:55 +0000114 return Val == TypeByteSize;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000115 }
116
117 Value *getLoadPtr() const { return Load->getPointerOperand(); }
118
119#ifndef NDEBUG
120 friend raw_ostream &operator<<(raw_ostream &OS,
121 const StoreToLoadForwardingCandidate &Cand) {
122 OS << *Cand.Store << " -->\n";
123 OS.indent(2) << *Cand.Load << "\n";
124 return OS;
125 }
126#endif
127};
128
129/// \brief Check if the store dominates all latches, so as long as there is no
130/// intervening store this value will be loaded in the next iteration.
131bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
132 DominatorTree *DT) {
133 SmallVector<BasicBlock *, 8> Latches;
134 L->getLoopLatches(Latches);
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000135 return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
David Majnemer0a16c222016-08-11 21:15:00 +0000136 return DT->dominates(StoreBlock, Latch);
137 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000138}
139
Adam Nemetbd861ac2016-06-28 04:02:47 +0000140/// \brief Return true if the load is not executed on all paths in the loop.
141static bool isLoadConditional(LoadInst *Load, Loop *L) {
142 return Load->getParent() != L->getHeader();
143}
144
Adam Nemete54a4fa2015-11-03 23:50:08 +0000145/// \brief The per-loop class that does most of the work.
146class LoadEliminationForLoop {
147public:
148 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
Silviu Baranga86de80d2015-12-10 11:07:18 +0000149 DominatorTree *DT)
Xinliang David Li94734ee2016-07-01 05:59:55 +0000150 : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.getPSE()) {}
Adam Nemete54a4fa2015-11-03 23:50:08 +0000151
152 /// \brief Look through the loop-carried and loop-independent dependences in
153 /// this loop and find store->load dependences.
154 ///
155 /// Note that no candidate is returned if LAA has failed to analyze the loop
156 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
157 std::forward_list<StoreToLoadForwardingCandidate>
158 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
159 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
160
161 const auto *Deps = LAI.getDepChecker().getDependences();
162 if (!Deps)
163 return Candidates;
164
165 // Find store->load dependences (consequently true dep). Both lexically
166 // forward and backward dependences qualify. Disqualify loads that have
167 // other unknown dependences.
168
169 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence;
170
171 for (const auto &Dep : *Deps) {
172 Instruction *Source = Dep.getSource(LAI);
173 Instruction *Destination = Dep.getDestination(LAI);
174
175 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
176 if (isa<LoadInst>(Source))
177 LoadsWithUnknownDepedence.insert(Source);
178 if (isa<LoadInst>(Destination))
179 LoadsWithUnknownDepedence.insert(Destination);
180 continue;
181 }
182
183 if (Dep.isBackward())
184 // Note that the designations source and destination follow the program
185 // order, i.e. source is always first. (The direction is given by the
186 // DepType.)
187 std::swap(Source, Destination);
188 else
189 assert(Dep.isForward() && "Needs to be a forward dependence");
190
191 auto *Store = dyn_cast<StoreInst>(Source);
192 if (!Store)
193 continue;
194 auto *Load = dyn_cast<LoadInst>(Destination);
195 if (!Load)
196 continue;
Adam Nemet7aba60c2016-03-24 17:59:26 +0000197
198 // Only progagate the value if they are of the same type.
199 if (Store->getPointerOperand()->getType() !=
200 Load->getPointerOperand()->getType())
201 continue;
202
Adam Nemete54a4fa2015-11-03 23:50:08 +0000203 Candidates.emplace_front(Load, Store);
204 }
205
206 if (!LoadsWithUnknownDepedence.empty())
207 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
208 return LoadsWithUnknownDepedence.count(C.Load);
209 });
210
211 return Candidates;
212 }
213
214 /// \brief Return the index of the instruction according to program order.
215 unsigned getInstrIndex(Instruction *Inst) {
216 auto I = InstOrder.find(Inst);
217 assert(I != InstOrder.end() && "No index for instruction");
218 return I->second;
219 }
220
221 /// \brief If a load has multiple candidates associated (i.e. different
222 /// stores), it means that it could be forwarding from multiple stores
223 /// depending on control flow. Remove these candidates.
224 ///
225 /// Here, we rely on LAA to include the relevant loop-independent dependences.
226 /// LAA is known to omit these in the very simple case when the read and the
227 /// write within an alias set always takes place using the *same* pointer.
228 ///
229 /// However, we know that this is not the case here, i.e. we can rely on LAA
230 /// to provide us with loop-independent dependences for the cases we're
231 /// interested. Consider the case for example where a loop-independent
232 /// dependece S1->S2 invalidates the forwarding S3->S2.
233 ///
234 /// A[i] = ... (S1)
235 /// ... = A[i] (S2)
236 /// A[i+1] = ... (S3)
237 ///
238 /// LAA will perform dependence analysis here because there are two
239 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
240 void removeDependencesFromMultipleStores(
241 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
242 // If Store is nullptr it means that we have multiple stores forwarding to
243 // this store.
244 typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>
245 LoadToSingleCandT;
246 LoadToSingleCandT LoadToSingleCand;
247
248 for (const auto &Cand : Candidates) {
249 bool NewElt;
250 LoadToSingleCandT::iterator Iter;
251
252 std::tie(Iter, NewElt) =
253 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
254 if (!NewElt) {
255 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
256 // Already multiple stores forward to this load.
257 if (OtherCand == nullptr)
258 continue;
259
Adam Nemetefc091f2016-02-29 23:21:12 +0000260 // Handle the very basic case when the two stores are in the same block
261 // so deciding which one forwards is easy. The later one forwards as
262 // long as they both have a dependence distance of one to the load.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000263 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Adam Nemet660748c2016-03-09 20:47:55 +0000264 Cand.isDependenceDistanceOfOne(PSE, L) &&
265 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000266 // They are in the same block, the later one will forward to the load.
267 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
268 OtherCand = &Cand;
269 } else
270 OtherCand = nullptr;
271 }
272 }
273
274 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
275 if (LoadToSingleCand[Cand.Load] != &Cand) {
276 DEBUG(dbgs() << "Removing from candidates: \n" << Cand
277 << " The load may have multiple stores forwarding to "
278 << "it\n");
279 return true;
280 }
281 return false;
282 });
283 }
284
285 /// \brief Given two pointers operations by their RuntimePointerChecking
286 /// indices, return true if they require an alias check.
287 ///
288 /// We need a check if one is a pointer for a candidate load and the other is
289 /// a pointer for a possibly intervening store.
290 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
291 const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath,
292 const std::set<Value *> &CandLoadPtrs) {
293 Value *Ptr1 =
294 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
295 Value *Ptr2 =
296 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
297 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
298 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
299 }
300
301 /// \brief Return pointers that are possibly written to on the path from a
302 /// forwarding store to a load.
303 ///
304 /// These pointers need to be alias-checked against the forwarding candidates.
305 SmallSet<Value *, 4> findPointersWrittenOnForwardingPath(
306 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
307 // From FirstStore to LastLoad neither of the elimination candidate loads
308 // should overlap with any of the stores.
309 //
310 // E.g.:
311 //
312 // st1 C[i]
313 // ld1 B[i] <-------,
314 // ld0 A[i] <----, | * LastLoad
315 // ... | |
316 // st2 E[i] | |
317 // st3 B[i+1] -- | -' * FirstStore
318 // st0 A[i+1] ---'
319 // st4 D[i]
320 //
321 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
322 // ld0.
323
324 LoadInst *LastLoad =
325 std::max_element(Candidates.begin(), Candidates.end(),
326 [&](const StoreToLoadForwardingCandidate &A,
327 const StoreToLoadForwardingCandidate &B) {
328 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
329 })
330 ->Load;
331 StoreInst *FirstStore =
332 std::min_element(Candidates.begin(), Candidates.end(),
333 [&](const StoreToLoadForwardingCandidate &A,
334 const StoreToLoadForwardingCandidate &B) {
335 return getInstrIndex(A.Store) <
336 getInstrIndex(B.Store);
337 })
338 ->Store;
339
340 // We're looking for stores after the first forwarding store until the end
341 // of the loop, then from the beginning of the loop until the last
342 // forwarded-to load. Collect the pointer for the stores.
343 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath;
344
345 auto InsertStorePtr = [&](Instruction *I) {
346 if (auto *S = dyn_cast<StoreInst>(I))
347 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
348 };
349 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
350 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
351 MemInstrs.end(), InsertStorePtr);
352 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
353 InsertStorePtr);
354
355 return PtrsWrittenOnFwdingPath;
356 }
357
358 /// \brief Determine the pointer alias checks to prove that there are no
359 /// intervening stores.
360 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
361 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
362
363 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath =
364 findPointersWrittenOnForwardingPath(Candidates);
365
366 // Collect the pointers of the candidate loads.
367 // FIXME: SmallSet does not work with std::inserter.
368 std::set<Value *> CandLoadPtrs;
David Majnemer2d006e72016-08-12 04:32:42 +0000369 transform(Candidates,
Adam Nemete54a4fa2015-11-03 23:50:08 +0000370 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
371 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
372
373 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
374 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
375
376 std::copy_if(AllChecks.begin(), AllChecks.end(), std::back_inserter(Checks),
377 [&](const RuntimePointerChecking::PointerCheck &Check) {
378 for (auto PtrIdx1 : Check.first->Members)
379 for (auto PtrIdx2 : Check.second->Members)
380 if (needsChecking(PtrIdx1, PtrIdx2,
381 PtrsWrittenOnFwdingPath, CandLoadPtrs))
382 return true;
383 return false;
384 });
385
386 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n");
387 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
388
389 return Checks;
390 }
391
392 /// \brief Perform the transformation for a candidate.
393 void
394 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
395 SCEVExpander &SEE) {
396 //
397 // loop:
398 // %x = load %gep_i
399 // = ... %x
400 // store %y, %gep_i_plus_1
401 //
402 // =>
403 //
404 // ph:
405 // %x.initial = load %gep_0
406 // loop:
407 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
408 // %x = load %gep_i <---- now dead
409 // = ... %x.storeforward
410 // store %y, %gep_i_plus_1
411
412 Value *Ptr = Cand.Load->getPointerOperand();
Silviu Baranga86de80d2015-12-10 11:07:18 +0000413 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000414 auto *PH = L->getLoopPreheader();
415 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
416 PH->getTerminator());
417 Value *Initial =
Mehdi Amini27d224f2017-01-06 21:06:51 +0000418 new LoadInst(InitialPtr, "load_initial", /* isVolatile */ false,
419 Cand.Load->getAlignment(), PH->getTerminator());
420
Adam Nemete54a4fa2015-11-03 23:50:08 +0000421 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000422 &L->getHeader()->front());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000423 PHI->addIncoming(Initial, PH);
424 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
425
426 Cand.Load->replaceAllUsesWith(PHI);
427 }
428
429 /// \brief Top-level driver for each loop: find store->load forwarding
430 /// candidates, add run-time checks and perform transformation.
431 bool processLoop() {
432 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
433 << "\" checking " << *L << "\n");
434 // Look for store-to-load forwarding cases across the
435 // backedge. E.g.:
436 //
437 // loop:
438 // %x = load %gep_i
439 // = ... %x
440 // store %y, %gep_i_plus_1
441 //
442 // =>
443 //
444 // ph:
445 // %x.initial = load %gep_0
446 // loop:
447 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
448 // %x = load %gep_i <---- now dead
449 // = ... %x.storeforward
450 // store %y, %gep_i_plus_1
451
452 // First start with store->load dependences.
453 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
454 if (StoreToLoadDependences.empty())
455 return false;
456
457 // Generate an index for each load and store according to the original
458 // program order. This will be used later.
459 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
460
461 // To keep things simple for now, remove those where the load is potentially
462 // fed by multiple stores.
463 removeDependencesFromMultipleStores(StoreToLoadDependences);
464 if (StoreToLoadDependences.empty())
465 return false;
466
467 // Filter the candidates further.
468 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
469 unsigned NumForwarding = 0;
470 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
471 DEBUG(dbgs() << "Candidate " << Cand);
Adam Nemet83be06e2016-02-29 22:53:59 +0000472
Adam Nemete54a4fa2015-11-03 23:50:08 +0000473 // Make sure that the stored values is available everywhere in the loop in
474 // the next iteration.
475 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
476 continue;
477
Adam Nemetbd861ac2016-06-28 04:02:47 +0000478 // If the load is conditional we can't hoist its 0-iteration instance to
479 // the preheader because that would make it unconditional. Thus we would
480 // access a memory location that the original loop did not access.
481 if (isLoadConditional(Cand.Load, L))
482 continue;
483
Adam Nemete54a4fa2015-11-03 23:50:08 +0000484 // Check whether the SCEV difference is the same as the induction step,
485 // thus we load the value in the next iteration.
Adam Nemet660748c2016-03-09 20:47:55 +0000486 if (!Cand.isDependenceDistanceOfOne(PSE, L))
Adam Nemete54a4fa2015-11-03 23:50:08 +0000487 continue;
488
489 ++NumForwarding;
490 DEBUG(dbgs()
491 << NumForwarding
492 << ". Valid store-to-load forwarding across the loop backedge\n");
493 Candidates.push_back(Cand);
494 }
495 if (Candidates.empty())
496 return false;
497
498 // Check intervening may-alias stores. These need runtime checks for alias
499 // disambiguation.
500 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
501 collectMemchecks(Candidates);
502
503 // Too many checks are likely to outweigh the benefits of forwarding.
504 if (Checks.size() > Candidates.size() * CheckPerElim) {
505 DEBUG(dbgs() << "Too many run-time checks needed.\n");
506 return false;
507 }
508
Xinliang David Li94734ee2016-07-01 05:59:55 +0000509 if (LAI.getPSE().getUnionPredicate().getComplexity() >
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000510 LoadElimSCEVCheckThreshold) {
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000511 DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
512 return false;
513 }
514
Xinliang David Li94734ee2016-07-01 05:59:55 +0000515 if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
Adam Nemet9455c1d2016-02-05 01:14:05 +0000516 if (L->getHeader()->getParent()->optForSize()) {
517 DEBUG(dbgs() << "Versioning is needed but not allowed when optimizing "
518 "for size.\n");
519 return false;
520 }
521
Florian Hahn2e032132016-12-19 17:13:37 +0000522 if (!L->isLoopSimplifyForm()) {
523 DEBUG(dbgs() << "Loop is not is loop-simplify form");
524 return false;
525 }
526
Adam Nemet9455c1d2016-02-05 01:14:05 +0000527 // Point of no-return, start the transformation. First, version the loop
528 // if necessary.
529
Silviu Baranga86de80d2015-12-10 11:07:18 +0000530 LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000531 LV.setAliasChecks(std::move(Checks));
Xinliang David Li94734ee2016-07-01 05:59:55 +0000532 LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000533 LV.versionLoop();
534 }
535
536 // Next, propagate the value stored by the store to the users of the load.
537 // Also for the first iteration, generate the initial value of the load.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000538 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
Adam Nemete54a4fa2015-11-03 23:50:08 +0000539 "storeforward");
540 for (const auto &Cand : Candidates)
541 propagateStoredValueToLoadUsers(Cand, SEE);
542 NumLoopLoadEliminted += NumForwarding;
543
544 return true;
545 }
546
547private:
548 Loop *L;
549
550 /// \brief Maps the load/store instructions to their index according to
551 /// program order.
552 DenseMap<Instruction *, unsigned> InstOrder;
553
554 // Analyses used.
555 LoopInfo *LI;
556 const LoopAccessInfo &LAI;
557 DominatorTree *DT;
Silviu Baranga86de80d2015-12-10 11:07:18 +0000558 PredicatedScalarEvolution PSE;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000559};
560
561/// \brief The pass. Most of the work is delegated to the per-loop
562/// LoadEliminationForLoop class.
563class LoopLoadElimination : public FunctionPass {
564public:
565 LoopLoadElimination() : FunctionPass(ID) {
566 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
567 }
568
569 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000570 if (skipFunction(F))
571 return false;
572
Adam Nemete54a4fa2015-11-03 23:50:08 +0000573 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000574 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000575 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000576
577 // Build up a worklist of inner-loops to vectorize. This is necessary as the
578 // act of distributing a loop creates new loops and can invalidate iterators
579 // across the loops.
580 SmallVector<Loop *, 8> Worklist;
581
582 for (Loop *TopLevelLoop : *LI)
583 for (Loop *L : depth_first(TopLevelLoop))
584 // We only handle inner-most loops.
585 if (L->empty())
586 Worklist.push_back(L);
587
588 // Now walk the identified inner loops.
589 bool Changed = false;
590 for (Loop *L : Worklist) {
Adam Nemetbdbc5222016-06-16 08:26:56 +0000591 const LoopAccessInfo &LAI = LAA->getInfo(L);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000592 // The actual work is performed by LoadEliminationForLoop.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000593 LoadEliminationForLoop LEL(L, LI, LAI, DT);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000594 Changed |= LEL.processLoop();
595 }
596
597 // Process each loop nest in the function.
598 return Changed;
599 }
600
601 void getAnalysisUsage(AnalysisUsage &AU) const override {
Adam Nemetefb23412016-03-10 23:54:39 +0000602 AU.addRequiredID(LoopSimplifyID);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000603 AU.addRequired<LoopInfoWrapperPass>();
604 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000605 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000606 AU.addRequired<ScalarEvolutionWrapperPass>();
607 AU.addRequired<DominatorTreeWrapperPass>();
608 AU.addPreserved<DominatorTreeWrapperPass>();
Eli Friedman02d48be2016-09-16 17:58:07 +0000609 AU.addPreserved<GlobalsAAWrapperPass>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000610 }
611
612 static char ID;
613};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000614
615} // end anonymous namespace
Adam Nemete54a4fa2015-11-03 23:50:08 +0000616
617char LoopLoadElimination::ID;
618static const char LLE_name[] = "Loop Load Elimination";
619
620INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
621INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000622INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000623INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
624INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemetefb23412016-03-10 23:54:39 +0000625INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000626INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
627
628namespace llvm {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000629
Adam Nemete54a4fa2015-11-03 23:50:08 +0000630FunctionPass *createLoopLoadEliminationPass() {
631 return new LoopLoadElimination();
632}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000633
634} // end namespace llvm