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