1 //==- SIMachineFunctionInfo.h - SIMachineFunctionInfo interface --*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
14 #define LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
15 
16 #include "AMDGPUArgumentUsageInfo.h"
17 #include "AMDGPUMachineFunction.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "SIInstrInfo.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/CodeGen/MIRYamlMapping.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 namespace llvm {
27 
28 class MachineFrameInfo;
29 class MachineFunction;
30 class SIMachineFunctionInfo;
31 class SIRegisterInfo;
32 class TargetRegisterClass;
33 
34 class AMDGPUPseudoSourceValue : public PseudoSourceValue {
35 public:
36   enum AMDGPUPSVKind : unsigned {
37     PSVBuffer = PseudoSourceValue::TargetCustom,
38     PSVImage,
39     GWSResource
40   };
41 
42 protected:
43   AMDGPUPseudoSourceValue(unsigned Kind, const AMDGPUTargetMachine &TM)
44       : PseudoSourceValue(Kind, TM) {}
45 
46 public:
47   bool isConstant(const MachineFrameInfo *) const override {
48     // This should probably be true for most images, but we will start by being
49     // conservative.
50     return false;
51   }
52 
53   bool isAliased(const MachineFrameInfo *) const override {
54     return true;
55   }
56 
57   bool mayAlias(const MachineFrameInfo *) const override {
58     return true;
59   }
60 };
61 
62 class AMDGPUBufferPseudoSourceValue final : public AMDGPUPseudoSourceValue {
63 public:
64   explicit AMDGPUBufferPseudoSourceValue(const AMDGPUTargetMachine &TM)
65       : AMDGPUPseudoSourceValue(PSVBuffer, TM) {}
66 
67   static bool classof(const PseudoSourceValue *V) {
68     return V->kind() == PSVBuffer;
69   }
70 
71   void printCustom(raw_ostream &OS) const override { OS << "BufferResource"; }
72 };
73 
74 class AMDGPUImagePseudoSourceValue final : public AMDGPUPseudoSourceValue {
75 public:
76   // TODO: Is the img rsrc useful?
77   explicit AMDGPUImagePseudoSourceValue(const AMDGPUTargetMachine &TM)
78       : AMDGPUPseudoSourceValue(PSVImage, TM) {}
79 
80   static bool classof(const PseudoSourceValue *V) {
81     return V->kind() == PSVImage;
82   }
83 
84   void printCustom(raw_ostream &OS) const override { OS << "ImageResource"; }
85 };
86 
87 class AMDGPUGWSResourcePseudoSourceValue final : public AMDGPUPseudoSourceValue {
88 public:
89   explicit AMDGPUGWSResourcePseudoSourceValue(const AMDGPUTargetMachine &TM)
90       : AMDGPUPseudoSourceValue(GWSResource, TM) {}
91 
92   static bool classof(const PseudoSourceValue *V) {
93     return V->kind() == GWSResource;
94   }
95 
96   // These are inaccessible memory from IR.
97   bool isAliased(const MachineFrameInfo *) const override {
98     return false;
99   }
100 
101   // These are inaccessible memory from IR.
102   bool mayAlias(const MachineFrameInfo *) const override {
103     return false;
104   }
105 
106   void printCustom(raw_ostream &OS) const override {
107     OS << "GWSResource";
108   }
109 };
110 
111 namespace yaml {
112 
113 struct SIArgument {
114   bool IsRegister;
115   union {
116     StringValue RegisterName;
117     unsigned StackOffset;
118   };
119   Optional<unsigned> Mask;
120 
121   // Default constructor, which creates a stack argument.
122   SIArgument() : IsRegister(false), StackOffset(0) {}
123   SIArgument(const SIArgument &Other) {
124     IsRegister = Other.IsRegister;
125     if (IsRegister) {
126       ::new ((void *)std::addressof(RegisterName))
127           StringValue(Other.RegisterName);
128     } else
129       StackOffset = Other.StackOffset;
130     Mask = Other.Mask;
131   }
132   SIArgument &operator=(const SIArgument &Other) {
133     IsRegister = Other.IsRegister;
134     if (IsRegister) {
135       ::new ((void *)std::addressof(RegisterName))
136           StringValue(Other.RegisterName);
137     } else
138       StackOffset = Other.StackOffset;
139     Mask = Other.Mask;
140     return *this;
141   }
142   ~SIArgument() {
143     if (IsRegister)
144       RegisterName.~StringValue();
145   }
146 
147   // Helper to create a register or stack argument.
148   static inline SIArgument createArgument(bool IsReg) {
149     if (IsReg)
150       return SIArgument(IsReg);
151     return SIArgument();
152   }
153 
154 private:
155   // Construct a register argument.
156   SIArgument(bool) : IsRegister(true), RegisterName() {}
157 };
158 
159 template <> struct MappingTraits<SIArgument> {
160   static void mapping(IO &YamlIO, SIArgument &A) {
161     if (YamlIO.outputting()) {
162       if (A.IsRegister)
163         YamlIO.mapRequired("reg", A.RegisterName);
164       else
165         YamlIO.mapRequired("offset", A.StackOffset);
166     } else {
167       auto Keys = YamlIO.keys();
168       if (is_contained(Keys, "reg")) {
169         A = SIArgument::createArgument(true);
170         YamlIO.mapRequired("reg", A.RegisterName);
171       } else if (is_contained(Keys, "offset"))
172         YamlIO.mapRequired("offset", A.StackOffset);
173       else
174         YamlIO.setError("missing required key 'reg' or 'offset'");
175     }
176     YamlIO.mapOptional("mask", A.Mask);
177   }
178   static const bool flow = true;
179 };
180 
181 struct SIArgumentInfo {
182   Optional<SIArgument> PrivateSegmentBuffer;
183   Optional<SIArgument> DispatchPtr;
184   Optional<SIArgument> QueuePtr;
185   Optional<SIArgument> KernargSegmentPtr;
186   Optional<SIArgument> DispatchID;
187   Optional<SIArgument> FlatScratchInit;
188   Optional<SIArgument> PrivateSegmentSize;
189 
190   Optional<SIArgument> WorkGroupIDX;
191   Optional<SIArgument> WorkGroupIDY;
192   Optional<SIArgument> WorkGroupIDZ;
193   Optional<SIArgument> WorkGroupInfo;
194   Optional<SIArgument> PrivateSegmentWaveByteOffset;
195 
196   Optional<SIArgument> ImplicitArgPtr;
197   Optional<SIArgument> ImplicitBufferPtr;
198 
199   Optional<SIArgument> WorkItemIDX;
200   Optional<SIArgument> WorkItemIDY;
201   Optional<SIArgument> WorkItemIDZ;
202 };
203 
204 template <> struct MappingTraits<SIArgumentInfo> {
205   static void mapping(IO &YamlIO, SIArgumentInfo &AI) {
206     YamlIO.mapOptional("privateSegmentBuffer", AI.PrivateSegmentBuffer);
207     YamlIO.mapOptional("dispatchPtr", AI.DispatchPtr);
208     YamlIO.mapOptional("queuePtr", AI.QueuePtr);
209     YamlIO.mapOptional("kernargSegmentPtr", AI.KernargSegmentPtr);
210     YamlIO.mapOptional("dispatchID", AI.DispatchID);
211     YamlIO.mapOptional("flatScratchInit", AI.FlatScratchInit);
212     YamlIO.mapOptional("privateSegmentSize", AI.PrivateSegmentSize);
213 
214     YamlIO.mapOptional("workGroupIDX", AI.WorkGroupIDX);
215     YamlIO.mapOptional("workGroupIDY", AI.WorkGroupIDY);
216     YamlIO.mapOptional("workGroupIDZ", AI.WorkGroupIDZ);
217     YamlIO.mapOptional("workGroupInfo", AI.WorkGroupInfo);
218     YamlIO.mapOptional("privateSegmentWaveByteOffset",
219                        AI.PrivateSegmentWaveByteOffset);
220 
221     YamlIO.mapOptional("implicitArgPtr", AI.ImplicitArgPtr);
222     YamlIO.mapOptional("implicitBufferPtr", AI.ImplicitBufferPtr);
223 
224     YamlIO.mapOptional("workItemIDX", AI.WorkItemIDX);
225     YamlIO.mapOptional("workItemIDY", AI.WorkItemIDY);
226     YamlIO.mapOptional("workItemIDZ", AI.WorkItemIDZ);
227   }
228 };
229 
230 // Default to default mode for default calling convention.
231 struct SIMode {
232   bool IEEE = true;
233   bool DX10Clamp = true;
234   bool FP32InputDenormals = true;
235   bool FP32OutputDenormals = true;
236   bool FP64FP16InputDenormals = true;
237   bool FP64FP16OutputDenormals = true;
238 
239   SIMode() = default;
240 
241   SIMode(const AMDGPU::SIModeRegisterDefaults &Mode) {
242     IEEE = Mode.IEEE;
243     DX10Clamp = Mode.DX10Clamp;
244     FP32InputDenormals = Mode.FP32InputDenormals;
245     FP32OutputDenormals = Mode.FP32OutputDenormals;
246     FP64FP16InputDenormals = Mode.FP64FP16InputDenormals;
247     FP64FP16OutputDenormals = Mode.FP64FP16OutputDenormals;
248   }
249 
250   bool operator ==(const SIMode Other) const {
251     return IEEE == Other.IEEE &&
252            DX10Clamp == Other.DX10Clamp &&
253            FP32InputDenormals == Other.FP32InputDenormals &&
254            FP32OutputDenormals == Other.FP32OutputDenormals &&
255            FP64FP16InputDenormals == Other.FP64FP16InputDenormals &&
256            FP64FP16OutputDenormals == Other.FP64FP16OutputDenormals;
257   }
258 };
259 
260 template <> struct MappingTraits<SIMode> {
261   static void mapping(IO &YamlIO, SIMode &Mode) {
262     YamlIO.mapOptional("ieee", Mode.IEEE, true);
263     YamlIO.mapOptional("dx10-clamp", Mode.DX10Clamp, true);
264     YamlIO.mapOptional("fp32-input-denormals", Mode.FP32InputDenormals, true);
265     YamlIO.mapOptional("fp32-output-denormals", Mode.FP32OutputDenormals, true);
266     YamlIO.mapOptional("fp64-fp16-input-denormals", Mode.FP64FP16InputDenormals, true);
267     YamlIO.mapOptional("fp64-fp16-output-denormals", Mode.FP64FP16OutputDenormals, true);
268   }
269 };
270 
271 struct SIMachineFunctionInfo final : public yaml::MachineFunctionInfo {
272   uint64_t ExplicitKernArgSize = 0;
273   unsigned MaxKernArgAlign = 0;
274   uint32_t LDSSize = 0;
275   uint32_t GDSSize = 0;
276   Align DynLDSAlign;
277   bool IsEntryFunction = false;
278   bool NoSignedZerosFPMath = false;
279   bool MemoryBound = false;
280   bool WaveLimiter = false;
281   bool HasSpilledSGPRs = false;
282   bool HasSpilledVGPRs = false;
283   uint32_t HighBitsOf32BitAddress = 0;
284 
285   // TODO: 10 may be a better default since it's the maximum.
286   unsigned Occupancy = 0;
287 
288   SmallVector<StringValue> WWMReservedRegs;
289 
290   StringValue ScratchRSrcReg = "$private_rsrc_reg";
291   StringValue FrameOffsetReg = "$fp_reg";
292   StringValue StackPtrOffsetReg = "$sp_reg";
293 
294   unsigned BytesInStackArgArea = 0;
295   bool ReturnsVoid = true;
296 
297   Optional<SIArgumentInfo> ArgInfo;
298   SIMode Mode;
299   Optional<FrameIndex> ScavengeFI;
300   StringValue VGPRForAGPRCopy;
301 
302   SIMachineFunctionInfo() = default;
303   SIMachineFunctionInfo(const llvm::SIMachineFunctionInfo &,
304                         const TargetRegisterInfo &TRI,
305                         const llvm::MachineFunction &MF);
306 
307   void mappingImpl(yaml::IO &YamlIO) override;
308   ~SIMachineFunctionInfo() = default;
309 };
310 
311 template <> struct MappingTraits<SIMachineFunctionInfo> {
312   static void mapping(IO &YamlIO, SIMachineFunctionInfo &MFI) {
313     YamlIO.mapOptional("explicitKernArgSize", MFI.ExplicitKernArgSize,
314                        UINT64_C(0));
315     YamlIO.mapOptional("maxKernArgAlign", MFI.MaxKernArgAlign, 0u);
316     YamlIO.mapOptional("ldsSize", MFI.LDSSize, 0u);
317     YamlIO.mapOptional("gdsSize", MFI.GDSSize, 0u);
318     YamlIO.mapOptional("dynLDSAlign", MFI.DynLDSAlign, Align());
319     YamlIO.mapOptional("isEntryFunction", MFI.IsEntryFunction, false);
320     YamlIO.mapOptional("noSignedZerosFPMath", MFI.NoSignedZerosFPMath, false);
321     YamlIO.mapOptional("memoryBound", MFI.MemoryBound, false);
322     YamlIO.mapOptional("waveLimiter", MFI.WaveLimiter, false);
323     YamlIO.mapOptional("hasSpilledSGPRs", MFI.HasSpilledSGPRs, false);
324     YamlIO.mapOptional("hasSpilledVGPRs", MFI.HasSpilledVGPRs, false);
325     YamlIO.mapOptional("scratchRSrcReg", MFI.ScratchRSrcReg,
326                        StringValue("$private_rsrc_reg"));
327     YamlIO.mapOptional("frameOffsetReg", MFI.FrameOffsetReg,
328                        StringValue("$fp_reg"));
329     YamlIO.mapOptional("stackPtrOffsetReg", MFI.StackPtrOffsetReg,
330                        StringValue("$sp_reg"));
331     YamlIO.mapOptional("bytesInStackArgArea", MFI.BytesInStackArgArea, 0u);
332     YamlIO.mapOptional("returnsVoid", MFI.ReturnsVoid, true);
333     YamlIO.mapOptional("argumentInfo", MFI.ArgInfo);
334     YamlIO.mapOptional("mode", MFI.Mode, SIMode());
335     YamlIO.mapOptional("highBitsOf32BitAddress",
336                        MFI.HighBitsOf32BitAddress, 0u);
337     YamlIO.mapOptional("occupancy", MFI.Occupancy, 0);
338     YamlIO.mapOptional("wwmReservedRegs", MFI.WWMReservedRegs);
339     YamlIO.mapOptional("scavengeFI", MFI.ScavengeFI);
340     YamlIO.mapOptional("vgprForAGPRCopy", MFI.VGPRForAGPRCopy,
341                        StringValue()); // Don't print out when it's empty.
342   }
343 };
344 
345 } // end namespace yaml
346 
347 /// This class keeps track of the SPI_SP_INPUT_ADDR config register, which
348 /// tells the hardware which interpolation parameters to load.
349 class SIMachineFunctionInfo final : public AMDGPUMachineFunction {
350   friend class GCNTargetMachine;
351 
352   // Registers that may be reserved for spilling purposes. These may be the same
353   // as the input registers.
354   Register ScratchRSrcReg = AMDGPU::PRIVATE_RSRC_REG;
355 
356   // This is the the unswizzled offset from the current dispatch's scratch wave
357   // base to the beginning of the current function's frame.
358   Register FrameOffsetReg = AMDGPU::FP_REG;
359 
360   // This is an ABI register used in the non-entry calling convention to
361   // communicate the unswizzled offset from the current dispatch's scratch wave
362   // base to the beginning of the new function's frame.
363   Register StackPtrOffsetReg = AMDGPU::SP_REG;
364 
365   AMDGPUFunctionArgInfo ArgInfo;
366 
367   // Graphics info.
368   unsigned PSInputAddr = 0;
369   unsigned PSInputEnable = 0;
370 
371   /// Number of bytes of arguments this function has on the stack. If the callee
372   /// is expected to restore the argument stack this should be a multiple of 16,
373   /// all usable during a tail call.
374   ///
375   /// The alternative would forbid tail call optimisation in some cases: if we
376   /// want to transfer control from a function with 8-bytes of stack-argument
377   /// space to a function with 16-bytes then misalignment of this value would
378   /// make a stack adjustment necessary, which could not be undone by the
379   /// callee.
380   unsigned BytesInStackArgArea = 0;
381 
382   bool ReturnsVoid = true;
383 
384   // A pair of default/requested minimum/maximum flat work group sizes.
385   // Minimum - first, maximum - second.
386   std::pair<unsigned, unsigned> FlatWorkGroupSizes = {0, 0};
387 
388   // A pair of default/requested minimum/maximum number of waves per execution
389   // unit. Minimum - first, maximum - second.
390   std::pair<unsigned, unsigned> WavesPerEU = {0, 0};
391 
392   std::unique_ptr<const AMDGPUBufferPseudoSourceValue> BufferPSV;
393   std::unique_ptr<const AMDGPUImagePseudoSourceValue> ImagePSV;
394   std::unique_ptr<const AMDGPUGWSResourcePseudoSourceValue> GWSResourcePSV;
395 
396 private:
397   unsigned NumUserSGPRs = 0;
398   unsigned NumSystemSGPRs = 0;
399 
400   bool HasSpilledSGPRs = false;
401   bool HasSpilledVGPRs = false;
402   bool HasNonSpillStackObjects = false;
403   bool IsStackRealigned = false;
404 
405   unsigned NumSpilledSGPRs = 0;
406   unsigned NumSpilledVGPRs = 0;
407 
408   // Feature bits required for inputs passed in user SGPRs.
409   bool PrivateSegmentBuffer : 1;
410   bool DispatchPtr : 1;
411   bool QueuePtr : 1;
412   bool KernargSegmentPtr : 1;
413   bool DispatchID : 1;
414   bool FlatScratchInit : 1;
415 
416   // Feature bits required for inputs passed in system SGPRs.
417   bool WorkGroupIDX : 1; // Always initialized.
418   bool WorkGroupIDY : 1;
419   bool WorkGroupIDZ : 1;
420   bool WorkGroupInfo : 1;
421   bool PrivateSegmentWaveByteOffset : 1;
422 
423   bool WorkItemIDX : 1; // Always initialized.
424   bool WorkItemIDY : 1;
425   bool WorkItemIDZ : 1;
426 
427   // Private memory buffer
428   // Compute directly in sgpr[0:1]
429   // Other shaders indirect 64-bits at sgpr[0:1]
430   bool ImplicitBufferPtr : 1;
431 
432   // Pointer to where the ABI inserts special kernel arguments separate from the
433   // user arguments. This is an offset from the KernargSegmentPtr.
434   bool ImplicitArgPtr : 1;
435 
436   bool MayNeedAGPRs : 1;
437 
438   // The hard-wired high half of the address of the global information table
439   // for AMDPAL OS type. 0xffffffff represents no hard-wired high half, since
440   // current hardware only allows a 16 bit value.
441   unsigned GITPtrHigh;
442 
443   unsigned HighBitsOf32BitAddress;
444 
445   // Current recorded maximum possible occupancy.
446   unsigned Occupancy;
447 
448   mutable Optional<bool> UsesAGPRs;
449 
450   MCPhysReg getNextUserSGPR() const;
451 
452   MCPhysReg getNextSystemSGPR() const;
453 
454 public:
455   struct SpilledReg {
456     Register VGPR;
457     int Lane = -1;
458 
459     SpilledReg() = default;
460     SpilledReg(Register R, int L) : VGPR (R), Lane (L) {}
461 
462     bool hasLane() { return Lane != -1;}
463     bool hasReg() { return VGPR != 0;}
464   };
465 
466   struct SGPRSpillVGPR {
467     // VGPR used for SGPR spills
468     Register VGPR;
469 
470     // If the VGPR is is used for SGPR spills in a non-entrypoint function, the
471     // stack slot used to save/restore it in the prolog/epilog.
472     Optional<int> FI;
473 
474     SGPRSpillVGPR(Register V, Optional<int> F) : VGPR(V), FI(F) {}
475   };
476 
477   struct VGPRSpillToAGPR {
478     SmallVector<MCPhysReg, 32> Lanes;
479     bool FullyAllocated = false;
480     bool IsDead = false;
481   };
482 
483   // Track VGPRs reserved for WWM.
484   SmallSetVector<Register, 8> WWMReservedRegs;
485 
486   /// Track stack slots used for save/restore of reserved WWM VGPRs in the
487   /// prolog/epilog.
488 
489   /// FIXME: This is temporary state only needed in PrologEpilogInserter, and
490   /// doesn't really belong here. It does not require serialization
491   SmallVector<int, 8> WWMReservedFrameIndexes;
492 
493   void allocateWWMReservedSpillSlots(MachineFrameInfo &MFI,
494                                      const SIRegisterInfo &TRI);
495 
496   auto wwmAllocation() const {
497     assert(WWMReservedRegs.size() == WWMReservedFrameIndexes.size());
498     return zip(WWMReservedRegs, WWMReservedFrameIndexes);
499   }
500 
501 private:
502   // Track VGPR + wave index for each subregister of the SGPR spilled to
503   // frameindex key.
504   DenseMap<int, std::vector<SpilledReg>> SGPRToVGPRSpills;
505   unsigned NumVGPRSpillLanes = 0;
506   SmallVector<SGPRSpillVGPR, 2> SpillVGPRs;
507 
508   DenseMap<int, VGPRSpillToAGPR> VGPRToAGPRSpills;
509 
510   // AGPRs used for VGPR spills.
511   SmallVector<MCPhysReg, 32> SpillAGPR;
512 
513   // VGPRs used for AGPR spills.
514   SmallVector<MCPhysReg, 32> SpillVGPR;
515 
516   // Emergency stack slot. Sometimes, we create this before finalizing the stack
517   // frame, so save it here and add it to the RegScavenger later.
518   Optional<int> ScavengeFI;
519 
520 private:
521   Register VGPRForAGPRCopy;
522 
523 public:
524   Register getVGPRForAGPRCopy() const {
525     return VGPRForAGPRCopy;
526   }
527 
528   void setVGPRForAGPRCopy(Register NewVGPRForAGPRCopy) {
529     VGPRForAGPRCopy = NewVGPRForAGPRCopy;
530   }
531 
532 public: // FIXME
533   /// If this is set, an SGPR used for save/restore of the register used for the
534   /// frame pointer.
535   Register SGPRForFPSaveRestoreCopy;
536   Optional<int> FramePointerSaveIndex;
537 
538   /// If this is set, an SGPR used for save/restore of the register used for the
539   /// base pointer.
540   Register SGPRForBPSaveRestoreCopy;
541   Optional<int> BasePointerSaveIndex;
542 
543   bool isCalleeSavedReg(const MCPhysReg *CSRegs, MCPhysReg Reg);
544 
545 public:
546   SIMachineFunctionInfo(const MachineFunction &MF);
547 
548   bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI,
549                                 const MachineFunction &MF,
550                                 PerFunctionMIParsingState &PFS,
551                                 SMDiagnostic &Error, SMRange &SourceRange);
552 
553   void reserveWWMRegister(Register Reg) {
554     WWMReservedRegs.insert(Reg);
555   }
556 
557   ArrayRef<SpilledReg> getSGPRToVGPRSpills(int FrameIndex) const {
558     auto I = SGPRToVGPRSpills.find(FrameIndex);
559     return (I == SGPRToVGPRSpills.end()) ?
560       ArrayRef<SpilledReg>() : makeArrayRef(I->second);
561   }
562 
563   ArrayRef<SGPRSpillVGPR> getSGPRSpillVGPRs() const { return SpillVGPRs; }
564 
565   ArrayRef<MCPhysReg> getAGPRSpillVGPRs() const {
566     return SpillAGPR;
567   }
568 
569   ArrayRef<MCPhysReg> getVGPRSpillAGPRs() const {
570     return SpillVGPR;
571   }
572 
573   MCPhysReg getVGPRToAGPRSpill(int FrameIndex, unsigned Lane) const {
574     auto I = VGPRToAGPRSpills.find(FrameIndex);
575     return (I == VGPRToAGPRSpills.end()) ? (MCPhysReg)AMDGPU::NoRegister
576                                          : I->second.Lanes[Lane];
577   }
578 
579   void setVGPRToAGPRSpillDead(int FrameIndex) {
580     auto I = VGPRToAGPRSpills.find(FrameIndex);
581     if (I != VGPRToAGPRSpills.end())
582       I->second.IsDead = true;
583   }
584 
585   bool haveFreeLanesForSGPRSpill(const MachineFunction &MF,
586                                  unsigned NumLane) const;
587   bool allocateSGPRSpillToVGPR(MachineFunction &MF, int FI);
588   bool allocateVGPRSpillToAGPR(MachineFunction &MF, int FI, bool isAGPRtoVGPR);
589 
590   /// If \p ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill
591   /// to the default stack.
592   bool removeDeadFrameIndices(MachineFrameInfo &MFI,
593                               bool ResetSGPRSpillStackIDs);
594 
595   int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI);
596   Optional<int> getOptionalScavengeFI() const { return ScavengeFI; }
597 
598   unsigned getBytesInStackArgArea() const {
599     return BytesInStackArgArea;
600   }
601 
602   void setBytesInStackArgArea(unsigned Bytes) {
603     BytesInStackArgArea = Bytes;
604   }
605 
606   // Add user SGPRs.
607   Register addPrivateSegmentBuffer(const SIRegisterInfo &TRI);
608   Register addDispatchPtr(const SIRegisterInfo &TRI);
609   Register addQueuePtr(const SIRegisterInfo &TRI);
610   Register addKernargSegmentPtr(const SIRegisterInfo &TRI);
611   Register addDispatchID(const SIRegisterInfo &TRI);
612   Register addFlatScratchInit(const SIRegisterInfo &TRI);
613   Register addImplicitBufferPtr(const SIRegisterInfo &TRI);
614 
615   // Add system SGPRs.
616   Register addWorkGroupIDX() {
617     ArgInfo.WorkGroupIDX = ArgDescriptor::createRegister(getNextSystemSGPR());
618     NumSystemSGPRs += 1;
619     return ArgInfo.WorkGroupIDX.getRegister();
620   }
621 
622   Register addWorkGroupIDY() {
623     ArgInfo.WorkGroupIDY = ArgDescriptor::createRegister(getNextSystemSGPR());
624     NumSystemSGPRs += 1;
625     return ArgInfo.WorkGroupIDY.getRegister();
626   }
627 
628   Register addWorkGroupIDZ() {
629     ArgInfo.WorkGroupIDZ = ArgDescriptor::createRegister(getNextSystemSGPR());
630     NumSystemSGPRs += 1;
631     return ArgInfo.WorkGroupIDZ.getRegister();
632   }
633 
634   Register addWorkGroupInfo() {
635     ArgInfo.WorkGroupInfo = ArgDescriptor::createRegister(getNextSystemSGPR());
636     NumSystemSGPRs += 1;
637     return ArgInfo.WorkGroupInfo.getRegister();
638   }
639 
640   // Add special VGPR inputs
641   void setWorkItemIDX(ArgDescriptor Arg) {
642     ArgInfo.WorkItemIDX = Arg;
643   }
644 
645   void setWorkItemIDY(ArgDescriptor Arg) {
646     ArgInfo.WorkItemIDY = Arg;
647   }
648 
649   void setWorkItemIDZ(ArgDescriptor Arg) {
650     ArgInfo.WorkItemIDZ = Arg;
651   }
652 
653   Register addPrivateSegmentWaveByteOffset() {
654     ArgInfo.PrivateSegmentWaveByteOffset
655       = ArgDescriptor::createRegister(getNextSystemSGPR());
656     NumSystemSGPRs += 1;
657     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
658   }
659 
660   void setPrivateSegmentWaveByteOffset(Register Reg) {
661     ArgInfo.PrivateSegmentWaveByteOffset = ArgDescriptor::createRegister(Reg);
662   }
663 
664   bool hasPrivateSegmentBuffer() const {
665     return PrivateSegmentBuffer;
666   }
667 
668   bool hasDispatchPtr() const {
669     return DispatchPtr;
670   }
671 
672   bool hasQueuePtr() const {
673     return QueuePtr;
674   }
675 
676   bool hasKernargSegmentPtr() const {
677     return KernargSegmentPtr;
678   }
679 
680   bool hasDispatchID() const {
681     return DispatchID;
682   }
683 
684   bool hasFlatScratchInit() const {
685     return FlatScratchInit;
686   }
687 
688   bool hasWorkGroupIDX() const {
689     return WorkGroupIDX;
690   }
691 
692   bool hasWorkGroupIDY() const {
693     return WorkGroupIDY;
694   }
695 
696   bool hasWorkGroupIDZ() const {
697     return WorkGroupIDZ;
698   }
699 
700   bool hasWorkGroupInfo() const {
701     return WorkGroupInfo;
702   }
703 
704   bool hasPrivateSegmentWaveByteOffset() const {
705     return PrivateSegmentWaveByteOffset;
706   }
707 
708   bool hasWorkItemIDX() const {
709     return WorkItemIDX;
710   }
711 
712   bool hasWorkItemIDY() const {
713     return WorkItemIDY;
714   }
715 
716   bool hasWorkItemIDZ() const {
717     return WorkItemIDZ;
718   }
719 
720   bool hasImplicitArgPtr() const {
721     return ImplicitArgPtr;
722   }
723 
724   bool hasImplicitBufferPtr() const {
725     return ImplicitBufferPtr;
726   }
727 
728   AMDGPUFunctionArgInfo &getArgInfo() {
729     return ArgInfo;
730   }
731 
732   const AMDGPUFunctionArgInfo &getArgInfo() const {
733     return ArgInfo;
734   }
735 
736   std::tuple<const ArgDescriptor *, const TargetRegisterClass *, LLT>
737   getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
738     return ArgInfo.getPreloadedValue(Value);
739   }
740 
741   MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
742     auto Arg = std::get<0>(ArgInfo.getPreloadedValue(Value));
743     return Arg ? Arg->getRegister() : MCRegister();
744   }
745 
746   unsigned getGITPtrHigh() const {
747     return GITPtrHigh;
748   }
749 
750   Register getGITPtrLoReg(const MachineFunction &MF) const;
751 
752   uint32_t get32BitAddressHighBits() const {
753     return HighBitsOf32BitAddress;
754   }
755 
756   unsigned getNumUserSGPRs() const {
757     return NumUserSGPRs;
758   }
759 
760   unsigned getNumPreloadedSGPRs() const {
761     return NumUserSGPRs + NumSystemSGPRs;
762   }
763 
764   Register getPrivateSegmentWaveByteOffsetSystemSGPR() const {
765     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
766   }
767 
768   /// Returns the physical register reserved for use as the resource
769   /// descriptor for scratch accesses.
770   Register getScratchRSrcReg() const {
771     return ScratchRSrcReg;
772   }
773 
774   void setScratchRSrcReg(Register Reg) {
775     assert(Reg != 0 && "Should never be unset");
776     ScratchRSrcReg = Reg;
777   }
778 
779   Register getFrameOffsetReg() const {
780     return FrameOffsetReg;
781   }
782 
783   void setFrameOffsetReg(Register Reg) {
784     assert(Reg != 0 && "Should never be unset");
785     FrameOffsetReg = Reg;
786   }
787 
788   void setStackPtrOffsetReg(Register Reg) {
789     assert(Reg != 0 && "Should never be unset");
790     StackPtrOffsetReg = Reg;
791   }
792 
793   // Note the unset value for this is AMDGPU::SP_REG rather than
794   // NoRegister. This is mostly a workaround for MIR tests where state that
795   // can't be directly computed from the function is not preserved in serialized
796   // MIR.
797   Register getStackPtrOffsetReg() const {
798     return StackPtrOffsetReg;
799   }
800 
801   Register getQueuePtrUserSGPR() const {
802     return ArgInfo.QueuePtr.getRegister();
803   }
804 
805   Register getImplicitBufferPtrUserSGPR() const {
806     return ArgInfo.ImplicitBufferPtr.getRegister();
807   }
808 
809   bool hasSpilledSGPRs() const {
810     return HasSpilledSGPRs;
811   }
812 
813   void setHasSpilledSGPRs(bool Spill = true) {
814     HasSpilledSGPRs = Spill;
815   }
816 
817   bool hasSpilledVGPRs() const {
818     return HasSpilledVGPRs;
819   }
820 
821   void setHasSpilledVGPRs(bool Spill = true) {
822     HasSpilledVGPRs = Spill;
823   }
824 
825   bool hasNonSpillStackObjects() const {
826     return HasNonSpillStackObjects;
827   }
828 
829   void setHasNonSpillStackObjects(bool StackObject = true) {
830     HasNonSpillStackObjects = StackObject;
831   }
832 
833   bool isStackRealigned() const {
834     return IsStackRealigned;
835   }
836 
837   void setIsStackRealigned(bool Realigned = true) {
838     IsStackRealigned = Realigned;
839   }
840 
841   unsigned getNumSpilledSGPRs() const {
842     return NumSpilledSGPRs;
843   }
844 
845   unsigned getNumSpilledVGPRs() const {
846     return NumSpilledVGPRs;
847   }
848 
849   void addToSpilledSGPRs(unsigned num) {
850     NumSpilledSGPRs += num;
851   }
852 
853   void addToSpilledVGPRs(unsigned num) {
854     NumSpilledVGPRs += num;
855   }
856 
857   unsigned getPSInputAddr() const {
858     return PSInputAddr;
859   }
860 
861   unsigned getPSInputEnable() const {
862     return PSInputEnable;
863   }
864 
865   bool isPSInputAllocated(unsigned Index) const {
866     return PSInputAddr & (1 << Index);
867   }
868 
869   void markPSInputAllocated(unsigned Index) {
870     PSInputAddr |= 1 << Index;
871   }
872 
873   void markPSInputEnabled(unsigned Index) {
874     PSInputEnable |= 1 << Index;
875   }
876 
877   bool returnsVoid() const {
878     return ReturnsVoid;
879   }
880 
881   void setIfReturnsVoid(bool Value) {
882     ReturnsVoid = Value;
883   }
884 
885   /// \returns A pair of default/requested minimum/maximum flat work group sizes
886   /// for this function.
887   std::pair<unsigned, unsigned> getFlatWorkGroupSizes() const {
888     return FlatWorkGroupSizes;
889   }
890 
891   /// \returns Default/requested minimum flat work group size for this function.
892   unsigned getMinFlatWorkGroupSize() const {
893     return FlatWorkGroupSizes.first;
894   }
895 
896   /// \returns Default/requested maximum flat work group size for this function.
897   unsigned getMaxFlatWorkGroupSize() const {
898     return FlatWorkGroupSizes.second;
899   }
900 
901   /// \returns A pair of default/requested minimum/maximum number of waves per
902   /// execution unit.
903   std::pair<unsigned, unsigned> getWavesPerEU() const {
904     return WavesPerEU;
905   }
906 
907   /// \returns Default/requested minimum number of waves per execution unit.
908   unsigned getMinWavesPerEU() const {
909     return WavesPerEU.first;
910   }
911 
912   /// \returns Default/requested maximum number of waves per execution unit.
913   unsigned getMaxWavesPerEU() const {
914     return WavesPerEU.second;
915   }
916 
917   /// \returns SGPR used for \p Dim's work group ID.
918   Register getWorkGroupIDSGPR(unsigned Dim) const {
919     switch (Dim) {
920     case 0:
921       assert(hasWorkGroupIDX());
922       return ArgInfo.WorkGroupIDX.getRegister();
923     case 1:
924       assert(hasWorkGroupIDY());
925       return ArgInfo.WorkGroupIDY.getRegister();
926     case 2:
927       assert(hasWorkGroupIDZ());
928       return ArgInfo.WorkGroupIDZ.getRegister();
929     }
930     llvm_unreachable("unexpected dimension");
931   }
932 
933   const AMDGPUBufferPseudoSourceValue *
934   getBufferPSV(const AMDGPUTargetMachine &TM) {
935     if (!BufferPSV)
936       BufferPSV = std::make_unique<AMDGPUBufferPseudoSourceValue>(TM);
937 
938     return BufferPSV.get();
939   }
940 
941   const AMDGPUImagePseudoSourceValue *
942   getImagePSV(const AMDGPUTargetMachine &TM) {
943     if (!ImagePSV)
944       ImagePSV = std::make_unique<AMDGPUImagePseudoSourceValue>(TM);
945 
946     return ImagePSV.get();
947   }
948 
949   const AMDGPUGWSResourcePseudoSourceValue *
950   getGWSPSV(const AMDGPUTargetMachine &TM) {
951     if (!GWSResourcePSV) {
952       GWSResourcePSV = std::make_unique<AMDGPUGWSResourcePseudoSourceValue>(TM);
953     }
954 
955     return GWSResourcePSV.get();
956   }
957 
958   unsigned getOccupancy() const {
959     return Occupancy;
960   }
961 
962   unsigned getMinAllowedOccupancy() const {
963     if (!isMemoryBound() && !needsWaveLimiter())
964       return Occupancy;
965     return (Occupancy < 4) ? Occupancy : 4;
966   }
967 
968   void limitOccupancy(const MachineFunction &MF);
969 
970   void limitOccupancy(unsigned Limit) {
971     if (Occupancy > Limit)
972       Occupancy = Limit;
973   }
974 
975   void increaseOccupancy(const MachineFunction &MF, unsigned Limit) {
976     if (Occupancy < Limit)
977       Occupancy = Limit;
978     limitOccupancy(MF);
979   }
980 
981   bool mayNeedAGPRs() const {
982     return MayNeedAGPRs;
983   }
984 
985   // \returns true if a function has a use of AGPRs via inline asm or
986   // has a call which may use it.
987   bool mayUseAGPRs(const MachineFunction &MF) const;
988 
989   // \returns true if a function needs or may need AGPRs.
990   bool usesAGPRs(const MachineFunction &MF) const;
991 };
992 
993 } // end namespace llvm
994 
995 #endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
996