1 //===- SILoadStoreOptimizer.cpp -------------------------------------------===//
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 //
9 // This pass tries to fuse DS instructions with close by immediate offsets.
10 // This will fuse operations such as
11 //  ds_read_b32 v0, v2 offset:16
12 //  ds_read_b32 v1, v2 offset:32
13 // ==>
14 //   ds_read2_b32 v[0:1], v2, offset0:4 offset1:8
15 //
16 // The same is done for certain SMEM and VMEM opcodes, e.g.:
17 //  s_buffer_load_dword s4, s[0:3], 4
18 //  s_buffer_load_dword s5, s[0:3], 8
19 // ==>
20 //  s_buffer_load_dwordx2 s[4:5], s[0:3], 4
21 //
22 // This pass also tries to promote constant offset to the immediate by
23 // adjusting the base. It tries to use a base from the nearby instructions that
24 // allows it to have a 13bit constant offset and then promotes the 13bit offset
25 // to the immediate.
26 // E.g.
27 //  s_movk_i32 s0, 0x1800
28 //  v_add_co_u32_e32 v0, vcc, s0, v2
29 //  v_addc_co_u32_e32 v1, vcc, 0, v6, vcc
30 //
31 //  s_movk_i32 s0, 0x1000
32 //  v_add_co_u32_e32 v5, vcc, s0, v2
33 //  v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
34 //  global_load_dwordx2 v[5:6], v[5:6], off
35 //  global_load_dwordx2 v[0:1], v[0:1], off
36 // =>
37 //  s_movk_i32 s0, 0x1000
38 //  v_add_co_u32_e32 v5, vcc, s0, v2
39 //  v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
40 //  global_load_dwordx2 v[5:6], v[5:6], off
41 //  global_load_dwordx2 v[0:1], v[5:6], off offset:2048
42 //
43 // Future improvements:
44 //
45 // - This is currently missing stores of constants because loading
46 //   the constant into the data register is placed between the stores, although
47 //   this is arguably a scheduling problem.
48 //
49 // - Live interval recomputing seems inefficient. This currently only matches
50 //   one pair, and recomputes live intervals and moves on to the next pair. It
51 //   would be better to compute a list of all merges that need to occur.
52 //
53 // - With a list of instructions to process, we can also merge more. If a
54 //   cluster of loads have offsets that are too large to fit in the 8-bit
55 //   offsets, but are close enough to fit in the 8 bits, we can add to the base
56 //   pointer and use the new reduced offsets.
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "AMDGPU.h"
61 #include "AMDGPUSubtarget.h"
62 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
63 #include "SIInstrInfo.h"
64 #include "SIRegisterInfo.h"
65 #include "Utils/AMDGPUBaseInfo.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/SmallVector.h"
68 #include "llvm/ADT/StringRef.h"
69 #include "llvm/Analysis/AliasAnalysis.h"
70 #include "llvm/CodeGen/MachineBasicBlock.h"
71 #include "llvm/CodeGen/MachineFunction.h"
72 #include "llvm/CodeGen/MachineFunctionPass.h"
73 #include "llvm/CodeGen/MachineInstr.h"
74 #include "llvm/CodeGen/MachineInstrBuilder.h"
75 #include "llvm/CodeGen/MachineOperand.h"
76 #include "llvm/CodeGen/MachineRegisterInfo.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include <algorithm>
84 #include <cassert>
85 #include <cstdlib>
86 #include <iterator>
87 #include <utility>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "si-load-store-opt"
92 
93 namespace {
94 enum InstClassEnum {
95   UNKNOWN,
96   DS_READ,
97   DS_WRITE,
98   S_BUFFER_LOAD_IMM,
99   BUFFER_LOAD,
100   BUFFER_STORE,
101   MIMG,
102   TBUFFER_LOAD,
103   TBUFFER_STORE,
104 };
105 
106 struct AddressRegs {
107   unsigned char NumVAddrs = 0;
108   bool SBase = false;
109   bool SRsrc = false;
110   bool SOffset = false;
111   bool VAddr = false;
112   bool Addr = false;
113   bool SSamp = false;
114 };
115 
116 // GFX10 image_sample instructions can have 12 vaddrs + srsrc + ssamp.
117 const unsigned MaxAddressRegs = 12 + 1 + 1;
118 
119 class SILoadStoreOptimizer : public MachineFunctionPass {
120   struct CombineInfo {
121     MachineBasicBlock::iterator I;
122     unsigned EltSize;
123     unsigned Offset;
124     unsigned Width;
125     unsigned Format;
126     unsigned BaseOff;
127     unsigned DMask;
128     InstClassEnum InstClass;
129     bool GLC;
130     bool SLC;
131     bool DLC;
132     bool UseST64;
133     int AddrIdx[MaxAddressRegs];
134     const MachineOperand *AddrReg[MaxAddressRegs];
135     unsigned NumAddresses;
136     unsigned Order;
137 
138     bool hasSameBaseAddress(const MachineInstr &MI) {
139       for (unsigned i = 0; i < NumAddresses; i++) {
140         const MachineOperand &AddrRegNext = MI.getOperand(AddrIdx[i]);
141 
142         if (AddrReg[i]->isImm() || AddrRegNext.isImm()) {
143           if (AddrReg[i]->isImm() != AddrRegNext.isImm() ||
144               AddrReg[i]->getImm() != AddrRegNext.getImm()) {
145             return false;
146           }
147           continue;
148         }
149 
150         // Check same base pointer. Be careful of subregisters, which can occur
151         // with vectors of pointers.
152         if (AddrReg[i]->getReg() != AddrRegNext.getReg() ||
153             AddrReg[i]->getSubReg() != AddrRegNext.getSubReg()) {
154          return false;
155         }
156       }
157       return true;
158     }
159 
160     bool hasMergeableAddress(const MachineRegisterInfo &MRI) {
161       for (unsigned i = 0; i < NumAddresses; ++i) {
162         const MachineOperand *AddrOp = AddrReg[i];
163         // Immediates are always OK.
164         if (AddrOp->isImm())
165           continue;
166 
167         // Don't try to merge addresses that aren't either immediates or registers.
168         // TODO: Should be possible to merge FrameIndexes and maybe some other
169         // non-register
170         if (!AddrOp->isReg())
171           return false;
172 
173         // TODO: We should be able to merge physical reg addreses.
174         if (AddrOp->getReg().isPhysical())
175           return false;
176 
177         // If an address has only one use then there will be on other
178         // instructions with the same address, so we can't merge this one.
179         if (MRI.hasOneNonDBGUse(AddrOp->getReg()))
180           return false;
181       }
182       return true;
183     }
184 
185     void setMI(MachineBasicBlock::iterator MI, const SIInstrInfo &TII,
186                const GCNSubtarget &STM);
187   };
188 
189   struct BaseRegisters {
190     Register LoReg;
191     Register HiReg;
192 
193     unsigned LoSubReg = 0;
194     unsigned HiSubReg = 0;
195   };
196 
197   struct MemAddress {
198     BaseRegisters Base;
199     int64_t Offset = 0;
200   };
201 
202   using MemInfoMap = DenseMap<MachineInstr *, MemAddress>;
203 
204 private:
205   const GCNSubtarget *STM = nullptr;
206   const SIInstrInfo *TII = nullptr;
207   const SIRegisterInfo *TRI = nullptr;
208   MachineRegisterInfo *MRI = nullptr;
209   AliasAnalysis *AA = nullptr;
210   bool OptimizeAgain;
211 
212   static bool dmasksCanBeCombined(const CombineInfo &CI,
213                                   const SIInstrInfo &TII,
214                                   const CombineInfo &Paired);
215   static bool offsetsCanBeCombined(CombineInfo &CI, const GCNSubtarget &STI,
216                                    CombineInfo &Paired, bool Modify = false);
217   static bool widthsFit(const GCNSubtarget &STI, const CombineInfo &CI,
218                         const CombineInfo &Paired);
219   static unsigned getNewOpcode(const CombineInfo &CI, const CombineInfo &Paired);
220   static std::pair<unsigned, unsigned> getSubRegIdxs(const CombineInfo &CI,
221                                                      const CombineInfo &Paired);
222   const TargetRegisterClass *getTargetRegisterClass(const CombineInfo &CI,
223                                                     const CombineInfo &Paired);
224 
225   bool checkAndPrepareMerge(CombineInfo &CI, CombineInfo &Paired,
226                             SmallVectorImpl<MachineInstr *> &InstsToMove);
227 
228   unsigned read2Opcode(unsigned EltSize) const;
229   unsigned read2ST64Opcode(unsigned EltSize) const;
230   MachineBasicBlock::iterator mergeRead2Pair(CombineInfo &CI,
231                                              CombineInfo &Paired,
232                   const SmallVectorImpl<MachineInstr *> &InstsToMove);
233 
234   unsigned write2Opcode(unsigned EltSize) const;
235   unsigned write2ST64Opcode(unsigned EltSize) const;
236   MachineBasicBlock::iterator
237   mergeWrite2Pair(CombineInfo &CI, CombineInfo &Paired,
238                   const SmallVectorImpl<MachineInstr *> &InstsToMove);
239   MachineBasicBlock::iterator
240   mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
241                  const SmallVectorImpl<MachineInstr *> &InstsToMove);
242   MachineBasicBlock::iterator
243   mergeSBufferLoadImmPair(CombineInfo &CI, CombineInfo &Paired,
244                           const SmallVectorImpl<MachineInstr *> &InstsToMove);
245   MachineBasicBlock::iterator
246   mergeBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
247                       const SmallVectorImpl<MachineInstr *> &InstsToMove);
248   MachineBasicBlock::iterator
249   mergeBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
250                        const SmallVectorImpl<MachineInstr *> &InstsToMove);
251   MachineBasicBlock::iterator
252   mergeTBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
253                        const SmallVectorImpl<MachineInstr *> &InstsToMove);
254   MachineBasicBlock::iterator
255   mergeTBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
256                         const SmallVectorImpl<MachineInstr *> &InstsToMove);
257 
258   void updateBaseAndOffset(MachineInstr &I, Register NewBase,
259                            int32_t NewOffset) const;
260   Register computeBase(MachineInstr &MI, const MemAddress &Addr) const;
261   MachineOperand createRegOrImm(int32_t Val, MachineInstr &MI) const;
262   Optional<int32_t> extractConstOffset(const MachineOperand &Op) const;
263   void processBaseWithConstOffset(const MachineOperand &Base, MemAddress &Addr) const;
264   /// Promotes constant offset to the immediate by adjusting the base. It
265   /// tries to use a base from the nearby instructions that allows it to have
266   /// a 13bit constant offset which gets promoted to the immediate.
267   bool promoteConstantOffsetToImm(MachineInstr &CI,
268                                   MemInfoMap &Visited,
269                                   SmallPtrSet<MachineInstr *, 4> &Promoted) const;
270   void addInstToMergeableList(const CombineInfo &CI,
271                   std::list<std::list<CombineInfo> > &MergeableInsts) const;
272 
273   std::pair<MachineBasicBlock::iterator, bool> collectMergeableInsts(
274       MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End,
275       MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
276       std::list<std::list<CombineInfo>> &MergeableInsts) const;
277 
278 public:
279   static char ID;
280 
281   SILoadStoreOptimizer() : MachineFunctionPass(ID) {
282     initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
283   }
284 
285   bool optimizeInstsWithSameBaseAddr(std::list<CombineInfo> &MergeList,
286                                      bool &OptimizeListAgain);
287   bool optimizeBlock(std::list<std::list<CombineInfo> > &MergeableInsts);
288 
289   bool runOnMachineFunction(MachineFunction &MF) override;
290 
291   StringRef getPassName() const override { return "SI Load Store Optimizer"; }
292 
293   void getAnalysisUsage(AnalysisUsage &AU) const override {
294     AU.setPreservesCFG();
295     AU.addRequired<AAResultsWrapperPass>();
296 
297     MachineFunctionPass::getAnalysisUsage(AU);
298   }
299 
300   MachineFunctionProperties getRequiredProperties() const override {
301     return MachineFunctionProperties()
302       .set(MachineFunctionProperties::Property::IsSSA);
303   }
304 };
305 
306 static unsigned getOpcodeWidth(const MachineInstr &MI, const SIInstrInfo &TII) {
307   const unsigned Opc = MI.getOpcode();
308 
309   if (TII.isMUBUF(Opc)) {
310     // FIXME: Handle d16 correctly
311     return AMDGPU::getMUBUFElements(Opc);
312   }
313   if (TII.isMIMG(MI)) {
314     uint64_t DMaskImm =
315         TII.getNamedOperand(MI, AMDGPU::OpName::dmask)->getImm();
316     return countPopulation(DMaskImm);
317   }
318   if (TII.isMTBUF(Opc)) {
319     return AMDGPU::getMTBUFElements(Opc);
320   }
321 
322   switch (Opc) {
323   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
324     return 1;
325   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
326     return 2;
327   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
328     return 4;
329   default:
330     return 0;
331   }
332 }
333 
334 /// Maps instruction opcode to enum InstClassEnum.
335 static InstClassEnum getInstClass(unsigned Opc, const SIInstrInfo &TII) {
336   switch (Opc) {
337   default:
338     if (TII.isMUBUF(Opc)) {
339       switch (AMDGPU::getMUBUFBaseOpcode(Opc)) {
340       default:
341         return UNKNOWN;
342       case AMDGPU::BUFFER_LOAD_DWORD_OFFEN:
343       case AMDGPU::BUFFER_LOAD_DWORD_OFFEN_exact:
344       case AMDGPU::BUFFER_LOAD_DWORD_OFFSET:
345       case AMDGPU::BUFFER_LOAD_DWORD_OFFSET_exact:
346         return BUFFER_LOAD;
347       case AMDGPU::BUFFER_STORE_DWORD_OFFEN:
348       case AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact:
349       case AMDGPU::BUFFER_STORE_DWORD_OFFSET:
350       case AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact:
351         return BUFFER_STORE;
352       }
353     }
354     if (TII.isMIMG(Opc)) {
355       // Ignore instructions encoded without vaddr.
356       if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr) == -1 &&
357           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0) == -1)
358         return UNKNOWN;
359       // TODO: Support IMAGE_GET_RESINFO and IMAGE_GET_LOD.
360       if (TII.get(Opc).mayStore() || !TII.get(Opc).mayLoad() ||
361           TII.isGather4(Opc))
362         return UNKNOWN;
363       return MIMG;
364     }
365     if (TII.isMTBUF(Opc)) {
366       switch (AMDGPU::getMTBUFBaseOpcode(Opc)) {
367       default:
368         return UNKNOWN;
369       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN:
370       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN_exact:
371       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET:
372       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET_exact:
373         return TBUFFER_LOAD;
374       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN:
375       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN_exact:
376       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET:
377       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET_exact:
378         return TBUFFER_STORE;
379       }
380     }
381     return UNKNOWN;
382   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
383   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
384   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
385     return S_BUFFER_LOAD_IMM;
386   case AMDGPU::DS_READ_B32:
387   case AMDGPU::DS_READ_B32_gfx9:
388   case AMDGPU::DS_READ_B64:
389   case AMDGPU::DS_READ_B64_gfx9:
390     return DS_READ;
391   case AMDGPU::DS_WRITE_B32:
392   case AMDGPU::DS_WRITE_B32_gfx9:
393   case AMDGPU::DS_WRITE_B64:
394   case AMDGPU::DS_WRITE_B64_gfx9:
395     return DS_WRITE;
396   }
397 }
398 
399 /// Determines instruction subclass from opcode. Only instructions
400 /// of the same subclass can be merged together.
401 static unsigned getInstSubclass(unsigned Opc, const SIInstrInfo &TII) {
402   switch (Opc) {
403   default:
404     if (TII.isMUBUF(Opc))
405       return AMDGPU::getMUBUFBaseOpcode(Opc);
406     if (TII.isMIMG(Opc)) {
407       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
408       assert(Info);
409       return Info->BaseOpcode;
410     }
411     if (TII.isMTBUF(Opc))
412       return AMDGPU::getMTBUFBaseOpcode(Opc);
413     return -1;
414   case AMDGPU::DS_READ_B32:
415   case AMDGPU::DS_READ_B32_gfx9:
416   case AMDGPU::DS_READ_B64:
417   case AMDGPU::DS_READ_B64_gfx9:
418   case AMDGPU::DS_WRITE_B32:
419   case AMDGPU::DS_WRITE_B32_gfx9:
420   case AMDGPU::DS_WRITE_B64:
421   case AMDGPU::DS_WRITE_B64_gfx9:
422     return Opc;
423   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
424   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
425   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
426     return AMDGPU::S_BUFFER_LOAD_DWORD_IMM;
427   }
428 }
429 
430 static AddressRegs getRegs(unsigned Opc, const SIInstrInfo &TII) {
431   AddressRegs Result;
432 
433   if (TII.isMUBUF(Opc)) {
434     if (AMDGPU::getMUBUFHasVAddr(Opc))
435       Result.VAddr = true;
436     if (AMDGPU::getMUBUFHasSrsrc(Opc))
437       Result.SRsrc = true;
438     if (AMDGPU::getMUBUFHasSoffset(Opc))
439       Result.SOffset = true;
440 
441     return Result;
442   }
443 
444   if (TII.isMIMG(Opc)) {
445     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
446     if (VAddr0Idx >= 0) {
447       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
448       Result.NumVAddrs = SRsrcIdx - VAddr0Idx;
449     } else {
450       Result.VAddr = true;
451     }
452     Result.SRsrc = true;
453     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
454     if (Info && AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode)->Sampler)
455       Result.SSamp = true;
456 
457     return Result;
458   }
459   if (TII.isMTBUF(Opc)) {
460     if (AMDGPU::getMTBUFHasVAddr(Opc))
461       Result.VAddr = true;
462     if (AMDGPU::getMTBUFHasSrsrc(Opc))
463       Result.SRsrc = true;
464     if (AMDGPU::getMTBUFHasSoffset(Opc))
465       Result.SOffset = true;
466 
467     return Result;
468   }
469 
470   switch (Opc) {
471   default:
472     return Result;
473   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
474   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
475   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
476     Result.SBase = true;
477     return Result;
478   case AMDGPU::DS_READ_B32:
479   case AMDGPU::DS_READ_B64:
480   case AMDGPU::DS_READ_B32_gfx9:
481   case AMDGPU::DS_READ_B64_gfx9:
482   case AMDGPU::DS_WRITE_B32:
483   case AMDGPU::DS_WRITE_B64:
484   case AMDGPU::DS_WRITE_B32_gfx9:
485   case AMDGPU::DS_WRITE_B64_gfx9:
486     Result.Addr = true;
487     return Result;
488   }
489 }
490 
491 void SILoadStoreOptimizer::CombineInfo::setMI(MachineBasicBlock::iterator MI,
492                                               const SIInstrInfo &TII,
493                                               const GCNSubtarget &STM) {
494   I = MI;
495   unsigned Opc = MI->getOpcode();
496   InstClass = getInstClass(Opc, TII);
497 
498   if (InstClass == UNKNOWN)
499     return;
500 
501   switch (InstClass) {
502   case DS_READ:
503    EltSize =
504           (Opc == AMDGPU::DS_READ_B64 || Opc == AMDGPU::DS_READ_B64_gfx9) ? 8
505                                                                           : 4;
506    break;
507   case DS_WRITE:
508     EltSize =
509           (Opc == AMDGPU::DS_WRITE_B64 || Opc == AMDGPU::DS_WRITE_B64_gfx9) ? 8
510                                                                             : 4;
511     break;
512   case S_BUFFER_LOAD_IMM:
513     EltSize = AMDGPU::convertSMRDOffsetUnits(STM, 4);
514     break;
515   default:
516     EltSize = 4;
517     break;
518   }
519 
520   if (InstClass == MIMG) {
521     DMask = TII.getNamedOperand(*I, AMDGPU::OpName::dmask)->getImm();
522     // Offset is not considered for MIMG instructions.
523     Offset = 0;
524   } else {
525     int OffsetIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::offset);
526     Offset = I->getOperand(OffsetIdx).getImm();
527   }
528 
529   if (InstClass == TBUFFER_LOAD || InstClass == TBUFFER_STORE)
530     Format = TII.getNamedOperand(*I, AMDGPU::OpName::format)->getImm();
531 
532   Width = getOpcodeWidth(*I, TII);
533 
534   if ((InstClass == DS_READ) || (InstClass == DS_WRITE)) {
535     Offset &= 0xffff;
536   } else if (InstClass != MIMG) {
537     GLC = TII.getNamedOperand(*I, AMDGPU::OpName::glc)->getImm();
538     if (InstClass != S_BUFFER_LOAD_IMM) {
539       SLC = TII.getNamedOperand(*I, AMDGPU::OpName::slc)->getImm();
540     }
541     DLC = TII.getNamedOperand(*I, AMDGPU::OpName::dlc)->getImm();
542   }
543 
544   AddressRegs Regs = getRegs(Opc, TII);
545 
546   NumAddresses = 0;
547   for (unsigned J = 0; J < Regs.NumVAddrs; J++)
548     AddrIdx[NumAddresses++] =
549         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0) + J;
550   if (Regs.Addr)
551     AddrIdx[NumAddresses++] =
552         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::addr);
553   if (Regs.SBase)
554     AddrIdx[NumAddresses++] =
555         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sbase);
556   if (Regs.SRsrc)
557     AddrIdx[NumAddresses++] =
558         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
559   if (Regs.SOffset)
560     AddrIdx[NumAddresses++] =
561         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset);
562   if (Regs.VAddr)
563     AddrIdx[NumAddresses++] =
564         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
565   if (Regs.SSamp)
566     AddrIdx[NumAddresses++] =
567         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::ssamp);
568   assert(NumAddresses <= MaxAddressRegs);
569 
570   for (unsigned J = 0; J < NumAddresses; J++)
571     AddrReg[J] = &I->getOperand(AddrIdx[J]);
572 }
573 
574 } // end anonymous namespace.
575 
576 INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
577                       "SI Load Store Optimizer", false, false)
578 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
579 INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE, "SI Load Store Optimizer",
580                     false, false)
581 
582 char SILoadStoreOptimizer::ID = 0;
583 
584 char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;
585 
586 FunctionPass *llvm::createSILoadStoreOptimizerPass() {
587   return new SILoadStoreOptimizer();
588 }
589 
590 static void moveInstsAfter(MachineBasicBlock::iterator I,
591                            ArrayRef<MachineInstr *> InstsToMove) {
592   MachineBasicBlock *MBB = I->getParent();
593   ++I;
594   for (MachineInstr *MI : InstsToMove) {
595     MI->removeFromParent();
596     MBB->insert(I, MI);
597   }
598 }
599 
600 static void addDefsUsesToList(const MachineInstr &MI,
601                               DenseSet<Register> &RegDefs,
602                               DenseSet<Register> &PhysRegUses) {
603   for (const MachineOperand &Op : MI.operands()) {
604     if (Op.isReg()) {
605       if (Op.isDef())
606         RegDefs.insert(Op.getReg());
607       else if (Op.readsReg() && Op.getReg().isPhysical())
608         PhysRegUses.insert(Op.getReg());
609     }
610   }
611 }
612 
613 static bool memAccessesCanBeReordered(MachineBasicBlock::iterator A,
614                                       MachineBasicBlock::iterator B,
615                                       AliasAnalysis *AA) {
616   // RAW or WAR - cannot reorder
617   // WAW - cannot reorder
618   // RAR - safe to reorder
619   return !(A->mayStore() || B->mayStore()) || !A->mayAlias(AA, *B, true);
620 }
621 
622 // Add MI and its defs to the lists if MI reads one of the defs that are
623 // already in the list. Returns true in that case.
624 static bool addToListsIfDependent(MachineInstr &MI, DenseSet<Register> &RegDefs,
625                                   DenseSet<Register> &PhysRegUses,
626                                   SmallVectorImpl<MachineInstr *> &Insts) {
627   for (MachineOperand &Use : MI.operands()) {
628     // If one of the defs is read, then there is a use of Def between I and the
629     // instruction that I will potentially be merged with. We will need to move
630     // this instruction after the merged instructions.
631     //
632     // Similarly, if there is a def which is read by an instruction that is to
633     // be moved for merging, then we need to move the def-instruction as well.
634     // This can only happen for physical registers such as M0; virtual
635     // registers are in SSA form.
636     if (Use.isReg() && ((Use.readsReg() && RegDefs.count(Use.getReg())) ||
637                         (Use.isDef() && RegDefs.count(Use.getReg())) ||
638                         (Use.isDef() && Use.getReg().isPhysical() &&
639                          PhysRegUses.count(Use.getReg())))) {
640       Insts.push_back(&MI);
641       addDefsUsesToList(MI, RegDefs, PhysRegUses);
642       return true;
643     }
644   }
645 
646   return false;
647 }
648 
649 static bool canMoveInstsAcrossMemOp(MachineInstr &MemOp,
650                                     ArrayRef<MachineInstr *> InstsToMove,
651                                     AliasAnalysis *AA) {
652   assert(MemOp.mayLoadOrStore());
653 
654   for (MachineInstr *InstToMove : InstsToMove) {
655     if (!InstToMove->mayLoadOrStore())
656       continue;
657     if (!memAccessesCanBeReordered(MemOp, *InstToMove, AA))
658       return false;
659   }
660   return true;
661 }
662 
663 // This function assumes that \p A and \p B have are identical except for
664 // size and offset, and they referecne adjacent memory.
665 static MachineMemOperand *combineKnownAdjacentMMOs(MachineFunction &MF,
666                                                    const MachineMemOperand *A,
667                                                    const MachineMemOperand *B) {
668   unsigned MinOffset = std::min(A->getOffset(), B->getOffset());
669   unsigned Size = A->getSize() + B->getSize();
670   // This function adds the offset parameter to the existing offset for A,
671   // so we pass 0 here as the offset and then manually set it to the correct
672   // value after the call.
673   MachineMemOperand *MMO = MF.getMachineMemOperand(A, 0, Size);
674   MMO->setOffset(MinOffset);
675   return MMO;
676 }
677 
678 bool SILoadStoreOptimizer::dmasksCanBeCombined(const CombineInfo &CI,
679                                                const SIInstrInfo &TII,
680                                                const CombineInfo &Paired) {
681   assert(CI.InstClass == MIMG);
682 
683   // Ignore instructions with tfe/lwe set.
684   const auto *TFEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::tfe);
685   const auto *LWEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::lwe);
686 
687   if ((TFEOp && TFEOp->getImm()) || (LWEOp && LWEOp->getImm()))
688     return false;
689 
690   // Check other optional immediate operands for equality.
691   unsigned OperandsToMatch[] = {AMDGPU::OpName::glc, AMDGPU::OpName::slc,
692                                 AMDGPU::OpName::d16, AMDGPU::OpName::unorm,
693                                 AMDGPU::OpName::da,  AMDGPU::OpName::r128,
694                                 AMDGPU::OpName::a16, AMDGPU::OpName::dlc};
695 
696   for (auto op : OperandsToMatch) {
697     int Idx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), op);
698     if (AMDGPU::getNamedOperandIdx(Paired.I->getOpcode(), op) != Idx)
699       return false;
700     if (Idx != -1 &&
701         CI.I->getOperand(Idx).getImm() != Paired.I->getOperand(Idx).getImm())
702       return false;
703   }
704 
705   // Check DMask for overlaps.
706   unsigned MaxMask = std::max(CI.DMask, Paired.DMask);
707   unsigned MinMask = std::min(CI.DMask, Paired.DMask);
708 
709   unsigned AllowedBitsForMin = llvm::countTrailingZeros(MaxMask);
710   if ((1u << AllowedBitsForMin) <= MinMask)
711     return false;
712 
713   return true;
714 }
715 
716 static unsigned getBufferFormatWithCompCount(unsigned OldFormat,
717                                        unsigned ComponentCount,
718                                        const GCNSubtarget &STI) {
719   if (ComponentCount > 4)
720     return 0;
721 
722   const llvm::AMDGPU::GcnBufferFormatInfo *OldFormatInfo =
723       llvm::AMDGPU::getGcnBufferFormatInfo(OldFormat, STI);
724   if (!OldFormatInfo)
725     return 0;
726 
727   const llvm::AMDGPU::GcnBufferFormatInfo *NewFormatInfo =
728       llvm::AMDGPU::getGcnBufferFormatInfo(OldFormatInfo->BitsPerComp,
729                                            ComponentCount,
730                                            OldFormatInfo->NumFormat, STI);
731 
732   if (!NewFormatInfo)
733     return 0;
734 
735   assert(NewFormatInfo->NumFormat == OldFormatInfo->NumFormat &&
736          NewFormatInfo->BitsPerComp == OldFormatInfo->BitsPerComp);
737 
738   return NewFormatInfo->Format;
739 }
740 
741 bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI,
742                                                 const GCNSubtarget &STI,
743                                                 CombineInfo &Paired,
744                                                 bool Modify) {
745   assert(CI.InstClass != MIMG);
746 
747   // XXX - Would the same offset be OK? Is there any reason this would happen or
748   // be useful?
749   if (CI.Offset == Paired.Offset)
750     return false;
751 
752   // This won't be valid if the offset isn't aligned.
753   if ((CI.Offset % CI.EltSize != 0) || (Paired.Offset % CI.EltSize != 0))
754     return false;
755 
756   if (CI.InstClass == TBUFFER_LOAD || CI.InstClass == TBUFFER_STORE) {
757 
758     const llvm::AMDGPU::GcnBufferFormatInfo *Info0 =
759         llvm::AMDGPU::getGcnBufferFormatInfo(CI.Format, STI);
760     if (!Info0)
761       return false;
762     const llvm::AMDGPU::GcnBufferFormatInfo *Info1 =
763         llvm::AMDGPU::getGcnBufferFormatInfo(Paired.Format, STI);
764     if (!Info1)
765       return false;
766 
767     if (Info0->BitsPerComp != Info1->BitsPerComp ||
768         Info0->NumFormat != Info1->NumFormat)
769       return false;
770 
771     // TODO: Should be possible to support more formats, but if format loads
772     // are not dword-aligned, the merged load might not be valid.
773     if (Info0->BitsPerComp != 32)
774       return false;
775 
776     if (getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, STI) == 0)
777       return false;
778   }
779 
780   unsigned EltOffset0 = CI.Offset / CI.EltSize;
781   unsigned EltOffset1 = Paired.Offset / CI.EltSize;
782   CI.UseST64 = false;
783   CI.BaseOff = 0;
784 
785   // Handle DS instructions.
786   if ((CI.InstClass != DS_READ) && (CI.InstClass != DS_WRITE)) {
787     return (EltOffset0 + CI.Width == EltOffset1 ||
788             EltOffset1 + Paired.Width == EltOffset0) &&
789            CI.GLC == Paired.GLC && CI.DLC == Paired.DLC &&
790            (CI.InstClass == S_BUFFER_LOAD_IMM || CI.SLC == Paired.SLC);
791   }
792 
793   // Handle SMEM and VMEM instructions.
794   // If the offset in elements doesn't fit in 8-bits, we might be able to use
795   // the stride 64 versions.
796   if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 &&
797       isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) {
798     if (Modify) {
799       CI.Offset = EltOffset0 / 64;
800       Paired.Offset = EltOffset1 / 64;
801       CI.UseST64 = true;
802     }
803     return true;
804   }
805 
806   // Check if the new offsets fit in the reduced 8-bit range.
807   if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) {
808     if (Modify) {
809       CI.Offset = EltOffset0;
810       Paired.Offset = EltOffset1;
811     }
812     return true;
813   }
814 
815   // Try to shift base address to decrease offsets.
816   unsigned OffsetDiff = std::abs((int)EltOffset1 - (int)EltOffset0);
817   CI.BaseOff = std::min(CI.Offset, Paired.Offset);
818 
819   if ((OffsetDiff % 64 == 0) && isUInt<8>(OffsetDiff / 64)) {
820     if (Modify) {
821       CI.Offset = (EltOffset0 - CI.BaseOff / CI.EltSize) / 64;
822       Paired.Offset = (EltOffset1 - CI.BaseOff / CI.EltSize) / 64;
823       CI.UseST64 = true;
824     }
825     return true;
826   }
827 
828   if (isUInt<8>(OffsetDiff)) {
829     if (Modify) {
830       CI.Offset = EltOffset0 - CI.BaseOff / CI.EltSize;
831       Paired.Offset = EltOffset1 - CI.BaseOff / CI.EltSize;
832     }
833     return true;
834   }
835 
836   return false;
837 }
838 
839 bool SILoadStoreOptimizer::widthsFit(const GCNSubtarget &STM,
840                                      const CombineInfo &CI,
841                                      const CombineInfo &Paired) {
842   const unsigned Width = (CI.Width + Paired.Width);
843   switch (CI.InstClass) {
844   default:
845     return (Width <= 4) && (STM.hasDwordx3LoadStores() || (Width != 3));
846   case S_BUFFER_LOAD_IMM:
847     switch (Width) {
848     default:
849       return false;
850     case 2:
851     case 4:
852       return true;
853     }
854   }
855 }
856 
857 /// This function assumes that CI comes before Paired in a basic block.
858 bool SILoadStoreOptimizer::checkAndPrepareMerge(
859     CombineInfo &CI, CombineInfo &Paired,
860     SmallVectorImpl<MachineInstr *> &InstsToMove) {
861 
862   // Check both offsets (or masks for MIMG) can be combined and fit in the
863   // reduced range.
864   if (CI.InstClass == MIMG && !dmasksCanBeCombined(CI, *TII, Paired))
865     return false;
866 
867   if (CI.InstClass != MIMG &&
868       (!widthsFit(*STM, CI, Paired) || !offsetsCanBeCombined(CI, *STM, Paired)))
869     return false;
870 
871   const unsigned Opc = CI.I->getOpcode();
872   const InstClassEnum InstClass = getInstClass(Opc, *TII);
873 
874   if (InstClass == UNKNOWN) {
875     return false;
876   }
877   const unsigned InstSubclass = getInstSubclass(Opc, *TII);
878 
879   // Do not merge VMEM buffer instructions with "swizzled" bit set.
880   int Swizzled =
881       AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AMDGPU::OpName::swz);
882   if (Swizzled != -1 && CI.I->getOperand(Swizzled).getImm())
883     return false;
884 
885   DenseSet<Register> RegDefsToMove;
886   DenseSet<Register> PhysRegUsesToMove;
887   addDefsUsesToList(*CI.I, RegDefsToMove, PhysRegUsesToMove);
888 
889   MachineBasicBlock::iterator E = std::next(Paired.I);
890   MachineBasicBlock::iterator MBBI = std::next(CI.I);
891   MachineBasicBlock::iterator MBBE = CI.I->getParent()->end();
892   for (; MBBI != E; ++MBBI) {
893 
894     if (MBBI == MBBE) {
895       // CombineInfo::Order is a hint on the instruction ordering within the
896       // basic block. This hint suggests that CI precedes Paired, which is
897       // true most of the time. However, moveInstsAfter() processing a
898       // previous list may have changed this order in a situation when it
899       // moves an instruction which exists in some other merge list.
900       // In this case it must be dependent.
901       return false;
902     }
903 
904     if ((getInstClass(MBBI->getOpcode(), *TII) != InstClass) ||
905         (getInstSubclass(MBBI->getOpcode(), *TII) != InstSubclass)) {
906       // This is not a matching instruction, but we can keep looking as
907       // long as one of these conditions are met:
908       // 1. It is safe to move I down past MBBI.
909       // 2. It is safe to move MBBI down past the instruction that I will
910       //    be merged into.
911 
912       if (MBBI->hasUnmodeledSideEffects()) {
913         // We can't re-order this instruction with respect to other memory
914         // operations, so we fail both conditions mentioned above.
915         return false;
916       }
917 
918       if (MBBI->mayLoadOrStore() &&
919           (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
920            !canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA))) {
921         // We fail condition #1, but we may still be able to satisfy condition
922         // #2.  Add this instruction to the move list and then we will check
923         // if condition #2 holds once we have selected the matching instruction.
924         InstsToMove.push_back(&*MBBI);
925         addDefsUsesToList(*MBBI, RegDefsToMove, PhysRegUsesToMove);
926         continue;
927       }
928 
929       // When we match I with another DS instruction we will be moving I down
930       // to the location of the matched instruction any uses of I will need to
931       // be moved down as well.
932       addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
933                             InstsToMove);
934       continue;
935     }
936 
937     // Don't merge volatiles.
938     if (MBBI->hasOrderedMemoryRef())
939       return false;
940 
941     int Swizzled =
942         AMDGPU::getNamedOperandIdx(MBBI->getOpcode(), AMDGPU::OpName::swz);
943     if (Swizzled != -1 && MBBI->getOperand(Swizzled).getImm())
944       return false;
945 
946     // Handle a case like
947     //   DS_WRITE_B32 addr, v, idx0
948     //   w = DS_READ_B32 addr, idx0
949     //   DS_WRITE_B32 addr, f(w), idx1
950     // where the DS_READ_B32 ends up in InstsToMove and therefore prevents
951     // merging of the two writes.
952     if (addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
953                               InstsToMove))
954       continue;
955 
956     if (&*MBBI == &*Paired.I) {
957       // We need to go through the list of instructions that we plan to
958       // move and make sure they are all safe to move down past the merged
959       // instruction.
960       if (canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA)) {
961 
962         // Call offsetsCanBeCombined with modify = true so that the offsets are
963         // correct for the new instruction.  This should return true, because
964         // this function should only be called on CombineInfo objects that
965         // have already been confirmed to be mergeable.
966         if (CI.InstClass != MIMG)
967           offsetsCanBeCombined(CI, *STM, Paired, true);
968         return true;
969       }
970       return false;
971     }
972 
973     // We've found a load/store that we couldn't merge for some reason.
974     // We could potentially keep looking, but we'd need to make sure that
975     // it was safe to move I and also all the instruction in InstsToMove
976     // down past this instruction.
977     // check if we can move I across MBBI and if we can move all I's users
978     if (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
979         !canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA))
980       break;
981   }
982   return false;
983 }
984 
985 unsigned SILoadStoreOptimizer::read2Opcode(unsigned EltSize) const {
986   if (STM->ldsRequiresM0Init())
987     return (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
988   return (EltSize == 4) ? AMDGPU::DS_READ2_B32_gfx9 : AMDGPU::DS_READ2_B64_gfx9;
989 }
990 
991 unsigned SILoadStoreOptimizer::read2ST64Opcode(unsigned EltSize) const {
992   if (STM->ldsRequiresM0Init())
993     return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;
994 
995   return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32_gfx9
996                         : AMDGPU::DS_READ2ST64_B64_gfx9;
997 }
998 
999 MachineBasicBlock::iterator
1000 SILoadStoreOptimizer::mergeRead2Pair(CombineInfo &CI, CombineInfo &Paired,
1001     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1002   MachineBasicBlock *MBB = CI.I->getParent();
1003 
1004   // Be careful, since the addresses could be subregisters themselves in weird
1005   // cases, like vectors of pointers.
1006   const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1007 
1008   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdst);
1009   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdst);
1010 
1011   unsigned NewOffset0 = CI.Offset;
1012   unsigned NewOffset1 = Paired.Offset;
1013   unsigned Opc =
1014       CI.UseST64 ? read2ST64Opcode(CI.EltSize) : read2Opcode(CI.EltSize);
1015 
1016   unsigned SubRegIdx0 = (CI.EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
1017   unsigned SubRegIdx1 = (CI.EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;
1018 
1019   if (NewOffset0 > NewOffset1) {
1020     // Canonicalize the merged instruction so the smaller offset comes first.
1021     std::swap(NewOffset0, NewOffset1);
1022     std::swap(SubRegIdx0, SubRegIdx1);
1023   }
1024 
1025   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1026          (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1027 
1028   const MCInstrDesc &Read2Desc = TII->get(Opc);
1029 
1030   const TargetRegisterClass *SuperRC =
1031       (CI.EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass;
1032   Register DestReg = MRI->createVirtualRegister(SuperRC);
1033 
1034   DebugLoc DL = CI.I->getDebugLoc();
1035 
1036   Register BaseReg = AddrReg->getReg();
1037   unsigned BaseSubReg = AddrReg->getSubReg();
1038   unsigned BaseRegFlags = 0;
1039   if (CI.BaseOff) {
1040     Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1041     BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1042         .addImm(CI.BaseOff);
1043 
1044     BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1045     BaseRegFlags = RegState::Kill;
1046 
1047     TII->getAddNoCarry(*MBB, Paired.I, DL, BaseReg)
1048         .addReg(ImmReg)
1049         .addReg(AddrReg->getReg(), 0, BaseSubReg)
1050         .addImm(0); // clamp bit
1051     BaseSubReg = 0;
1052   }
1053 
1054   MachineInstrBuilder Read2 =
1055       BuildMI(*MBB, Paired.I, DL, Read2Desc, DestReg)
1056           .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
1057           .addImm(NewOffset0)                        // offset0
1058           .addImm(NewOffset1)                        // offset1
1059           .addImm(0)                                 // gds
1060           .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1061 
1062   (void)Read2;
1063 
1064   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1065 
1066   // Copy to the old destination registers.
1067   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1068       .add(*Dest0) // Copy to same destination including flags and sub reg.
1069       .addReg(DestReg, 0, SubRegIdx0);
1070   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1071                             .add(*Dest1)
1072                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1073 
1074   moveInstsAfter(Copy1, InstsToMove);
1075 
1076   CI.I->eraseFromParent();
1077   Paired.I->eraseFromParent();
1078 
1079   LLVM_DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
1080   return Read2;
1081 }
1082 
1083 unsigned SILoadStoreOptimizer::write2Opcode(unsigned EltSize) const {
1084   if (STM->ldsRequiresM0Init())
1085     return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
1086   return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32_gfx9
1087                         : AMDGPU::DS_WRITE2_B64_gfx9;
1088 }
1089 
1090 unsigned SILoadStoreOptimizer::write2ST64Opcode(unsigned EltSize) const {
1091   if (STM->ldsRequiresM0Init())
1092     return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32
1093                           : AMDGPU::DS_WRITE2ST64_B64;
1094 
1095   return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32_gfx9
1096                         : AMDGPU::DS_WRITE2ST64_B64_gfx9;
1097 }
1098 
1099 MachineBasicBlock::iterator
1100 SILoadStoreOptimizer::mergeWrite2Pair(CombineInfo &CI, CombineInfo &Paired,
1101                                       const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1102   MachineBasicBlock *MBB = CI.I->getParent();
1103 
1104   // Be sure to use .addOperand(), and not .addReg() with these. We want to be
1105   // sure we preserve the subregister index and any register flags set on them.
1106   const MachineOperand *AddrReg =
1107       TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1108   const MachineOperand *Data0 =
1109       TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
1110   const MachineOperand *Data1 =
1111       TII->getNamedOperand(*Paired.I, AMDGPU::OpName::data0);
1112 
1113   unsigned NewOffset0 = CI.Offset;
1114   unsigned NewOffset1 = Paired.Offset;
1115   unsigned Opc =
1116       CI.UseST64 ? write2ST64Opcode(CI.EltSize) : write2Opcode(CI.EltSize);
1117 
1118   if (NewOffset0 > NewOffset1) {
1119     // Canonicalize the merged instruction so the smaller offset comes first.
1120     std::swap(NewOffset0, NewOffset1);
1121     std::swap(Data0, Data1);
1122   }
1123 
1124   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1125          (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1126 
1127   const MCInstrDesc &Write2Desc = TII->get(Opc);
1128   DebugLoc DL = CI.I->getDebugLoc();
1129 
1130   Register BaseReg = AddrReg->getReg();
1131   unsigned BaseSubReg = AddrReg->getSubReg();
1132   unsigned BaseRegFlags = 0;
1133   if (CI.BaseOff) {
1134     Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1135     BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1136         .addImm(CI.BaseOff);
1137 
1138     BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1139     BaseRegFlags = RegState::Kill;
1140 
1141     TII->getAddNoCarry(*MBB, Paired.I, DL, BaseReg)
1142         .addReg(ImmReg)
1143         .addReg(AddrReg->getReg(), 0, BaseSubReg)
1144         .addImm(0); // clamp bit
1145     BaseSubReg = 0;
1146   }
1147 
1148   MachineInstrBuilder Write2 =
1149       BuildMI(*MBB, Paired.I, DL, Write2Desc)
1150           .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
1151           .add(*Data0)                               // data0
1152           .add(*Data1)                               // data1
1153           .addImm(NewOffset0)                        // offset0
1154           .addImm(NewOffset1)                        // offset1
1155           .addImm(0)                                 // gds
1156           .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1157 
1158   moveInstsAfter(Write2, InstsToMove);
1159 
1160   CI.I->eraseFromParent();
1161   Paired.I->eraseFromParent();
1162 
1163   LLVM_DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
1164   return Write2;
1165 }
1166 
1167 MachineBasicBlock::iterator
1168 SILoadStoreOptimizer::mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
1169                            const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1170   MachineBasicBlock *MBB = CI.I->getParent();
1171   DebugLoc DL = CI.I->getDebugLoc();
1172   const unsigned Opcode = getNewOpcode(CI, Paired);
1173 
1174   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1175 
1176   Register DestReg = MRI->createVirtualRegister(SuperRC);
1177   unsigned MergedDMask = CI.DMask | Paired.DMask;
1178   unsigned DMaskIdx =
1179       AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AMDGPU::OpName::dmask);
1180 
1181   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1182   for (unsigned I = 1, E = (*CI.I).getNumOperands(); I != E; ++I) {
1183     if (I == DMaskIdx)
1184       MIB.addImm(MergedDMask);
1185     else
1186       MIB.add((*CI.I).getOperand(I));
1187   }
1188 
1189   // It shouldn't be possible to get this far if the two instructions
1190   // don't have a single memoperand, because MachineInstr::mayAlias()
1191   // will return true if this is the case.
1192   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1193 
1194   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1195   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1196 
1197   MachineInstr *New = MIB.addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1198 
1199   unsigned SubRegIdx0, SubRegIdx1;
1200   std::tie(SubRegIdx0, SubRegIdx1) = getSubRegIdxs(CI, Paired);
1201 
1202   // Copy to the old destination registers.
1203   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1204   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1205   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1206 
1207   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1208       .add(*Dest0) // Copy to same destination including flags and sub reg.
1209       .addReg(DestReg, 0, SubRegIdx0);
1210   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1211                             .add(*Dest1)
1212                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1213 
1214   moveInstsAfter(Copy1, InstsToMove);
1215 
1216   CI.I->eraseFromParent();
1217   Paired.I->eraseFromParent();
1218   return New;
1219 }
1220 
1221 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeSBufferLoadImmPair(
1222     CombineInfo &CI, CombineInfo &Paired,
1223     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1224   MachineBasicBlock *MBB = CI.I->getParent();
1225   DebugLoc DL = CI.I->getDebugLoc();
1226   const unsigned Opcode = getNewOpcode(CI, Paired);
1227 
1228   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1229 
1230   Register DestReg = MRI->createVirtualRegister(SuperRC);
1231   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1232 
1233   // It shouldn't be possible to get this far if the two instructions
1234   // don't have a single memoperand, because MachineInstr::mayAlias()
1235   // will return true if this is the case.
1236   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1237 
1238   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1239   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1240 
1241   MachineInstr *New =
1242     BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg)
1243         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::sbase))
1244         .addImm(MergedOffset) // offset
1245         .addImm(CI.GLC)      // glc
1246         .addImm(CI.DLC)      // dlc
1247         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1248 
1249   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1250   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1251   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1252 
1253   // Copy to the old destination registers.
1254   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1255   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::sdst);
1256   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::sdst);
1257 
1258   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1259       .add(*Dest0) // Copy to same destination including flags and sub reg.
1260       .addReg(DestReg, 0, SubRegIdx0);
1261   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1262                             .add(*Dest1)
1263                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1264 
1265   moveInstsAfter(Copy1, InstsToMove);
1266 
1267   CI.I->eraseFromParent();
1268   Paired.I->eraseFromParent();
1269   return New;
1270 }
1271 
1272 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferLoadPair(
1273     CombineInfo &CI, CombineInfo &Paired,
1274     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1275   MachineBasicBlock *MBB = CI.I->getParent();
1276   DebugLoc DL = CI.I->getDebugLoc();
1277 
1278   const unsigned Opcode = getNewOpcode(CI, Paired);
1279 
1280   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1281 
1282   // Copy to the new source register.
1283   Register DestReg = MRI->createVirtualRegister(SuperRC);
1284   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1285 
1286   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1287 
1288   AddressRegs Regs = getRegs(Opcode, *TII);
1289 
1290   if (Regs.VAddr)
1291     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1292 
1293   // It shouldn't be possible to get this far if the two instructions
1294   // don't have a single memoperand, because MachineInstr::mayAlias()
1295   // will return true if this is the case.
1296   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1297 
1298   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1299   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1300 
1301   MachineInstr *New =
1302     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1303         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1304         .addImm(MergedOffset) // offset
1305         .addImm(CI.GLC)      // glc
1306         .addImm(CI.SLC)      // slc
1307         .addImm(0)            // tfe
1308         .addImm(CI.DLC)      // dlc
1309         .addImm(0)            // swz
1310         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1311 
1312   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1313   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1314   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1315 
1316   // Copy to the old destination registers.
1317   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1318   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1319   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1320 
1321   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1322       .add(*Dest0) // Copy to same destination including flags and sub reg.
1323       .addReg(DestReg, 0, SubRegIdx0);
1324   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1325                             .add(*Dest1)
1326                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1327 
1328   moveInstsAfter(Copy1, InstsToMove);
1329 
1330   CI.I->eraseFromParent();
1331   Paired.I->eraseFromParent();
1332   return New;
1333 }
1334 
1335 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferLoadPair(
1336     CombineInfo &CI, CombineInfo &Paired,
1337     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1338   MachineBasicBlock *MBB = CI.I->getParent();
1339   DebugLoc DL = CI.I->getDebugLoc();
1340 
1341   const unsigned Opcode = getNewOpcode(CI, Paired);
1342 
1343   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1344 
1345   // Copy to the new source register.
1346   Register DestReg = MRI->createVirtualRegister(SuperRC);
1347   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1348 
1349   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1350 
1351   AddressRegs Regs = getRegs(Opcode, *TII);
1352 
1353   if (Regs.VAddr)
1354     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1355 
1356   unsigned JoinedFormat =
1357       getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, *STM);
1358 
1359   // It shouldn't be possible to get this far if the two instructions
1360   // don't have a single memoperand, because MachineInstr::mayAlias()
1361   // will return true if this is the case.
1362   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1363 
1364   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1365   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1366 
1367   MachineInstr *New =
1368       MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1369           .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1370           .addImm(MergedOffset) // offset
1371           .addImm(JoinedFormat) // format
1372           .addImm(CI.GLC)      // glc
1373           .addImm(CI.SLC)      // slc
1374           .addImm(0)            // tfe
1375           .addImm(CI.DLC)      // dlc
1376           .addImm(0)            // swz
1377           .addMemOperand(
1378               combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1379 
1380   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1381   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1382   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1383 
1384   // Copy to the old destination registers.
1385   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1386   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1387   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1388 
1389   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1390       .add(*Dest0) // Copy to same destination including flags and sub reg.
1391       .addReg(DestReg, 0, SubRegIdx0);
1392   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1393                             .add(*Dest1)
1394                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1395 
1396   moveInstsAfter(Copy1, InstsToMove);
1397 
1398   CI.I->eraseFromParent();
1399   Paired.I->eraseFromParent();
1400   return New;
1401 }
1402 
1403 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferStorePair(
1404     CombineInfo &CI, CombineInfo &Paired,
1405     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1406   MachineBasicBlock *MBB = CI.I->getParent();
1407   DebugLoc DL = CI.I->getDebugLoc();
1408 
1409   const unsigned Opcode = getNewOpcode(CI, Paired);
1410 
1411   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1412   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1413   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1414 
1415   // Copy to the new source register.
1416   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1417   Register SrcReg = MRI->createVirtualRegister(SuperRC);
1418 
1419   const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1420   const auto *Src1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1421 
1422   BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
1423       .add(*Src0)
1424       .addImm(SubRegIdx0)
1425       .add(*Src1)
1426       .addImm(SubRegIdx1);
1427 
1428   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode))
1429                  .addReg(SrcReg, RegState::Kill);
1430 
1431   AddressRegs Regs = getRegs(Opcode, *TII);
1432 
1433   if (Regs.VAddr)
1434     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1435 
1436   unsigned JoinedFormat =
1437       getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, *STM);
1438 
1439   // It shouldn't be possible to get this far if the two instructions
1440   // don't have a single memoperand, because MachineInstr::mayAlias()
1441   // will return true if this is the case.
1442   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1443 
1444   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1445   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1446 
1447   MachineInstr *New =
1448       MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1449           .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1450           .addImm(std::min(CI.Offset, Paired.Offset)) // offset
1451           .addImm(JoinedFormat)                     // format
1452           .addImm(CI.GLC)                          // glc
1453           .addImm(CI.SLC)                          // slc
1454           .addImm(0)                                // tfe
1455           .addImm(CI.DLC)                          // dlc
1456           .addImm(0)                                // swz
1457           .addMemOperand(
1458               combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1459 
1460   moveInstsAfter(MIB, InstsToMove);
1461 
1462   CI.I->eraseFromParent();
1463   Paired.I->eraseFromParent();
1464   return New;
1465 }
1466 
1467 unsigned SILoadStoreOptimizer::getNewOpcode(const CombineInfo &CI,
1468                                             const CombineInfo &Paired) {
1469   const unsigned Width = CI.Width + Paired.Width;
1470 
1471   switch (CI.InstClass) {
1472   default:
1473     assert(CI.InstClass == BUFFER_LOAD || CI.InstClass == BUFFER_STORE);
1474     // FIXME: Handle d16 correctly
1475     return AMDGPU::getMUBUFOpcode(AMDGPU::getMUBUFBaseOpcode(CI.I->getOpcode()),
1476                                   Width);
1477   case TBUFFER_LOAD:
1478   case TBUFFER_STORE:
1479     return AMDGPU::getMTBUFOpcode(AMDGPU::getMTBUFBaseOpcode(CI.I->getOpcode()),
1480                                   Width);
1481 
1482   case UNKNOWN:
1483     llvm_unreachable("Unknown instruction class");
1484   case S_BUFFER_LOAD_IMM:
1485     switch (Width) {
1486     default:
1487       return 0;
1488     case 2:
1489       return AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;
1490     case 4:
1491       return AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM;
1492     }
1493   case MIMG:
1494     assert("No overlaps" && (countPopulation(CI.DMask | Paired.DMask) == Width));
1495     return AMDGPU::getMaskedMIMGOp(CI.I->getOpcode(), Width);
1496   }
1497 }
1498 
1499 std::pair<unsigned, unsigned>
1500 SILoadStoreOptimizer::getSubRegIdxs(const CombineInfo &CI, const CombineInfo &Paired) {
1501 
1502   if (CI.Width == 0 || Paired.Width == 0 || CI.Width + Paired.Width > 4)
1503     return std::make_pair(0, 0);
1504 
1505   bool ReverseOrder;
1506   if (CI.InstClass == MIMG) {
1507     assert((countPopulation(CI.DMask | Paired.DMask) == CI.Width + Paired.Width) &&
1508            "No overlaps");
1509     ReverseOrder = CI.DMask > Paired.DMask;
1510   } else
1511     ReverseOrder = CI.Offset > Paired.Offset;
1512 
1513   static const unsigned Idxs[4][4] = {
1514       {AMDGPU::sub0, AMDGPU::sub0_sub1, AMDGPU::sub0_sub1_sub2, AMDGPU::sub0_sub1_sub2_sub3},
1515       {AMDGPU::sub1, AMDGPU::sub1_sub2, AMDGPU::sub1_sub2_sub3, 0},
1516       {AMDGPU::sub2, AMDGPU::sub2_sub3, 0, 0},
1517       {AMDGPU::sub3, 0, 0, 0},
1518   };
1519   unsigned Idx0;
1520   unsigned Idx1;
1521 
1522   assert(CI.Width >= 1 && CI.Width <= 3);
1523   assert(Paired.Width >= 1 && Paired.Width <= 3);
1524 
1525   if (ReverseOrder) {
1526     Idx1 = Idxs[0][Paired.Width - 1];
1527     Idx0 = Idxs[Paired.Width][CI.Width - 1];
1528   } else {
1529     Idx0 = Idxs[0][CI.Width - 1];
1530     Idx1 = Idxs[CI.Width][Paired.Width - 1];
1531   }
1532 
1533   return std::make_pair(Idx0, Idx1);
1534 }
1535 
1536 const TargetRegisterClass *
1537 SILoadStoreOptimizer::getTargetRegisterClass(const CombineInfo &CI,
1538                                              const CombineInfo &Paired) {
1539   if (CI.InstClass == S_BUFFER_LOAD_IMM) {
1540     switch (CI.Width + Paired.Width) {
1541     default:
1542       return nullptr;
1543     case 2:
1544       return &AMDGPU::SReg_64_XEXECRegClass;
1545     case 4:
1546       return &AMDGPU::SGPR_128RegClass;
1547     case 8:
1548       return &AMDGPU::SGPR_256RegClass;
1549     case 16:
1550       return &AMDGPU::SGPR_512RegClass;
1551     }
1552   } else {
1553     switch (CI.Width + Paired.Width) {
1554     default:
1555       return nullptr;
1556     case 2:
1557       return &AMDGPU::VReg_64RegClass;
1558     case 3:
1559       return &AMDGPU::VReg_96RegClass;
1560     case 4:
1561       return &AMDGPU::VReg_128RegClass;
1562     }
1563   }
1564 }
1565 
1566 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferStorePair(
1567     CombineInfo &CI, CombineInfo &Paired,
1568     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1569   MachineBasicBlock *MBB = CI.I->getParent();
1570   DebugLoc DL = CI.I->getDebugLoc();
1571 
1572   const unsigned Opcode = getNewOpcode(CI, Paired);
1573 
1574   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1575   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1576   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1577 
1578   // Copy to the new source register.
1579   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1580   Register SrcReg = MRI->createVirtualRegister(SuperRC);
1581 
1582   const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1583   const auto *Src1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1584 
1585   BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
1586       .add(*Src0)
1587       .addImm(SubRegIdx0)
1588       .add(*Src1)
1589       .addImm(SubRegIdx1);
1590 
1591   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode))
1592                  .addReg(SrcReg, RegState::Kill);
1593 
1594   AddressRegs Regs = getRegs(Opcode, *TII);
1595 
1596   if (Regs.VAddr)
1597     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1598 
1599 
1600   // It shouldn't be possible to get this far if the two instructions
1601   // don't have a single memoperand, because MachineInstr::mayAlias()
1602   // will return true if this is the case.
1603   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1604 
1605   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1606   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1607 
1608   MachineInstr *New =
1609     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1610         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1611         .addImm(std::min(CI.Offset, Paired.Offset)) // offset
1612         .addImm(CI.GLC)      // glc
1613         .addImm(CI.SLC)      // slc
1614         .addImm(0)            // tfe
1615         .addImm(CI.DLC)      // dlc
1616         .addImm(0)            // swz
1617         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1618 
1619   moveInstsAfter(MIB, InstsToMove);
1620 
1621   CI.I->eraseFromParent();
1622   Paired.I->eraseFromParent();
1623   return New;
1624 }
1625 
1626 MachineOperand
1627 SILoadStoreOptimizer::createRegOrImm(int32_t Val, MachineInstr &MI) const {
1628   APInt V(32, Val, true);
1629   if (TII->isInlineConstant(V))
1630     return MachineOperand::CreateImm(Val);
1631 
1632   Register Reg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1633   MachineInstr *Mov =
1634   BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1635           TII->get(AMDGPU::S_MOV_B32), Reg)
1636     .addImm(Val);
1637   (void)Mov;
1638   LLVM_DEBUG(dbgs() << "    "; Mov->dump());
1639   return MachineOperand::CreateReg(Reg, false);
1640 }
1641 
1642 // Compute base address using Addr and return the final register.
1643 Register SILoadStoreOptimizer::computeBase(MachineInstr &MI,
1644                                            const MemAddress &Addr) const {
1645   MachineBasicBlock *MBB = MI.getParent();
1646   MachineBasicBlock::iterator MBBI = MI.getIterator();
1647   DebugLoc DL = MI.getDebugLoc();
1648 
1649   assert((TRI->getRegSizeInBits(Addr.Base.LoReg, *MRI) == 32 ||
1650           Addr.Base.LoSubReg) &&
1651          "Expected 32-bit Base-Register-Low!!");
1652 
1653   assert((TRI->getRegSizeInBits(Addr.Base.HiReg, *MRI) == 32 ||
1654           Addr.Base.HiSubReg) &&
1655          "Expected 32-bit Base-Register-Hi!!");
1656 
1657   LLVM_DEBUG(dbgs() << "  Re-Computed Anchor-Base:\n");
1658   MachineOperand OffsetLo = createRegOrImm(static_cast<int32_t>(Addr.Offset), MI);
1659   MachineOperand OffsetHi =
1660     createRegOrImm(static_cast<int32_t>(Addr.Offset >> 32), MI);
1661 
1662   const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
1663   Register CarryReg = MRI->createVirtualRegister(CarryRC);
1664   Register DeadCarryReg = MRI->createVirtualRegister(CarryRC);
1665 
1666   Register DestSub0 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1667   Register DestSub1 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1668   MachineInstr *LoHalf =
1669     BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_CO_U32_e64), DestSub0)
1670       .addReg(CarryReg, RegState::Define)
1671       .addReg(Addr.Base.LoReg, 0, Addr.Base.LoSubReg)
1672       .add(OffsetLo)
1673       .addImm(0); // clamp bit
1674   (void)LoHalf;
1675   LLVM_DEBUG(dbgs() << "    "; LoHalf->dump(););
1676 
1677   MachineInstr *HiHalf =
1678   BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADDC_U32_e64), DestSub1)
1679     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
1680     .addReg(Addr.Base.HiReg, 0, Addr.Base.HiSubReg)
1681     .add(OffsetHi)
1682     .addReg(CarryReg, RegState::Kill)
1683     .addImm(0); // clamp bit
1684   (void)HiHalf;
1685   LLVM_DEBUG(dbgs() << "    "; HiHalf->dump(););
1686 
1687   Register FullDestReg = MRI->createVirtualRegister(&AMDGPU::VReg_64RegClass);
1688   MachineInstr *FullBase =
1689     BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::REG_SEQUENCE), FullDestReg)
1690       .addReg(DestSub0)
1691       .addImm(AMDGPU::sub0)
1692       .addReg(DestSub1)
1693       .addImm(AMDGPU::sub1);
1694   (void)FullBase;
1695   LLVM_DEBUG(dbgs() << "    "; FullBase->dump(); dbgs() << "\n";);
1696 
1697   return FullDestReg;
1698 }
1699 
1700 // Update base and offset with the NewBase and NewOffset in MI.
1701 void SILoadStoreOptimizer::updateBaseAndOffset(MachineInstr &MI,
1702                                                Register NewBase,
1703                                                int32_t NewOffset) const {
1704   auto Base = TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
1705   Base->setReg(NewBase);
1706   Base->setIsKill(false);
1707   TII->getNamedOperand(MI, AMDGPU::OpName::offset)->setImm(NewOffset);
1708 }
1709 
1710 Optional<int32_t>
1711 SILoadStoreOptimizer::extractConstOffset(const MachineOperand &Op) const {
1712   if (Op.isImm())
1713     return Op.getImm();
1714 
1715   if (!Op.isReg())
1716     return None;
1717 
1718   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
1719   if (!Def || Def->getOpcode() != AMDGPU::S_MOV_B32 ||
1720       !Def->getOperand(1).isImm())
1721     return None;
1722 
1723   return Def->getOperand(1).getImm();
1724 }
1725 
1726 // Analyze Base and extracts:
1727 //  - 32bit base registers, subregisters
1728 //  - 64bit constant offset
1729 // Expecting base computation as:
1730 //   %OFFSET0:sgpr_32 = S_MOV_B32 8000
1731 //   %LO:vgpr_32, %c:sreg_64_xexec =
1732 //       V_ADD_CO_U32_e64 %BASE_LO:vgpr_32, %103:sgpr_32,
1733 //   %HI:vgpr_32, = V_ADDC_U32_e64 %BASE_HI:vgpr_32, 0, killed %c:sreg_64_xexec
1734 //   %Base:vreg_64 =
1735 //       REG_SEQUENCE %LO:vgpr_32, %subreg.sub0, %HI:vgpr_32, %subreg.sub1
1736 void SILoadStoreOptimizer::processBaseWithConstOffset(const MachineOperand &Base,
1737                                                       MemAddress &Addr) const {
1738   if (!Base.isReg())
1739     return;
1740 
1741   MachineInstr *Def = MRI->getUniqueVRegDef(Base.getReg());
1742   if (!Def || Def->getOpcode() != AMDGPU::REG_SEQUENCE
1743       || Def->getNumOperands() != 5)
1744     return;
1745 
1746   MachineOperand BaseLo = Def->getOperand(1);
1747   MachineOperand BaseHi = Def->getOperand(3);
1748   if (!BaseLo.isReg() || !BaseHi.isReg())
1749     return;
1750 
1751   MachineInstr *BaseLoDef = MRI->getUniqueVRegDef(BaseLo.getReg());
1752   MachineInstr *BaseHiDef = MRI->getUniqueVRegDef(BaseHi.getReg());
1753 
1754   if (!BaseLoDef || BaseLoDef->getOpcode() != AMDGPU::V_ADD_CO_U32_e64 ||
1755       !BaseHiDef || BaseHiDef->getOpcode() != AMDGPU::V_ADDC_U32_e64)
1756     return;
1757 
1758   const auto *Src0 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src0);
1759   const auto *Src1 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src1);
1760 
1761   auto Offset0P = extractConstOffset(*Src0);
1762   if (Offset0P)
1763     BaseLo = *Src1;
1764   else {
1765     if (!(Offset0P = extractConstOffset(*Src1)))
1766       return;
1767     BaseLo = *Src0;
1768   }
1769 
1770   Src0 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src0);
1771   Src1 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src1);
1772 
1773   if (Src0->isImm())
1774     std::swap(Src0, Src1);
1775 
1776   if (!Src1->isImm())
1777     return;
1778 
1779   uint64_t Offset1 = Src1->getImm();
1780   BaseHi = *Src0;
1781 
1782   Addr.Base.LoReg = BaseLo.getReg();
1783   Addr.Base.HiReg = BaseHi.getReg();
1784   Addr.Base.LoSubReg = BaseLo.getSubReg();
1785   Addr.Base.HiSubReg = BaseHi.getSubReg();
1786   Addr.Offset = (*Offset0P & 0x00000000ffffffff) | (Offset1 << 32);
1787 }
1788 
1789 bool SILoadStoreOptimizer::promoteConstantOffsetToImm(
1790     MachineInstr &MI,
1791     MemInfoMap &Visited,
1792     SmallPtrSet<MachineInstr *, 4> &AnchorList) const {
1793 
1794   if (!(MI.mayLoad() ^ MI.mayStore()))
1795     return false;
1796 
1797   // TODO: Support flat and scratch.
1798   if (AMDGPU::getGlobalSaddrOp(MI.getOpcode()) < 0)
1799     return false;
1800 
1801   if (MI.mayLoad() && TII->getNamedOperand(MI, AMDGPU::OpName::vdata) != NULL)
1802     return false;
1803 
1804   if (AnchorList.count(&MI))
1805     return false;
1806 
1807   LLVM_DEBUG(dbgs() << "\nTryToPromoteConstantOffsetToImmFor "; MI.dump());
1808 
1809   if (TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm()) {
1810     LLVM_DEBUG(dbgs() << "  Const-offset is already promoted.\n";);
1811     return false;
1812   }
1813 
1814   // Step1: Find the base-registers and a 64bit constant offset.
1815   MachineOperand &Base = *TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
1816   MemAddress MAddr;
1817   if (Visited.find(&MI) == Visited.end()) {
1818     processBaseWithConstOffset(Base, MAddr);
1819     Visited[&MI] = MAddr;
1820   } else
1821     MAddr = Visited[&MI];
1822 
1823   if (MAddr.Offset == 0) {
1824     LLVM_DEBUG(dbgs() << "  Failed to extract constant-offset or there are no"
1825                          " constant offsets that can be promoted.\n";);
1826     return false;
1827   }
1828 
1829   LLVM_DEBUG(dbgs() << "  BASE: {" << MAddr.Base.HiReg << ", "
1830              << MAddr.Base.LoReg << "} Offset: " << MAddr.Offset << "\n\n";);
1831 
1832   // Step2: Traverse through MI's basic block and find an anchor(that has the
1833   // same base-registers) with the highest 13bit distance from MI's offset.
1834   // E.g. (64bit loads)
1835   // bb:
1836   //   addr1 = &a + 4096;   load1 = load(addr1,  0)
1837   //   addr2 = &a + 6144;   load2 = load(addr2,  0)
1838   //   addr3 = &a + 8192;   load3 = load(addr3,  0)
1839   //   addr4 = &a + 10240;  load4 = load(addr4,  0)
1840   //   addr5 = &a + 12288;  load5 = load(addr5,  0)
1841   //
1842   // Starting from the first load, the optimization will try to find a new base
1843   // from which (&a + 4096) has 13 bit distance. Both &a + 6144 and &a + 8192
1844   // has 13bit distance from &a + 4096. The heuristic considers &a + 8192
1845   // as the new-base(anchor) because of the maximum distance which can
1846   // accomodate more intermediate bases presumeably.
1847   //
1848   // Step3: move (&a + 8192) above load1. Compute and promote offsets from
1849   // (&a + 8192) for load1, load2, load4.
1850   //   addr = &a + 8192
1851   //   load1 = load(addr,       -4096)
1852   //   load2 = load(addr,       -2048)
1853   //   load3 = load(addr,       0)
1854   //   load4 = load(addr,       2048)
1855   //   addr5 = &a + 12288;  load5 = load(addr5,  0)
1856   //
1857   MachineInstr *AnchorInst = nullptr;
1858   MemAddress AnchorAddr;
1859   uint32_t MaxDist = std::numeric_limits<uint32_t>::min();
1860   SmallVector<std::pair<MachineInstr *, int64_t>, 4> InstsWCommonBase;
1861 
1862   MachineBasicBlock *MBB = MI.getParent();
1863   MachineBasicBlock::iterator E = MBB->end();
1864   MachineBasicBlock::iterator MBBI = MI.getIterator();
1865   ++MBBI;
1866   const SITargetLowering *TLI =
1867     static_cast<const SITargetLowering *>(STM->getTargetLowering());
1868 
1869   for ( ; MBBI != E; ++MBBI) {
1870     MachineInstr &MINext = *MBBI;
1871     // TODO: Support finding an anchor(with same base) from store addresses or
1872     // any other load addresses where the opcodes are different.
1873     if (MINext.getOpcode() != MI.getOpcode() ||
1874         TII->getNamedOperand(MINext, AMDGPU::OpName::offset)->getImm())
1875       continue;
1876 
1877     const MachineOperand &BaseNext =
1878       *TII->getNamedOperand(MINext, AMDGPU::OpName::vaddr);
1879     MemAddress MAddrNext;
1880     if (Visited.find(&MINext) == Visited.end()) {
1881       processBaseWithConstOffset(BaseNext, MAddrNext);
1882       Visited[&MINext] = MAddrNext;
1883     } else
1884       MAddrNext = Visited[&MINext];
1885 
1886     if (MAddrNext.Base.LoReg != MAddr.Base.LoReg ||
1887         MAddrNext.Base.HiReg != MAddr.Base.HiReg ||
1888         MAddrNext.Base.LoSubReg != MAddr.Base.LoSubReg ||
1889         MAddrNext.Base.HiSubReg != MAddr.Base.HiSubReg)
1890       continue;
1891 
1892     InstsWCommonBase.push_back(std::make_pair(&MINext, MAddrNext.Offset));
1893 
1894     int64_t Dist = MAddr.Offset - MAddrNext.Offset;
1895     TargetLoweringBase::AddrMode AM;
1896     AM.HasBaseReg = true;
1897     AM.BaseOffs = Dist;
1898     if (TLI->isLegalGlobalAddressingMode(AM) &&
1899         (uint32_t)std::abs(Dist) > MaxDist) {
1900       MaxDist = std::abs(Dist);
1901 
1902       AnchorAddr = MAddrNext;
1903       AnchorInst = &MINext;
1904     }
1905   }
1906 
1907   if (AnchorInst) {
1908     LLVM_DEBUG(dbgs() << "  Anchor-Inst(with max-distance from Offset): ";
1909                AnchorInst->dump());
1910     LLVM_DEBUG(dbgs() << "  Anchor-Offset from BASE: "
1911                <<  AnchorAddr.Offset << "\n\n");
1912 
1913     // Instead of moving up, just re-compute anchor-instruction's base address.
1914     Register Base = computeBase(MI, AnchorAddr);
1915 
1916     updateBaseAndOffset(MI, Base, MAddr.Offset - AnchorAddr.Offset);
1917     LLVM_DEBUG(dbgs() << "  After promotion: "; MI.dump(););
1918 
1919     for (auto P : InstsWCommonBase) {
1920       TargetLoweringBase::AddrMode AM;
1921       AM.HasBaseReg = true;
1922       AM.BaseOffs = P.second - AnchorAddr.Offset;
1923 
1924       if (TLI->isLegalGlobalAddressingMode(AM)) {
1925         LLVM_DEBUG(dbgs() << "  Promote Offset(" << P.second;
1926                    dbgs() << ")"; P.first->dump());
1927         updateBaseAndOffset(*P.first, Base, P.second - AnchorAddr.Offset);
1928         LLVM_DEBUG(dbgs() << "     After promotion: "; P.first->dump());
1929       }
1930     }
1931     AnchorList.insert(AnchorInst);
1932     return true;
1933   }
1934 
1935   return false;
1936 }
1937 
1938 void SILoadStoreOptimizer::addInstToMergeableList(const CombineInfo &CI,
1939                  std::list<std::list<CombineInfo> > &MergeableInsts) const {
1940   for (std::list<CombineInfo> &AddrList : MergeableInsts) {
1941     if (AddrList.front().InstClass == CI.InstClass &&
1942         AddrList.front().hasSameBaseAddress(*CI.I)) {
1943       AddrList.emplace_back(CI);
1944       return;
1945     }
1946   }
1947 
1948   // Base address not found, so add a new list.
1949   MergeableInsts.emplace_back(1, CI);
1950 }
1951 
1952 std::pair<MachineBasicBlock::iterator, bool>
1953 SILoadStoreOptimizer::collectMergeableInsts(
1954     MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End,
1955     MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
1956     std::list<std::list<CombineInfo>> &MergeableInsts) const {
1957   bool Modified = false;
1958 
1959   // Sort potential mergeable instructions into lists.  One list per base address.
1960   unsigned Order = 0;
1961   MachineBasicBlock::iterator BlockI = Begin;
1962   for (; BlockI != End; ++BlockI) {
1963     MachineInstr &MI = *BlockI;
1964 
1965     // We run this before checking if an address is mergeable, because it can produce
1966     // better code even if the instructions aren't mergeable.
1967     if (promoteConstantOffsetToImm(MI, Visited, AnchorList))
1968       Modified = true;
1969 
1970     // Don't combine if volatile. We also won't be able to merge across this, so
1971     // break the search. We can look after this barrier for separate merges.
1972     if (MI.hasOrderedMemoryRef()) {
1973       LLVM_DEBUG(dbgs() << "Breaking search on memory fence: " << MI);
1974 
1975       // Search will resume after this instruction in a separate merge list.
1976       ++BlockI;
1977       break;
1978     }
1979 
1980     const InstClassEnum InstClass = getInstClass(MI.getOpcode(), *TII);
1981     if (InstClass == UNKNOWN)
1982       continue;
1983 
1984     CombineInfo CI;
1985     CI.setMI(MI, *TII, *STM);
1986     CI.Order = Order++;
1987 
1988     if (!CI.hasMergeableAddress(*MRI))
1989       continue;
1990 
1991     LLVM_DEBUG(dbgs() << "Mergeable: " << MI);
1992 
1993     addInstToMergeableList(CI, MergeableInsts);
1994   }
1995 
1996   // At this point we have lists of Mergeable instructions.
1997   //
1998   // Part 2: Sort lists by offset and then for each CombineInfo object in the
1999   // list try to find an instruction that can be merged with I.  If an instruction
2000   // is found, it is stored in the Paired field.  If no instructions are found, then
2001   // the CombineInfo object is deleted from the list.
2002 
2003   for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2004                                                    E = MergeableInsts.end(); I != E;) {
2005 
2006     std::list<CombineInfo> &MergeList = *I;
2007     if (MergeList.size() <= 1) {
2008       // This means we have found only one instruction with a given address
2009       // that can be merged, and we need at least 2 instructions to do a merge,
2010       // so this list can be discarded.
2011       I = MergeableInsts.erase(I);
2012       continue;
2013     }
2014 
2015     // Sort the lists by offsets, this way mergeable instructions will be
2016     // adjacent to each other in the list, which will make it easier to find
2017     // matches.
2018     MergeList.sort(
2019         [] (const CombineInfo &A, CombineInfo &B) {
2020           return A.Offset < B.Offset;
2021         });
2022     ++I;
2023   }
2024 
2025   return std::make_pair(BlockI, Modified);
2026 }
2027 
2028 // Scan through looking for adjacent LDS operations with constant offsets from
2029 // the same base register. We rely on the scheduler to do the hard work of
2030 // clustering nearby loads, and assume these are all adjacent.
2031 bool SILoadStoreOptimizer::optimizeBlock(
2032                        std::list<std::list<CombineInfo> > &MergeableInsts) {
2033   bool Modified = false;
2034 
2035   for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2036                                                    E = MergeableInsts.end(); I != E;) {
2037     std::list<CombineInfo> &MergeList = *I;
2038 
2039     bool OptimizeListAgain = false;
2040     if (!optimizeInstsWithSameBaseAddr(MergeList, OptimizeListAgain)) {
2041       // We weren't able to make any changes, so delete the list so we don't
2042       // process the same instructions the next time we try to optimize this
2043       // block.
2044       I = MergeableInsts.erase(I);
2045       continue;
2046     }
2047 
2048     Modified = true;
2049 
2050     // We made changes, but also determined that there were no more optimization
2051     // opportunities, so we don't need to reprocess the list
2052     if (!OptimizeListAgain) {
2053       I = MergeableInsts.erase(I);
2054       continue;
2055     }
2056     OptimizeAgain = true;
2057   }
2058   return Modified;
2059 }
2060 
2061 bool
2062 SILoadStoreOptimizer::optimizeInstsWithSameBaseAddr(
2063                                           std::list<CombineInfo> &MergeList,
2064                                           bool &OptimizeListAgain) {
2065   if (MergeList.empty())
2066     return false;
2067 
2068   bool Modified = false;
2069 
2070   for (auto I = MergeList.begin(), Next = std::next(I); Next != MergeList.end();
2071        Next = std::next(I)) {
2072 
2073     auto First = I;
2074     auto Second = Next;
2075 
2076     if ((*First).Order > (*Second).Order)
2077       std::swap(First, Second);
2078     CombineInfo &CI = *First;
2079     CombineInfo &Paired = *Second;
2080 
2081     SmallVector<MachineInstr *, 8> InstsToMove;
2082     if (!checkAndPrepareMerge(CI, Paired, InstsToMove)) {
2083       ++I;
2084       continue;
2085     }
2086 
2087     Modified = true;
2088 
2089     LLVM_DEBUG(dbgs() << "Merging: " << *CI.I << "   with: " << *Paired.I);
2090 
2091     switch (CI.InstClass) {
2092     default:
2093       llvm_unreachable("unknown InstClass");
2094       break;
2095     case DS_READ: {
2096       MachineBasicBlock::iterator NewMI =
2097           mergeRead2Pair(CI, Paired, InstsToMove);
2098       CI.setMI(NewMI, *TII, *STM);
2099       break;
2100     }
2101     case DS_WRITE: {
2102       MachineBasicBlock::iterator NewMI =
2103           mergeWrite2Pair(CI, Paired, InstsToMove);
2104       CI.setMI(NewMI, *TII, *STM);
2105       break;
2106     }
2107     case S_BUFFER_LOAD_IMM: {
2108       MachineBasicBlock::iterator NewMI =
2109           mergeSBufferLoadImmPair(CI, Paired, InstsToMove);
2110       CI.setMI(NewMI, *TII, *STM);
2111       OptimizeListAgain |= (CI.Width + Paired.Width) < 16;
2112       break;
2113     }
2114     case BUFFER_LOAD: {
2115       MachineBasicBlock::iterator NewMI =
2116           mergeBufferLoadPair(CI, Paired, InstsToMove);
2117       CI.setMI(NewMI, *TII, *STM);
2118       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2119       break;
2120     }
2121     case BUFFER_STORE: {
2122       MachineBasicBlock::iterator NewMI =
2123           mergeBufferStorePair(CI, Paired, InstsToMove);
2124       CI.setMI(NewMI, *TII, *STM);
2125       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2126       break;
2127     }
2128     case MIMG: {
2129       MachineBasicBlock::iterator NewMI =
2130           mergeImagePair(CI, Paired, InstsToMove);
2131       CI.setMI(NewMI, *TII, *STM);
2132       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2133       break;
2134     }
2135     case TBUFFER_LOAD: {
2136       MachineBasicBlock::iterator NewMI =
2137           mergeTBufferLoadPair(CI, Paired, InstsToMove);
2138       CI.setMI(NewMI, *TII, *STM);
2139       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2140       break;
2141     }
2142     case TBUFFER_STORE: {
2143       MachineBasicBlock::iterator NewMI =
2144           mergeTBufferStorePair(CI, Paired, InstsToMove);
2145       CI.setMI(NewMI, *TII, *STM);
2146       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2147       break;
2148     }
2149     }
2150     CI.Order = Paired.Order;
2151     if (I == Second)
2152       I = Next;
2153 
2154     MergeList.erase(Second);
2155   }
2156 
2157   return Modified;
2158 }
2159 
2160 bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
2161   if (skipFunction(MF.getFunction()))
2162     return false;
2163 
2164   STM = &MF.getSubtarget<GCNSubtarget>();
2165   if (!STM->loadStoreOptEnabled())
2166     return false;
2167 
2168   TII = STM->getInstrInfo();
2169   TRI = &TII->getRegisterInfo();
2170 
2171   MRI = &MF.getRegInfo();
2172   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2173 
2174   LLVM_DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
2175 
2176   bool Modified = false;
2177 
2178   // Contains the list of instructions for which constant offsets are being
2179   // promoted to the IMM. This is tracked for an entire block at time.
2180   SmallPtrSet<MachineInstr *, 4> AnchorList;
2181   MemInfoMap Visited;
2182 
2183   for (MachineBasicBlock &MBB : MF) {
2184     MachineBasicBlock::iterator SectionEnd;
2185     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
2186          I = SectionEnd) {
2187       bool CollectModified;
2188       std::list<std::list<CombineInfo>> MergeableInsts;
2189 
2190       // First pass: Collect list of all instructions we know how to merge in a
2191       // subset of the block.
2192       std::tie(SectionEnd, CollectModified) =
2193           collectMergeableInsts(I, E, Visited, AnchorList, MergeableInsts);
2194 
2195       Modified |= CollectModified;
2196 
2197       do {
2198         OptimizeAgain = false;
2199         Modified |= optimizeBlock(MergeableInsts);
2200       } while (OptimizeAgain);
2201     }
2202 
2203     Visited.clear();
2204     AnchorList.clear();
2205   }
2206 
2207   return Modified;
2208 }
2209