1 //===- LoadStoreOpt.cpp ----------- Generic memory optimizations -*- C++ -*-==//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the LoadStoreOpt optimization pass.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/LoadStoreOpt.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/MemoryLocation.h"
16 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
17 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
18 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
20 #include "llvm/CodeGen/GlobalISel/Utils.h"
21 #include "llvm/CodeGen/LowLevelType.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Register.h"
29 #include "llvm/CodeGen/TargetLowering.h"
30 #include "llvm/CodeGen/TargetOpcodes.h"
31 #include "llvm/IR/DebugInfoMetadata.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Support/AtomicOrdering.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <algorithm>
39 
40 #define DEBUG_TYPE "loadstore-opt"
41 
42 using namespace llvm;
43 using namespace ore;
44 using namespace MIPatternMatch;
45 
46 STATISTIC(NumStoresMerged, "Number of stores merged");
47 
48 const unsigned MaxStoreSizeToForm = 128;
49 
50 char LoadStoreOpt::ID = 0;
51 INITIALIZE_PASS_BEGIN(LoadStoreOpt, DEBUG_TYPE, "Generic memory optimizations",
52                       false, false)
53 INITIALIZE_PASS_END(LoadStoreOpt, DEBUG_TYPE, "Generic memory optimizations",
54                     false, false)
55 
56 LoadStoreOpt::LoadStoreOpt(std::function<bool(const MachineFunction &)> F)
57     : MachineFunctionPass(ID), DoNotRunPass(F) {}
58 
59 LoadStoreOpt::LoadStoreOpt()
60     : LoadStoreOpt([](const MachineFunction &) { return false; }) {}
61 
62 void LoadStoreOpt::init(MachineFunction &MF) {
63   this->MF = &MF;
64   MRI = &MF.getRegInfo();
65   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
66   TLI = MF.getSubtarget().getTargetLowering();
67   LI = MF.getSubtarget().getLegalizerInfo();
68   Builder.setMF(MF);
69   IsPreLegalizer = !MF.getProperties().hasProperty(
70       MachineFunctionProperties::Property::Legalized);
71   InstsToErase.clear();
72 }
73 
74 void LoadStoreOpt::getAnalysisUsage(AnalysisUsage &AU) const {
75   AU.addRequired<AAResultsWrapperPass>();
76   getSelectionDAGFallbackAnalysisUsage(AU);
77   MachineFunctionPass::getAnalysisUsage(AU);
78 }
79 
80 BaseIndexOffset GISelAddressing::getPointerInfo(Register Ptr,
81                                                 MachineRegisterInfo &MRI) {
82   BaseIndexOffset Info;
83   Register PtrAddRHS;
84   if (!mi_match(Ptr, MRI, m_GPtrAdd(m_Reg(Info.BaseReg), m_Reg(PtrAddRHS)))) {
85     Info.BaseReg = Ptr;
86     Info.IndexReg = Register();
87     Info.IsIndexSignExt = false;
88     return Info;
89   }
90 
91   auto RHSCst = getIConstantVRegValWithLookThrough(PtrAddRHS, MRI);
92   if (RHSCst)
93     Info.Offset = RHSCst->Value.getSExtValue();
94 
95   // Just recognize a simple case for now. In future we'll need to match
96   // indexing patterns for base + index + constant.
97   Info.IndexReg = PtrAddRHS;
98   Info.IsIndexSignExt = false;
99   return Info;
100 }
101 
102 bool GISelAddressing::aliasIsKnownForLoadStore(const MachineInstr &MI1,
103                                                const MachineInstr &MI2,
104                                                bool &IsAlias,
105                                                MachineRegisterInfo &MRI) {
106   auto *LdSt1 = dyn_cast<GLoadStore>(&MI1);
107   auto *LdSt2 = dyn_cast<GLoadStore>(&MI2);
108   if (!LdSt1 || !LdSt2)
109     return false;
110 
111   BaseIndexOffset BasePtr0 = getPointerInfo(LdSt1->getPointerReg(), MRI);
112   BaseIndexOffset BasePtr1 = getPointerInfo(LdSt2->getPointerReg(), MRI);
113 
114   if (!BasePtr0.BaseReg.isValid() || !BasePtr1.BaseReg.isValid())
115     return false;
116 
117   int64_t Size1 = LdSt1->getMemSize();
118   int64_t Size2 = LdSt2->getMemSize();
119 
120   int64_t PtrDiff;
121   if (BasePtr0.BaseReg == BasePtr1.BaseReg) {
122     PtrDiff = BasePtr1.Offset - BasePtr0.Offset;
123     // If the size of memory access is unknown, do not use it to do analysis.
124     // One example of unknown size memory access is to load/store scalable
125     // vector objects on the stack.
126     // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
127     // following situations arise:
128     if (PtrDiff >= 0 &&
129         Size1 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
130       // [----BasePtr0----]
131       //                         [---BasePtr1--]
132       // ========PtrDiff========>
133       IsAlias = !(Size1 <= PtrDiff);
134       return true;
135     }
136     if (PtrDiff < 0 &&
137         Size2 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
138       //                     [----BasePtr0----]
139       // [---BasePtr1--]
140       // =====(-PtrDiff)====>
141       IsAlias = !((PtrDiff + Size2) <= 0);
142       return true;
143     }
144     return false;
145   }
146 
147   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
148   // able to calculate their relative offset if at least one arises
149   // from an alloca. However, these allocas cannot overlap and we
150   // can infer there is no alias.
151   auto *Base0Def = getDefIgnoringCopies(BasePtr0.BaseReg, MRI);
152   auto *Base1Def = getDefIgnoringCopies(BasePtr1.BaseReg, MRI);
153   if (!Base0Def || !Base1Def)
154     return false; // Couldn't tell anything.
155 
156 
157   if (Base0Def->getOpcode() != Base1Def->getOpcode())
158     return false;
159 
160   if (Base0Def->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
161     MachineFrameInfo &MFI = Base0Def->getMF()->getFrameInfo();
162     // If the bases have the same frame index but we couldn't find a
163     // constant offset, (indices are different) be conservative.
164     if (Base0Def != Base1Def &&
165         (!MFI.isFixedObjectIndex(Base0Def->getOperand(1).getIndex()) ||
166          !MFI.isFixedObjectIndex(Base1Def->getOperand(1).getIndex()))) {
167       IsAlias = false;
168       return true;
169     }
170   }
171 
172   // This implementation is a lot more primitive than the SDAG one for now.
173   // FIXME: what about constant pools?
174   if (Base0Def->getOpcode() == TargetOpcode::G_GLOBAL_VALUE) {
175     auto GV0 = Base0Def->getOperand(1).getGlobal();
176     auto GV1 = Base1Def->getOperand(1).getGlobal();
177     if (GV0 != GV1) {
178       IsAlias = false;
179       return true;
180     }
181   }
182 
183   // Can't tell anything about aliasing.
184   return false;
185 }
186 
187 bool GISelAddressing::instMayAlias(const MachineInstr &MI,
188                                    const MachineInstr &Other,
189                                    MachineRegisterInfo &MRI,
190                                    AliasAnalysis *AA) {
191   struct MemUseCharacteristics {
192     bool IsVolatile;
193     bool IsAtomic;
194     Register BasePtr;
195     int64_t Offset;
196     uint64_t NumBytes;
197     MachineMemOperand *MMO;
198   };
199 
200   auto getCharacteristics =
201       [&](const MachineInstr *MI) -> MemUseCharacteristics {
202     if (const auto *LS = dyn_cast<GLoadStore>(MI)) {
203       Register BaseReg;
204       int64_t Offset = 0;
205       // No pre/post-inc addressing modes are considered here, unlike in SDAG.
206       if (!mi_match(LS->getPointerReg(), MRI,
207                     m_GPtrAdd(m_Reg(BaseReg), m_ICst(Offset)))) {
208         BaseReg = LS->getPointerReg();
209         Offset = 0;
210       }
211 
212       uint64_t Size = MemoryLocation::getSizeOrUnknown(
213           LS->getMMO().getMemoryType().getSizeInBytes());
214       return {LS->isVolatile(),       LS->isAtomic(),          BaseReg,
215               Offset /*base offset*/, Size, &LS->getMMO()};
216     }
217     // FIXME: support recognizing lifetime instructions.
218     // Default.
219     return {false /*isvolatile*/,
220             /*isAtomic*/ false,          Register(),
221             (int64_t)0 /*offset*/,       0 /*size*/,
222             (MachineMemOperand *)nullptr};
223   };
224   MemUseCharacteristics MUC0 = getCharacteristics(&MI),
225                         MUC1 = getCharacteristics(&Other);
226 
227   // If they are to the same address, then they must be aliases.
228   if (MUC0.BasePtr.isValid() && MUC0.BasePtr == MUC1.BasePtr &&
229       MUC0.Offset == MUC1.Offset)
230     return true;
231 
232   // If they are both volatile then they cannot be reordered.
233   if (MUC0.IsVolatile && MUC1.IsVolatile)
234     return true;
235 
236   // Be conservative about atomics for the moment
237   // TODO: This is way overconservative for unordered atomics (see D66309)
238   if (MUC0.IsAtomic && MUC1.IsAtomic)
239     return true;
240 
241   // If one operation reads from invariant memory, and the other may store, they
242   // cannot alias.
243   if (MUC0.MMO && MUC1.MMO) {
244     if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
245         (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
246       return false;
247   }
248 
249   // Try to prove that there is aliasing, or that there is no aliasing. Either
250   // way, we can return now. If nothing can be proved, proceed with more tests.
251   bool IsAlias;
252   if (GISelAddressing::aliasIsKnownForLoadStore(MI, Other, IsAlias, MRI))
253     return IsAlias;
254 
255   // The following all rely on MMO0 and MMO1 being valid.
256   if (!MUC0.MMO || !MUC1.MMO)
257     return true;
258 
259   // FIXME: port the alignment based alias analysis from SDAG's isAlias().
260   int64_t SrcValOffset0 = MUC0.MMO->getOffset();
261   int64_t SrcValOffset1 = MUC1.MMO->getOffset();
262   uint64_t Size0 = MUC0.NumBytes;
263   uint64_t Size1 = MUC1.NumBytes;
264   if (AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() &&
265       Size0 != MemoryLocation::UnknownSize &&
266       Size1 != MemoryLocation::UnknownSize) {
267     // Use alias analysis information.
268     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
269     int64_t Overlap0 = Size0 + SrcValOffset0 - MinOffset;
270     int64_t Overlap1 = Size1 + SrcValOffset1 - MinOffset;
271     if (AA->isNoAlias(MemoryLocation(MUC0.MMO->getValue(), Overlap0,
272                                      MUC0.MMO->getAAInfo()),
273                       MemoryLocation(MUC1.MMO->getValue(), Overlap1,
274                                      MUC1.MMO->getAAInfo())))
275       return false;
276   }
277 
278   // Otherwise we have to assume they alias.
279   return true;
280 }
281 
282 /// Returns true if the instruction creates an unavoidable hazard that
283 /// forces a boundary between store merge candidates.
284 static bool isInstHardMergeHazard(MachineInstr &MI) {
285   return MI.hasUnmodeledSideEffects() || MI.hasOrderedMemoryRef();
286 }
287 
288 bool LoadStoreOpt::mergeStores(SmallVectorImpl<GStore *> &StoresToMerge) {
289   // Try to merge all the stores in the vector, splitting into separate segments
290   // as necessary.
291   assert(StoresToMerge.size() > 1 && "Expected multiple stores to merge");
292   LLT OrigTy = MRI->getType(StoresToMerge[0]->getValueReg());
293   LLT PtrTy = MRI->getType(StoresToMerge[0]->getPointerReg());
294   unsigned AS = PtrTy.getAddressSpace();
295   // Ensure the legal store info is computed for this address space.
296   initializeStoreMergeTargetInfo(AS);
297   const auto &LegalSizes = LegalStoreSizes[AS];
298 
299 #ifndef NDEBUG
300   for (auto StoreMI : StoresToMerge)
301     assert(MRI->getType(StoreMI->getValueReg()) == OrigTy);
302 #endif
303 
304   const auto &DL = MF->getFunction().getParent()->getDataLayout();
305   bool AnyMerged = false;
306   do {
307     unsigned NumPow2 = PowerOf2Floor(StoresToMerge.size());
308     unsigned MaxSizeBits = NumPow2 * OrigTy.getSizeInBits().getFixedSize();
309     // Compute the biggest store we can generate to handle the number of stores.
310     unsigned MergeSizeBits;
311     for (MergeSizeBits = MaxSizeBits; MergeSizeBits > 1; MergeSizeBits /= 2) {
312       LLT StoreTy = LLT::scalar(MergeSizeBits);
313       EVT StoreEVT =
314           getApproximateEVTForLLT(StoreTy, DL, MF->getFunction().getContext());
315       if (LegalSizes.size() > MergeSizeBits && LegalSizes[MergeSizeBits] &&
316           TLI->canMergeStoresTo(AS, StoreEVT, *MF) &&
317           (TLI->isTypeLegal(StoreEVT)))
318         break; // We can generate a MergeSize bits store.
319     }
320     if (MergeSizeBits <= OrigTy.getSizeInBits())
321       return AnyMerged; // No greater merge.
322 
323     unsigned NumStoresToMerge = MergeSizeBits / OrigTy.getSizeInBits();
324     // Perform the actual merging.
325     SmallVector<GStore *, 8> SingleMergeStores(
326         StoresToMerge.begin(), StoresToMerge.begin() + NumStoresToMerge);
327     AnyMerged |= doSingleStoreMerge(SingleMergeStores);
328     StoresToMerge.erase(StoresToMerge.begin(),
329                         StoresToMerge.begin() + NumStoresToMerge);
330   } while (StoresToMerge.size() > 1);
331   return AnyMerged;
332 }
333 
334 bool LoadStoreOpt::isLegalOrBeforeLegalizer(const LegalityQuery &Query,
335                                             MachineFunction &MF) const {
336   auto Action = LI->getAction(Query).Action;
337   // If the instruction is unsupported, it can't be legalized at all.
338   if (Action == LegalizeActions::Unsupported)
339     return false;
340   return IsPreLegalizer || Action == LegalizeAction::Legal;
341 }
342 
343 bool LoadStoreOpt::doSingleStoreMerge(SmallVectorImpl<GStore *> &Stores) {
344   assert(Stores.size() > 1);
345   // We know that all the stores are consecutive and there are no aliasing
346   // operations in the range. However, the values that are being stored may be
347   // generated anywhere before each store. To ensure we have the values
348   // available, we materialize the wide value and new store at the place of the
349   // final store in the merge sequence.
350   GStore *FirstStore = Stores[0];
351   const unsigned NumStores = Stores.size();
352   LLT SmallTy = MRI->getType(FirstStore->getValueReg());
353   LLT WideValueTy =
354       LLT::scalar(NumStores * SmallTy.getSizeInBits().getFixedSize());
355 
356   // For each store, compute pairwise merged debug locs.
357   DebugLoc MergedLoc;
358   for (unsigned AIdx = 0, BIdx = 1; BIdx < NumStores; ++AIdx, ++BIdx)
359     MergedLoc = DILocation::getMergedLocation(Stores[AIdx]->getDebugLoc(),
360                                               Stores[BIdx]->getDebugLoc());
361   Builder.setInstr(*Stores.back());
362   Builder.setDebugLoc(MergedLoc);
363 
364   // If all of the store values are constants, then create a wide constant
365   // directly. Otherwise, we need to generate some instructions to merge the
366   // existing values together into a wider type.
367   SmallVector<APInt, 8> ConstantVals;
368   for (auto Store : Stores) {
369     auto MaybeCst =
370         getIConstantVRegValWithLookThrough(Store->getValueReg(), *MRI);
371     if (!MaybeCst) {
372       ConstantVals.clear();
373       break;
374     }
375     ConstantVals.emplace_back(MaybeCst->Value);
376   }
377 
378   Register WideReg;
379   auto *WideMMO =
380       MF->getMachineMemOperand(&FirstStore->getMMO(), 0, WideValueTy);
381   if (ConstantVals.empty()) {
382     // Mimic the SDAG behaviour here and don't try to do anything for unknown
383     // values. In future, we should also support the cases of loads and
384     // extracted vector elements.
385     return false;
386   }
387 
388   assert(ConstantVals.size() == NumStores);
389   // Check if our wide constant is legal.
390   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {WideValueTy}}, *MF))
391     return false;
392   APInt WideConst(WideValueTy.getSizeInBits(), 0);
393   for (unsigned Idx = 0; Idx < ConstantVals.size(); ++Idx) {
394     // Insert the smaller constant into the corresponding position in the
395     // wider one.
396     WideConst.insertBits(ConstantVals[Idx], Idx * SmallTy.getSizeInBits());
397   }
398   WideReg = Builder.buildConstant(WideValueTy, WideConst).getReg(0);
399   auto NewStore =
400       Builder.buildStore(WideReg, FirstStore->getPointerReg(), *WideMMO);
401   (void) NewStore;
402   LLVM_DEBUG(dbgs() << "Created merged store: " << *NewStore);
403   NumStoresMerged += Stores.size();
404 
405   MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
406   MORE.emit([&]() {
407     MachineOptimizationRemark R(DEBUG_TYPE, "MergedStore",
408                                 FirstStore->getDebugLoc(),
409                                 FirstStore->getParent());
410     R << "Merged " << NV("NumMerged", Stores.size()) << " stores of "
411       << NV("OrigWidth", SmallTy.getSizeInBytes())
412       << " bytes into a single store of "
413       << NV("NewWidth", WideValueTy.getSizeInBytes()) << " bytes";
414     return R;
415   });
416 
417   for (auto MI : Stores)
418     InstsToErase.insert(MI);
419   return true;
420 }
421 
422 bool LoadStoreOpt::processMergeCandidate(StoreMergeCandidate &C) {
423   if (C.Stores.size() < 2) {
424     C.reset();
425     return false;
426   }
427 
428   LLVM_DEBUG(dbgs() << "Checking store merge candidate with " << C.Stores.size()
429                     << " stores, starting with " << *C.Stores[0]);
430   // We know that the stores in the candidate are adjacent.
431   // Now we need to check if any potential aliasing instructions recorded
432   // during the search alias with load/stores added to the candidate after.
433   // For example, if we have the candidate:
434   //   C.Stores = [ST1, ST2, ST3, ST4]
435   // and after seeing ST2 we saw a load LD1, which did not alias with ST1 or
436   // ST2, then we would have recorded it into the PotentialAliases structure
437   // with the associated index value of "1". Then we see ST3 and ST4 and add
438   // them to the candidate group. We know that LD1 does not alias with ST1 or
439   // ST2, since we already did that check. However we don't yet know if it
440   // may alias ST3 and ST4, so we perform those checks now.
441   SmallVector<GStore *> StoresToMerge;
442 
443   auto DoesStoreAliasWithPotential = [&](unsigned Idx, GStore &CheckStore) {
444     for (auto AliasInfo : reverse(C.PotentialAliases)) {
445       MachineInstr *PotentialAliasOp = AliasInfo.first;
446       unsigned PreCheckedIdx = AliasInfo.second;
447       if (static_cast<unsigned>(Idx) > PreCheckedIdx) {
448         // Need to check this alias.
449         if (GISelAddressing::instMayAlias(CheckStore, *PotentialAliasOp, *MRI,
450                                           AA)) {
451           LLVM_DEBUG(dbgs() << "Potential alias " << *PotentialAliasOp
452                             << " detected\n");
453           return true;
454         }
455       } else {
456         // Once our store index is lower than the index associated with the
457         // potential alias, we know that we've already checked for this alias
458         // and all of the earlier potential aliases too.
459         return false;
460       }
461     }
462     return false;
463   };
464   // Start from the last store in the group, and check if it aliases with any
465   // of the potential aliasing operations in the list.
466   for (int StoreIdx = C.Stores.size() - 1; StoreIdx >= 0; --StoreIdx) {
467     auto *CheckStore = C.Stores[StoreIdx];
468     if (DoesStoreAliasWithPotential(StoreIdx, *CheckStore))
469       continue;
470     StoresToMerge.emplace_back(CheckStore);
471   }
472 
473   LLVM_DEBUG(dbgs() << StoresToMerge.size()
474                     << " stores remaining after alias checks. Merging...\n");
475 
476   // Now we've checked for aliasing hazards, merge any stores left.
477   C.reset();
478   if (StoresToMerge.size() < 2)
479     return false;
480   return mergeStores(StoresToMerge);
481 }
482 
483 bool LoadStoreOpt::operationAliasesWithCandidate(MachineInstr &MI,
484                                                  StoreMergeCandidate &C) {
485   if (C.Stores.empty())
486     return false;
487   return llvm::any_of(C.Stores, [&](MachineInstr *OtherMI) {
488     return instMayAlias(MI, *OtherMI, *MRI, AA);
489   });
490 }
491 
492 void LoadStoreOpt::StoreMergeCandidate::addPotentialAlias(MachineInstr &MI) {
493   PotentialAliases.emplace_back(std::make_pair(&MI, Stores.size() - 1));
494 }
495 
496 bool LoadStoreOpt::addStoreToCandidate(GStore &StoreMI,
497                                        StoreMergeCandidate &C) {
498   // Check if the given store writes to an adjacent address, and other
499   // requirements.
500   LLT ValueTy = MRI->getType(StoreMI.getValueReg());
501   LLT PtrTy = MRI->getType(StoreMI.getPointerReg());
502 
503   // Only handle scalars.
504   if (!ValueTy.isScalar())
505     return false;
506 
507   // Don't allow truncating stores for now.
508   if (StoreMI.getMemSizeInBits() != ValueTy.getSizeInBits())
509     return false;
510 
511   Register StoreAddr = StoreMI.getPointerReg();
512   auto BIO = getPointerInfo(StoreAddr, *MRI);
513   Register StoreBase = BIO.BaseReg;
514   uint64_t StoreOffCst = BIO.Offset;
515   if (C.Stores.empty()) {
516     // This is the first store of the candidate.
517     // If the offset can't possibly allow for a lower addressed store with the
518     // same base, don't bother adding it.
519     if (StoreOffCst < ValueTy.getSizeInBytes())
520       return false;
521     C.BasePtr = StoreBase;
522     C.CurrentLowestOffset = StoreOffCst;
523     C.Stores.emplace_back(&StoreMI);
524     LLVM_DEBUG(dbgs() << "Starting a new merge candidate group with: "
525                       << StoreMI);
526     return true;
527   }
528 
529   // Check the store is the same size as the existing ones in the candidate.
530   if (MRI->getType(C.Stores[0]->getValueReg()).getSizeInBits() !=
531       ValueTy.getSizeInBits())
532     return false;
533 
534   if (MRI->getType(C.Stores[0]->getPointerReg()).getAddressSpace() !=
535       PtrTy.getAddressSpace())
536     return false;
537 
538   // There are other stores in the candidate. Check that the store address
539   // writes to the next lowest adjacent address.
540   if (C.BasePtr != StoreBase)
541     return false;
542   if ((C.CurrentLowestOffset - ValueTy.getSizeInBytes()) !=
543       static_cast<uint64_t>(StoreOffCst))
544     return false;
545 
546   // This writes to an adjacent address. Allow it.
547   C.Stores.emplace_back(&StoreMI);
548   C.CurrentLowestOffset = C.CurrentLowestOffset - ValueTy.getSizeInBytes();
549   LLVM_DEBUG(dbgs() << "Candidate added store: " << StoreMI);
550   return true;
551 }
552 
553 bool LoadStoreOpt::mergeBlockStores(MachineBasicBlock &MBB) {
554   bool Changed = false;
555   // Walk through the block bottom-up, looking for merging candidates.
556   StoreMergeCandidate Candidate;
557   for (MachineInstr &MI : llvm::reverse(MBB)) {
558     if (InstsToErase.contains(&MI))
559       continue;
560 
561     if (auto *StoreMI = dyn_cast<GStore>(&MI)) {
562       // We have a G_STORE. Add it to the candidate if it writes to an adjacent
563       // address.
564       if (!addStoreToCandidate(*StoreMI, Candidate)) {
565         // Store wasn't eligible to be added. May need to record it as a
566         // potential alias.
567         if (operationAliasesWithCandidate(*StoreMI, Candidate)) {
568           Changed |= processMergeCandidate(Candidate);
569           continue;
570         }
571         Candidate.addPotentialAlias(*StoreMI);
572       }
573       continue;
574     }
575 
576     // If we don't have any stores yet, this instruction can't pose a problem.
577     if (Candidate.Stores.empty())
578       continue;
579 
580     // We're dealing with some other kind of instruction.
581     if (isInstHardMergeHazard(MI)) {
582       Changed |= processMergeCandidate(Candidate);
583       Candidate.Stores.clear();
584       continue;
585     }
586 
587     if (!MI.mayLoadOrStore())
588       continue;
589 
590     if (operationAliasesWithCandidate(MI, Candidate)) {
591       // We have a potential alias, so process the current candidate if we can
592       // and then continue looking for a new candidate.
593       Changed |= processMergeCandidate(Candidate);
594       continue;
595     }
596 
597     // Record this instruction as a potential alias for future stores that are
598     // added to the candidate.
599     Candidate.addPotentialAlias(MI);
600   }
601 
602   // Process any candidate left after finishing searching the entire block.
603   Changed |= processMergeCandidate(Candidate);
604 
605   // Erase instructions now that we're no longer iterating over the block.
606   for (auto *MI : InstsToErase)
607     MI->eraseFromParent();
608   InstsToErase.clear();
609   return Changed;
610 }
611 
612 bool LoadStoreOpt::mergeFunctionStores(MachineFunction &MF) {
613   bool Changed = false;
614   for (auto &BB : MF) {
615     Changed |= mergeBlockStores(BB);
616   }
617   return Changed;
618 }
619 
620 void LoadStoreOpt::initializeStoreMergeTargetInfo(unsigned AddrSpace) {
621   // Query the legalizer info to record what store types are legal.
622   // We record this because we don't want to bother trying to merge stores into
623   // illegal ones, which would just result in being split again.
624 
625   if (LegalStoreSizes.count(AddrSpace)) {
626     assert(LegalStoreSizes[AddrSpace].any());
627     return; // Already cached sizes for this address space.
628   }
629 
630   // Need to reserve at least MaxStoreSizeToForm + 1 bits.
631   BitVector LegalSizes(MaxStoreSizeToForm * 2);
632   const auto &LI = *MF->getSubtarget().getLegalizerInfo();
633   const auto &DL = MF->getFunction().getParent()->getDataLayout();
634   Type *IntPtrIRTy =
635       DL.getIntPtrType(MF->getFunction().getContext(), AddrSpace);
636   LLT PtrTy = getLLTForType(*IntPtrIRTy->getPointerTo(AddrSpace), DL);
637   // We assume that we're not going to be generating any stores wider than
638   // MaxStoreSizeToForm bits for now.
639   for (unsigned Size = 2; Size <= MaxStoreSizeToForm; Size *= 2) {
640     LLT Ty = LLT::scalar(Size);
641     SmallVector<LegalityQuery::MemDesc, 2> MemDescrs(
642         {{Ty, Ty.getSizeInBits(), AtomicOrdering::NotAtomic}});
643     SmallVector<LLT> StoreTys({Ty, PtrTy});
644     LegalityQuery Q(TargetOpcode::G_STORE, StoreTys, MemDescrs);
645     LegalizeActionStep ActionStep = LI.getAction(Q);
646     if (ActionStep.Action == LegalizeActions::Legal)
647       LegalSizes.set(Size);
648   }
649   assert(LegalSizes.any() && "Expected some store sizes to be legal!");
650   LegalStoreSizes[AddrSpace] = LegalSizes;
651 }
652 
653 bool LoadStoreOpt::runOnMachineFunction(MachineFunction &MF) {
654   // If the ISel pipeline failed, do not bother running that pass.
655   if (MF.getProperties().hasProperty(
656           MachineFunctionProperties::Property::FailedISel))
657     return false;
658 
659   LLVM_DEBUG(dbgs() << "Begin memory optimizations for: " << MF.getName()
660                     << '\n');
661 
662   init(MF);
663   bool Changed = false;
664   Changed |= mergeFunctionStores(MF);
665 
666   LegalStoreSizes.clear();
667   return Changed;
668 }
669