1 //===-- SIFormMemoryClauses.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 /// \file
10 /// This pass creates bundles of SMEM and VMEM instructions forming memory
11 /// clauses if XNACK is enabled. Def operands of clauses are marked as early
12 /// clobber to make sure we will not override any source within a clause.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPU.h"
17 #include "GCNRegPressure.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "llvm/InitializePasses.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "si-form-memory-clauses"
24 
25 // Clauses longer then 15 instructions would overflow one of the counters
26 // and stall. They can stall even earlier if there are outstanding counters.
27 static cl::opt<unsigned>
28 MaxClause("amdgpu-max-memory-clause", cl::Hidden, cl::init(15),
29           cl::desc("Maximum length of a memory clause, instructions"));
30 
31 namespace {
32 
33 class SIFormMemoryClauses : public MachineFunctionPass {
34   typedef DenseMap<unsigned, std::pair<unsigned, LaneBitmask>> RegUse;
35 
36 public:
37   static char ID;
38 
39 public:
40   SIFormMemoryClauses() : MachineFunctionPass(ID) {
41     initializeSIFormMemoryClausesPass(*PassRegistry::getPassRegistry());
42   }
43 
44   bool runOnMachineFunction(MachineFunction &MF) override;
45 
46   StringRef getPassName() const override {
47     return "SI Form memory clauses";
48   }
49 
50   void getAnalysisUsage(AnalysisUsage &AU) const override {
51     AU.addRequired<LiveIntervals>();
52     AU.setPreservesAll();
53     MachineFunctionPass::getAnalysisUsage(AU);
54   }
55 
56   MachineFunctionProperties getClearedProperties() const override {
57     return MachineFunctionProperties().set(
58         MachineFunctionProperties::Property::IsSSA);
59   }
60 
61 private:
62   template <typename Callable>
63   void forAllLanes(Register Reg, LaneBitmask LaneMask, Callable Func) const;
64 
65   bool canBundle(const MachineInstr &MI, const RegUse &Defs,
66                  const RegUse &Uses) const;
67   bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT);
68   void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const;
69   bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses,
70                       GCNDownwardRPTracker &RPT);
71 
72   const GCNSubtarget *ST;
73   const SIRegisterInfo *TRI;
74   const MachineRegisterInfo *MRI;
75   SIMachineFunctionInfo *MFI;
76 
77   unsigned LastRecordedOccupancy;
78   unsigned MaxVGPRs;
79   unsigned MaxSGPRs;
80 };
81 
82 } // End anonymous namespace.
83 
84 INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE,
85                       "SI Form memory clauses", false, false)
86 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
87 INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE,
88                     "SI Form memory clauses", false, false)
89 
90 
91 char SIFormMemoryClauses::ID = 0;
92 
93 char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID;
94 
95 FunctionPass *llvm::createSIFormMemoryClausesPass() {
96   return new SIFormMemoryClauses();
97 }
98 
99 static bool isVMEMClauseInst(const MachineInstr &MI) {
100   return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI);
101 }
102 
103 static bool isSMEMClauseInst(const MachineInstr &MI) {
104   return SIInstrInfo::isSMRD(MI);
105 }
106 
107 // There no sense to create store clauses, they do not define anything,
108 // thus there is nothing to set early-clobber.
109 static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) {
110   assert(!MI.isDebugInstr() && "debug instructions should not reach here");
111   if (MI.isBundled())
112     return false;
113   if (!MI.mayLoad() || MI.mayStore())
114     return false;
115   if (AMDGPU::getAtomicNoRetOp(MI.getOpcode()) != -1 ||
116       AMDGPU::getAtomicRetOp(MI.getOpcode()) != -1)
117     return false;
118   if (IsVMEMClause && !isVMEMClauseInst(MI))
119     return false;
120   if (!IsVMEMClause && !isSMEMClauseInst(MI))
121     return false;
122   // If this is a load instruction where the result has been coalesced with an operand, then we cannot clause it.
123   for (const MachineOperand &ResMO : MI.defs()) {
124     Register ResReg = ResMO.getReg();
125     for (const MachineOperand &MO : MI.uses()) {
126       if (!MO.isReg() || MO.isDef())
127         continue;
128       if (MO.getReg() == ResReg)
129         return false;
130     }
131     break; // Only check the first def.
132   }
133   return true;
134 }
135 
136 static unsigned getMopState(const MachineOperand &MO) {
137   unsigned S = 0;
138   if (MO.isImplicit())
139     S |= RegState::Implicit;
140   if (MO.isDead())
141     S |= RegState::Dead;
142   if (MO.isUndef())
143     S |= RegState::Undef;
144   if (MO.isKill())
145     S |= RegState::Kill;
146   if (MO.isEarlyClobber())
147     S |= RegState::EarlyClobber;
148   if (MO.getReg().isPhysical() && MO.isRenamable())
149     S |= RegState::Renamable;
150   return S;
151 }
152 
153 template <typename Callable>
154 void SIFormMemoryClauses::forAllLanes(Register Reg, LaneBitmask LaneMask,
155                                       Callable Func) const {
156   if (LaneMask.all() || Reg.isPhysical() ||
157       LaneMask == MRI->getMaxLaneMaskForVReg(Reg)) {
158     Func(0);
159     return;
160   }
161 
162   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
163   unsigned E = TRI->getNumSubRegIndices();
164   SmallVector<unsigned, AMDGPU::NUM_TARGET_SUBREGS> CoveringSubregs;
165   for (unsigned Idx = 1; Idx < E; ++Idx) {
166     // Is this index even compatible with the given class?
167     if (TRI->getSubClassWithSubReg(RC, Idx) != RC)
168       continue;
169     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
170     // Early exit if we found a perfect match.
171     if (SubRegMask == LaneMask) {
172       Func(Idx);
173       return;
174     }
175 
176     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
177       continue;
178 
179     CoveringSubregs.push_back(Idx);
180   }
181 
182   llvm::sort(CoveringSubregs, [this](unsigned A, unsigned B) {
183     LaneBitmask MaskA = TRI->getSubRegIndexLaneMask(A);
184     LaneBitmask MaskB = TRI->getSubRegIndexLaneMask(B);
185     unsigned NA = MaskA.getNumLanes();
186     unsigned NB = MaskB.getNumLanes();
187     if (NA != NB)
188       return NA > NB;
189     return MaskA.getHighestLane() > MaskB.getHighestLane();
190   });
191 
192   for (unsigned Idx : CoveringSubregs) {
193     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
194     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
195       continue;
196 
197     Func(Idx);
198     LaneMask &= ~SubRegMask;
199     if (LaneMask.none())
200       return;
201   }
202 
203   llvm_unreachable("Failed to find all subregs to cover lane mask");
204 }
205 
206 // Returns false if there is a use of a def already in the map.
207 // In this case we must break the clause.
208 bool SIFormMemoryClauses::canBundle(const MachineInstr &MI, const RegUse &Defs,
209                                     const RegUse &Uses) const {
210   // Check interference with defs.
211   for (const MachineOperand &MO : MI.operands()) {
212     // TODO: Prologue/Epilogue Insertion pass does not process bundled
213     //       instructions.
214     if (MO.isFI())
215       return false;
216 
217     if (!MO.isReg())
218       continue;
219 
220     Register Reg = MO.getReg();
221 
222     // If it is tied we will need to write same register as we read.
223     if (MO.isTied())
224       return false;
225 
226     const RegUse &Map = MO.isDef() ? Uses : Defs;
227     auto Conflict = Map.find(Reg);
228     if (Conflict == Map.end())
229       continue;
230 
231     if (Reg.isPhysical())
232       return false;
233 
234     LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
235     if ((Conflict->second.second & Mask).any())
236       return false;
237   }
238 
239   return true;
240 }
241 
242 // Since all defs in the clause are early clobber we can run out of registers.
243 // Function returns false if pressure would hit the limit if instruction is
244 // bundled into a memory clause.
245 bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI,
246                                         GCNDownwardRPTracker &RPT) {
247   // NB: skip advanceBeforeNext() call. Since all defs will be marked
248   // early-clobber they will all stay alive at least to the end of the
249   // clause. Therefor we should not decrease pressure even if load
250   // pointer becomes dead and could otherwise be reused for destination.
251   RPT.advanceToNext();
252   GCNRegPressure MaxPressure = RPT.moveMaxPressure();
253   unsigned Occupancy = MaxPressure.getOccupancy(*ST);
254 
255   // Don't push over half the register budget. We don't want to introduce
256   // spilling just to form a soft clause.
257   //
258   // FIXME: This pressure check is fundamentally broken. First, this is checking
259   // the global pressure, not the pressure at this specific point in the
260   // program. Second, it's not accounting for the increased liveness of the use
261   // operands due to the early clobber we will introduce. Third, the pressure
262   // tracking does not account for the alignment requirements for SGPRs, or the
263   // fragmentation of registers the allocator will need to satisfy.
264   if (Occupancy >= MFI->getMinAllowedOccupancy() &&
265       MaxPressure.getVGPRNum() <= MaxVGPRs / 2 &&
266       MaxPressure.getSGPRNum() <= MaxSGPRs / 2) {
267     LastRecordedOccupancy = Occupancy;
268     return true;
269   }
270   return false;
271 }
272 
273 // Collect register defs and uses along with their lane masks and states.
274 void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI,
275                                          RegUse &Defs, RegUse &Uses) const {
276   for (const MachineOperand &MO : MI.operands()) {
277     if (!MO.isReg())
278       continue;
279     Register Reg = MO.getReg();
280     if (!Reg)
281       continue;
282 
283     LaneBitmask Mask = Reg.isVirtual()
284                            ? TRI->getSubRegIndexLaneMask(MO.getSubReg())
285                            : LaneBitmask::getAll();
286     RegUse &Map = MO.isDef() ? Defs : Uses;
287 
288     auto Loc = Map.find(Reg);
289     unsigned State = getMopState(MO);
290     if (Loc == Map.end()) {
291       Map[Reg] = std::make_pair(State, Mask);
292     } else {
293       Loc->second.first |= State;
294       Loc->second.second |= Mask;
295     }
296   }
297 }
298 
299 // Check register def/use conflicts, occupancy limits and collect def/use maps.
300 // Return true if instruction can be bundled with previous. It it cannot
301 // def/use maps are not updated.
302 bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI,
303                                          RegUse &Defs, RegUse &Uses,
304                                          GCNDownwardRPTracker &RPT) {
305   if (!canBundle(MI, Defs, Uses))
306     return false;
307 
308   if (!checkPressure(MI, RPT))
309     return false;
310 
311   collectRegUses(MI, Defs, Uses);
312   return true;
313 }
314 
315 bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) {
316   if (skipFunction(MF.getFunction()))
317     return false;
318 
319   ST = &MF.getSubtarget<GCNSubtarget>();
320   if (!ST->isXNACKEnabled())
321     return false;
322 
323   const SIInstrInfo *TII = ST->getInstrInfo();
324   TRI = ST->getRegisterInfo();
325   MRI = &MF.getRegInfo();
326   MFI = MF.getInfo<SIMachineFunctionInfo>();
327   LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
328   SlotIndexes *Ind = LIS->getSlotIndexes();
329   bool Changed = false;
330 
331   MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count();
332   MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count();
333   unsigned FuncMaxClause = AMDGPU::getIntegerAttribute(
334       MF.getFunction(), "amdgpu-max-memory-clause", MaxClause);
335 
336   SmallVector<MachineInstr *> DbgInstrs;
337 
338   for (MachineBasicBlock &MBB : MF) {
339     GCNDownwardRPTracker RPT(*LIS);
340     MachineBasicBlock::instr_iterator Next;
341     for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) {
342       MachineInstr &MI = *I;
343       Next = std::next(I);
344 
345       if (MI.isDebugInstr())
346         continue;
347 
348       bool IsVMEM = isVMEMClauseInst(MI);
349 
350       if (!isValidClauseInst(MI, IsVMEM))
351         continue;
352 
353       if (!RPT.getNext().isValid())
354         RPT.reset(MI);
355       else { // Advance the state to the current MI.
356         RPT.advance(MachineBasicBlock::const_iterator(MI));
357         RPT.advanceBeforeNext();
358       }
359 
360       const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs());
361       RegUse Defs, Uses;
362       if (!processRegUses(MI, Defs, Uses, RPT)) {
363         RPT.reset(MI, &LiveRegsCopy);
364         continue;
365       }
366 
367       unsigned Length = 1;
368       for ( ; Next != E && Length < FuncMaxClause; ++Next) {
369         // Debug instructions should not change the bundling. We need to move
370         // these after the bundle
371         if (Next->isDebugInstr())
372           continue;
373 
374         if (!isValidClauseInst(*Next, IsVMEM))
375           break;
376 
377         // A load from pointer which was loaded inside the same bundle is an
378         // impossible clause because we will need to write and read the same
379         // register inside. In this case processRegUses will return false.
380         if (!processRegUses(*Next, Defs, Uses, RPT))
381           break;
382 
383         ++Length;
384       }
385       if (Length < 2) {
386         RPT.reset(MI, &LiveRegsCopy);
387         continue;
388       }
389 
390       Changed = true;
391       MFI->limitOccupancy(LastRecordedOccupancy);
392 
393       auto B = BuildMI(MBB, I, DebugLoc(), TII->get(TargetOpcode::BUNDLE));
394       Ind->insertMachineInstrInMaps(*B);
395 
396       // Restore the state after processing the bundle.
397       RPT.reset(*B, &LiveRegsCopy);
398       DbgInstrs.clear();
399 
400       auto BundleNext = I;
401       for (auto BI = I; BI != Next; BI = BundleNext) {
402         BundleNext = std::next(BI);
403 
404         if (BI->isDebugValue()) {
405           DbgInstrs.push_back(BI->removeFromParent());
406           continue;
407         }
408 
409         BI->bundleWithPred();
410         Ind->removeSingleMachineInstrFromMaps(*BI);
411 
412         for (MachineOperand &MO : BI->defs())
413           if (MO.readsReg())
414             MO.setIsInternalRead(true);
415       }
416 
417       // Replace any debug instructions after the new bundle.
418       for (MachineInstr *DbgInst : DbgInstrs)
419         MBB.insert(Next, DbgInst);
420 
421       for (auto &&R : Defs) {
422         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
423           unsigned S = R.second.first | RegState::EarlyClobber;
424           if (!SubReg)
425             S &= ~(RegState::Undef | RegState::Dead);
426           B.addDef(R.first, S, SubReg);
427         });
428       }
429 
430       for (auto &&R : Uses) {
431         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
432           B.addUse(R.first, R.second.first & ~RegState::Kill, SubReg);
433         });
434       }
435 
436       for (auto &&R : Defs) {
437         Register Reg = R.first;
438         Uses.erase(Reg);
439         if (Reg.isPhysical())
440           continue;
441         LIS->removeInterval(Reg);
442         LIS->createAndComputeVirtRegInterval(Reg);
443       }
444 
445       for (auto &&R : Uses) {
446         Register Reg = R.first;
447         if (Reg.isPhysical())
448           continue;
449         LIS->removeInterval(Reg);
450         LIS->createAndComputeVirtRegInterval(Reg);
451       }
452     }
453   }
454 
455   return Changed;
456 }
457