1 //===- AMDGPUBaseInfo.cpp - AMDGPU Base encoding information --------------===//
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 #include "AMDGPUBaseInfo.h"
10 #include "AMDGPU.h"
11 #include "AMDGPUAsmUtils.h"
12 #include "AMDKernelCodeT.h"
13 #include "GCNSubtarget.h"
14 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
15 #include "llvm/BinaryFormat/ELF.h"
16 #include "llvm/IR/Attributes.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/GlobalValue.h"
19 #include "llvm/IR/IntrinsicsAMDGPU.h"
20 #include "llvm/IR/IntrinsicsR600.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/MC/MCSubtargetInfo.h"
23 #include "llvm/Support/AMDHSAKernelDescriptor.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/TargetParser.h"
26 
27 #define GET_INSTRINFO_NAMED_OPS
28 #define GET_INSTRMAP_INFO
29 #include "AMDGPUGenInstrInfo.inc"
30 
31 static llvm::cl::opt<unsigned> AmdhsaCodeObjectVersion(
32   "amdhsa-code-object-version", llvm::cl::Hidden,
33   llvm::cl::desc("AMDHSA Code Object Version"), llvm::cl::init(4),
34   llvm::cl::ZeroOrMore);
35 
36 namespace {
37 
38 /// \returns Bit mask for given bit \p Shift and bit \p Width.
39 unsigned getBitMask(unsigned Shift, unsigned Width) {
40   return ((1 << Width) - 1) << Shift;
41 }
42 
43 /// Packs \p Src into \p Dst for given bit \p Shift and bit \p Width.
44 ///
45 /// \returns Packed \p Dst.
46 unsigned packBits(unsigned Src, unsigned Dst, unsigned Shift, unsigned Width) {
47   Dst &= ~(1 << Shift) & ~getBitMask(Shift, Width);
48   Dst |= (Src << Shift) & getBitMask(Shift, Width);
49   return Dst;
50 }
51 
52 /// Unpacks bits from \p Src for given bit \p Shift and bit \p Width.
53 ///
54 /// \returns Unpacked bits.
55 unsigned unpackBits(unsigned Src, unsigned Shift, unsigned Width) {
56   return (Src & getBitMask(Shift, Width)) >> Shift;
57 }
58 
59 /// \returns Vmcnt bit shift (lower bits).
60 unsigned getVmcntBitShiftLo() { return 0; }
61 
62 /// \returns Vmcnt bit width (lower bits).
63 unsigned getVmcntBitWidthLo() { return 4; }
64 
65 /// \returns Expcnt bit shift.
66 unsigned getExpcntBitShift() { return 4; }
67 
68 /// \returns Expcnt bit width.
69 unsigned getExpcntBitWidth() { return 3; }
70 
71 /// \returns Lgkmcnt bit shift.
72 unsigned getLgkmcntBitShift() { return 8; }
73 
74 /// \returns Lgkmcnt bit width.
75 unsigned getLgkmcntBitWidth(unsigned VersionMajor) {
76   return (VersionMajor >= 10) ? 6 : 4;
77 }
78 
79 /// \returns Vmcnt bit shift (higher bits).
80 unsigned getVmcntBitShiftHi() { return 14; }
81 
82 /// \returns Vmcnt bit width (higher bits).
83 unsigned getVmcntBitWidthHi() { return 2; }
84 
85 } // end namespace anonymous
86 
87 namespace llvm {
88 
89 namespace AMDGPU {
90 
91 Optional<uint8_t> getHsaAbiVersion(const MCSubtargetInfo *STI) {
92   if (STI && STI->getTargetTriple().getOS() != Triple::AMDHSA)
93     return None;
94 
95   switch (AmdhsaCodeObjectVersion) {
96   case 2:
97     return ELF::ELFABIVERSION_AMDGPU_HSA_V2;
98   case 3:
99     return ELF::ELFABIVERSION_AMDGPU_HSA_V3;
100   case 4:
101     return ELF::ELFABIVERSION_AMDGPU_HSA_V4;
102   case 5:
103     return ELF::ELFABIVERSION_AMDGPU_HSA_V5;
104   default:
105     report_fatal_error(Twine("Unsupported AMDHSA Code Object Version ") +
106                        Twine(AmdhsaCodeObjectVersion));
107   }
108 }
109 
110 bool isHsaAbiVersion2(const MCSubtargetInfo *STI) {
111   if (Optional<uint8_t> HsaAbiVer = getHsaAbiVersion(STI))
112     return *HsaAbiVer == ELF::ELFABIVERSION_AMDGPU_HSA_V2;
113   return false;
114 }
115 
116 bool isHsaAbiVersion3(const MCSubtargetInfo *STI) {
117   if (Optional<uint8_t> HsaAbiVer = getHsaAbiVersion(STI))
118     return *HsaAbiVer == ELF::ELFABIVERSION_AMDGPU_HSA_V3;
119   return false;
120 }
121 
122 bool isHsaAbiVersion4(const MCSubtargetInfo *STI) {
123   if (Optional<uint8_t> HsaAbiVer = getHsaAbiVersion(STI))
124     return *HsaAbiVer == ELF::ELFABIVERSION_AMDGPU_HSA_V4;
125   return false;
126 }
127 
128 bool isHsaAbiVersion5(const MCSubtargetInfo *STI) {
129   if (Optional<uint8_t> HsaAbiVer = getHsaAbiVersion(STI))
130     return *HsaAbiVer == ELF::ELFABIVERSION_AMDGPU_HSA_V5;
131   return false;
132 }
133 
134 bool isHsaAbiVersion3AndAbove(const MCSubtargetInfo *STI) {
135   return isHsaAbiVersion3(STI) || isHsaAbiVersion4(STI) ||
136          isHsaAbiVersion5(STI);
137 }
138 
139 unsigned getAmdhsaCodeObjectVersion() {
140   return AmdhsaCodeObjectVersion;
141 }
142 
143 // FIXME: All such magic numbers about the ABI should be in a
144 // central TD file.
145 unsigned getHostcallImplicitArgPosition() {
146   switch (AmdhsaCodeObjectVersion) {
147   case 2:
148   case 3:
149   case 4:
150     return 24;
151   case 5:
152     return 80;
153   default:
154     llvm_unreachable("Unexpected code object version");
155     return 0;
156   }
157 }
158 
159 unsigned getHeapPtrImplicitArgPosition() {
160   if (AmdhsaCodeObjectVersion == 5)
161     return 96;
162   llvm_unreachable("hidden_heap is supported only by code object version 5");
163   return 0;
164 }
165 
166 unsigned getQueuePtrImplicitArgPosition() {
167   if (AmdhsaCodeObjectVersion == 5)
168     return 200;
169   llvm_unreachable("queue_ptr is supported only by code object version 5");
170   return 0;
171 }
172 
173 #define GET_MIMGBaseOpcodesTable_IMPL
174 #define GET_MIMGDimInfoTable_IMPL
175 #define GET_MIMGInfoTable_IMPL
176 #define GET_MIMGLZMappingTable_IMPL
177 #define GET_MIMGMIPMappingTable_IMPL
178 #define GET_MIMGBiasMappingTable_IMPL
179 #define GET_MIMGOffsetMappingTable_IMPL
180 #define GET_MIMGG16MappingTable_IMPL
181 #include "AMDGPUGenSearchableTables.inc"
182 
183 int getMIMGOpcode(unsigned BaseOpcode, unsigned MIMGEncoding,
184                   unsigned VDataDwords, unsigned VAddrDwords) {
185   const MIMGInfo *Info = getMIMGOpcodeHelper(BaseOpcode, MIMGEncoding,
186                                              VDataDwords, VAddrDwords);
187   return Info ? Info->Opcode : -1;
188 }
189 
190 const MIMGBaseOpcodeInfo *getMIMGBaseOpcode(unsigned Opc) {
191   const MIMGInfo *Info = getMIMGInfo(Opc);
192   return Info ? getMIMGBaseOpcodeInfo(Info->BaseOpcode) : nullptr;
193 }
194 
195 int getMaskedMIMGOp(unsigned Opc, unsigned NewChannels) {
196   const MIMGInfo *OrigInfo = getMIMGInfo(Opc);
197   const MIMGInfo *NewInfo =
198       getMIMGOpcodeHelper(OrigInfo->BaseOpcode, OrigInfo->MIMGEncoding,
199                           NewChannels, OrigInfo->VAddrDwords);
200   return NewInfo ? NewInfo->Opcode : -1;
201 }
202 
203 unsigned getAddrSizeMIMGOp(const MIMGBaseOpcodeInfo *BaseOpcode,
204                            const MIMGDimInfo *Dim, bool IsA16,
205                            bool IsG16Supported) {
206   unsigned AddrWords = BaseOpcode->NumExtraArgs;
207   unsigned AddrComponents = (BaseOpcode->Coordinates ? Dim->NumCoords : 0) +
208                             (BaseOpcode->LodOrClampOrMip ? 1 : 0);
209   if (IsA16)
210     AddrWords += divideCeil(AddrComponents, 2);
211   else
212     AddrWords += AddrComponents;
213 
214   // Note: For subtargets that support A16 but not G16, enabling A16 also
215   // enables 16 bit gradients.
216   // For subtargets that support A16 (operand) and G16 (done with a different
217   // instruction encoding), they are independent.
218 
219   if (BaseOpcode->Gradients) {
220     if ((IsA16 && !IsG16Supported) || BaseOpcode->G16)
221       // There are two gradients per coordinate, we pack them separately.
222       // For the 3d case,
223       // we get (dy/du, dx/du) (-, dz/du) (dy/dv, dx/dv) (-, dz/dv)
224       AddrWords += alignTo<2>(Dim->NumGradients / 2);
225     else
226       AddrWords += Dim->NumGradients;
227   }
228   return AddrWords;
229 }
230 
231 struct MUBUFInfo {
232   uint16_t Opcode;
233   uint16_t BaseOpcode;
234   uint8_t elements;
235   bool has_vaddr;
236   bool has_srsrc;
237   bool has_soffset;
238   bool IsBufferInv;
239 };
240 
241 struct MTBUFInfo {
242   uint16_t Opcode;
243   uint16_t BaseOpcode;
244   uint8_t elements;
245   bool has_vaddr;
246   bool has_srsrc;
247   bool has_soffset;
248 };
249 
250 struct SMInfo {
251   uint16_t Opcode;
252   bool IsBuffer;
253 };
254 
255 struct VOPInfo {
256   uint16_t Opcode;
257   bool IsSingle;
258 };
259 
260 #define GET_MTBUFInfoTable_DECL
261 #define GET_MTBUFInfoTable_IMPL
262 #define GET_MUBUFInfoTable_DECL
263 #define GET_MUBUFInfoTable_IMPL
264 #define GET_SMInfoTable_DECL
265 #define GET_SMInfoTable_IMPL
266 #define GET_VOP1InfoTable_DECL
267 #define GET_VOP1InfoTable_IMPL
268 #define GET_VOP2InfoTable_DECL
269 #define GET_VOP2InfoTable_IMPL
270 #define GET_VOP3InfoTable_DECL
271 #define GET_VOP3InfoTable_IMPL
272 #include "AMDGPUGenSearchableTables.inc"
273 
274 int getMTBUFBaseOpcode(unsigned Opc) {
275   const MTBUFInfo *Info = getMTBUFInfoFromOpcode(Opc);
276   return Info ? Info->BaseOpcode : -1;
277 }
278 
279 int getMTBUFOpcode(unsigned BaseOpc, unsigned Elements) {
280   const MTBUFInfo *Info = getMTBUFInfoFromBaseOpcodeAndElements(BaseOpc, Elements);
281   return Info ? Info->Opcode : -1;
282 }
283 
284 int getMTBUFElements(unsigned Opc) {
285   const MTBUFInfo *Info = getMTBUFOpcodeHelper(Opc);
286   return Info ? Info->elements : 0;
287 }
288 
289 bool getMTBUFHasVAddr(unsigned Opc) {
290   const MTBUFInfo *Info = getMTBUFOpcodeHelper(Opc);
291   return Info ? Info->has_vaddr : false;
292 }
293 
294 bool getMTBUFHasSrsrc(unsigned Opc) {
295   const MTBUFInfo *Info = getMTBUFOpcodeHelper(Opc);
296   return Info ? Info->has_srsrc : false;
297 }
298 
299 bool getMTBUFHasSoffset(unsigned Opc) {
300   const MTBUFInfo *Info = getMTBUFOpcodeHelper(Opc);
301   return Info ? Info->has_soffset : false;
302 }
303 
304 int getMUBUFBaseOpcode(unsigned Opc) {
305   const MUBUFInfo *Info = getMUBUFInfoFromOpcode(Opc);
306   return Info ? Info->BaseOpcode : -1;
307 }
308 
309 int getMUBUFOpcode(unsigned BaseOpc, unsigned Elements) {
310   const MUBUFInfo *Info = getMUBUFInfoFromBaseOpcodeAndElements(BaseOpc, Elements);
311   return Info ? Info->Opcode : -1;
312 }
313 
314 int getMUBUFElements(unsigned Opc) {
315   const MUBUFInfo *Info = getMUBUFOpcodeHelper(Opc);
316   return Info ? Info->elements : 0;
317 }
318 
319 bool getMUBUFHasVAddr(unsigned Opc) {
320   const MUBUFInfo *Info = getMUBUFOpcodeHelper(Opc);
321   return Info ? Info->has_vaddr : false;
322 }
323 
324 bool getMUBUFHasSrsrc(unsigned Opc) {
325   const MUBUFInfo *Info = getMUBUFOpcodeHelper(Opc);
326   return Info ? Info->has_srsrc : false;
327 }
328 
329 bool getMUBUFHasSoffset(unsigned Opc) {
330   const MUBUFInfo *Info = getMUBUFOpcodeHelper(Opc);
331   return Info ? Info->has_soffset : false;
332 }
333 
334 bool getMUBUFIsBufferInv(unsigned Opc) {
335   const MUBUFInfo *Info = getMUBUFOpcodeHelper(Opc);
336   return Info ? Info->IsBufferInv : false;
337 }
338 
339 bool getSMEMIsBuffer(unsigned Opc) {
340   const SMInfo *Info = getSMEMOpcodeHelper(Opc);
341   return Info ? Info->IsBuffer : false;
342 }
343 
344 bool getVOP1IsSingle(unsigned Opc) {
345   const VOPInfo *Info = getVOP1OpcodeHelper(Opc);
346   return Info ? Info->IsSingle : false;
347 }
348 
349 bool getVOP2IsSingle(unsigned Opc) {
350   const VOPInfo *Info = getVOP2OpcodeHelper(Opc);
351   return Info ? Info->IsSingle : false;
352 }
353 
354 bool getVOP3IsSingle(unsigned Opc) {
355   const VOPInfo *Info = getVOP3OpcodeHelper(Opc);
356   return Info ? Info->IsSingle : false;
357 }
358 
359 // Wrapper for Tablegen'd function.  enum Subtarget is not defined in any
360 // header files, so we need to wrap it in a function that takes unsigned
361 // instead.
362 int getMCOpcode(uint16_t Opcode, unsigned Gen) {
363   return getMCOpcodeGen(Opcode, static_cast<Subtarget>(Gen));
364 }
365 
366 namespace IsaInfo {
367 
368 AMDGPUTargetID::AMDGPUTargetID(const MCSubtargetInfo &STI)
369     : STI(STI), XnackSetting(TargetIDSetting::Any),
370       SramEccSetting(TargetIDSetting::Any) {
371   if (!STI.getFeatureBits().test(FeatureSupportsXNACK))
372     XnackSetting = TargetIDSetting::Unsupported;
373   if (!STI.getFeatureBits().test(FeatureSupportsSRAMECC))
374     SramEccSetting = TargetIDSetting::Unsupported;
375 }
376 
377 void AMDGPUTargetID::setTargetIDFromFeaturesString(StringRef FS) {
378   // Check if xnack or sramecc is explicitly enabled or disabled.  In the
379   // absence of the target features we assume we must generate code that can run
380   // in any environment.
381   SubtargetFeatures Features(FS);
382   Optional<bool> XnackRequested;
383   Optional<bool> SramEccRequested;
384 
385   for (const std::string &Feature : Features.getFeatures()) {
386     if (Feature == "+xnack")
387       XnackRequested = true;
388     else if (Feature == "-xnack")
389       XnackRequested = false;
390     else if (Feature == "+sramecc")
391       SramEccRequested = true;
392     else if (Feature == "-sramecc")
393       SramEccRequested = false;
394   }
395 
396   bool XnackSupported = isXnackSupported();
397   bool SramEccSupported = isSramEccSupported();
398 
399   if (XnackRequested) {
400     if (XnackSupported) {
401       XnackSetting =
402           *XnackRequested ? TargetIDSetting::On : TargetIDSetting::Off;
403     } else {
404       // If a specific xnack setting was requested and this GPU does not support
405       // xnack emit a warning. Setting will remain set to "Unsupported".
406       if (*XnackRequested) {
407         errs() << "warning: xnack 'On' was requested for a processor that does "
408                   "not support it!\n";
409       } else {
410         errs() << "warning: xnack 'Off' was requested for a processor that "
411                   "does not support it!\n";
412       }
413     }
414   }
415 
416   if (SramEccRequested) {
417     if (SramEccSupported) {
418       SramEccSetting =
419           *SramEccRequested ? TargetIDSetting::On : TargetIDSetting::Off;
420     } else {
421       // If a specific sramecc setting was requested and this GPU does not
422       // support sramecc emit a warning. Setting will remain set to
423       // "Unsupported".
424       if (*SramEccRequested) {
425         errs() << "warning: sramecc 'On' was requested for a processor that "
426                   "does not support it!\n";
427       } else {
428         errs() << "warning: sramecc 'Off' was requested for a processor that "
429                   "does not support it!\n";
430       }
431     }
432   }
433 }
434 
435 static TargetIDSetting
436 getTargetIDSettingFromFeatureString(StringRef FeatureString) {
437   if (FeatureString.endswith("-"))
438     return TargetIDSetting::Off;
439   if (FeatureString.endswith("+"))
440     return TargetIDSetting::On;
441 
442   llvm_unreachable("Malformed feature string");
443 }
444 
445 void AMDGPUTargetID::setTargetIDFromTargetIDStream(StringRef TargetID) {
446   SmallVector<StringRef, 3> TargetIDSplit;
447   TargetID.split(TargetIDSplit, ':');
448 
449   for (const auto &FeatureString : TargetIDSplit) {
450     if (FeatureString.startswith("xnack"))
451       XnackSetting = getTargetIDSettingFromFeatureString(FeatureString);
452     if (FeatureString.startswith("sramecc"))
453       SramEccSetting = getTargetIDSettingFromFeatureString(FeatureString);
454   }
455 }
456 
457 std::string AMDGPUTargetID::toString() const {
458   std::string StringRep;
459   raw_string_ostream StreamRep(StringRep);
460 
461   auto TargetTriple = STI.getTargetTriple();
462   auto Version = getIsaVersion(STI.getCPU());
463 
464   StreamRep << TargetTriple.getArchName() << '-'
465             << TargetTriple.getVendorName() << '-'
466             << TargetTriple.getOSName() << '-'
467             << TargetTriple.getEnvironmentName() << '-';
468 
469   std::string Processor;
470   // TODO: Following else statement is present here because we used various
471   // alias names for GPUs up until GFX9 (e.g. 'fiji' is same as 'gfx803').
472   // Remove once all aliases are removed from GCNProcessors.td.
473   if (Version.Major >= 9)
474     Processor = STI.getCPU().str();
475   else
476     Processor = (Twine("gfx") + Twine(Version.Major) + Twine(Version.Minor) +
477                  Twine(Version.Stepping))
478                     .str();
479 
480   std::string Features;
481   if (Optional<uint8_t> HsaAbiVersion = getHsaAbiVersion(&STI)) {
482     switch (*HsaAbiVersion) {
483     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
484       // Code object V2 only supported specific processors and had fixed
485       // settings for the XNACK.
486       if (Processor == "gfx600") {
487       } else if (Processor == "gfx601") {
488       } else if (Processor == "gfx602") {
489       } else if (Processor == "gfx700") {
490       } else if (Processor == "gfx701") {
491       } else if (Processor == "gfx702") {
492       } else if (Processor == "gfx703") {
493       } else if (Processor == "gfx704") {
494       } else if (Processor == "gfx705") {
495       } else if (Processor == "gfx801") {
496         if (!isXnackOnOrAny())
497           report_fatal_error(
498               "AMD GPU code object V2 does not support processor " +
499               Twine(Processor) + " without XNACK");
500       } else if (Processor == "gfx802") {
501       } else if (Processor == "gfx803") {
502       } else if (Processor == "gfx805") {
503       } else if (Processor == "gfx810") {
504         if (!isXnackOnOrAny())
505           report_fatal_error(
506               "AMD GPU code object V2 does not support processor " +
507               Twine(Processor) + " without XNACK");
508       } else if (Processor == "gfx900") {
509         if (isXnackOnOrAny())
510           Processor = "gfx901";
511       } else if (Processor == "gfx902") {
512         if (isXnackOnOrAny())
513           Processor = "gfx903";
514       } else if (Processor == "gfx904") {
515         if (isXnackOnOrAny())
516           Processor = "gfx905";
517       } else if (Processor == "gfx906") {
518         if (isXnackOnOrAny())
519           Processor = "gfx907";
520       } else if (Processor == "gfx90c") {
521         if (isXnackOnOrAny())
522           report_fatal_error(
523               "AMD GPU code object V2 does not support processor " +
524               Twine(Processor) + " with XNACK being ON or ANY");
525       } else {
526         report_fatal_error(
527             "AMD GPU code object V2 does not support processor " +
528             Twine(Processor));
529       }
530       break;
531     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
532       // xnack.
533       if (isXnackOnOrAny())
534         Features += "+xnack";
535       // In code object v2 and v3, "sramecc" feature was spelled with a
536       // hyphen ("sram-ecc").
537       if (isSramEccOnOrAny())
538         Features += "+sram-ecc";
539       break;
540     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
541     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
542       // sramecc.
543       if (getSramEccSetting() == TargetIDSetting::Off)
544         Features += ":sramecc-";
545       else if (getSramEccSetting() == TargetIDSetting::On)
546         Features += ":sramecc+";
547       // xnack.
548       if (getXnackSetting() == TargetIDSetting::Off)
549         Features += ":xnack-";
550       else if (getXnackSetting() == TargetIDSetting::On)
551         Features += ":xnack+";
552       break;
553     default:
554       break;
555     }
556   }
557 
558   StreamRep << Processor << Features;
559 
560   StreamRep.flush();
561   return StringRep;
562 }
563 
564 unsigned getWavefrontSize(const MCSubtargetInfo *STI) {
565   if (STI->getFeatureBits().test(FeatureWavefrontSize16))
566     return 16;
567   if (STI->getFeatureBits().test(FeatureWavefrontSize32))
568     return 32;
569 
570   return 64;
571 }
572 
573 unsigned getLocalMemorySize(const MCSubtargetInfo *STI) {
574   if (STI->getFeatureBits().test(FeatureLocalMemorySize32768))
575     return 32768;
576   if (STI->getFeatureBits().test(FeatureLocalMemorySize65536))
577     return 65536;
578 
579   return 0;
580 }
581 
582 unsigned getEUsPerCU(const MCSubtargetInfo *STI) {
583   // "Per CU" really means "per whatever functional block the waves of a
584   // workgroup must share". For gfx10 in CU mode this is the CU, which contains
585   // two SIMDs.
586   if (isGFX10Plus(*STI) && STI->getFeatureBits().test(FeatureCuMode))
587     return 2;
588   // Pre-gfx10 a CU contains four SIMDs. For gfx10 in WGP mode the WGP contains
589   // two CUs, so a total of four SIMDs.
590   return 4;
591 }
592 
593 unsigned getMaxWorkGroupsPerCU(const MCSubtargetInfo *STI,
594                                unsigned FlatWorkGroupSize) {
595   assert(FlatWorkGroupSize != 0);
596   if (STI->getTargetTriple().getArch() != Triple::amdgcn)
597     return 8;
598   unsigned N = getWavesPerWorkGroup(STI, FlatWorkGroupSize);
599   if (N == 1)
600     return 40;
601   N = 40 / N;
602   return std::min(N, 16u);
603 }
604 
605 unsigned getMinWavesPerEU(const MCSubtargetInfo *STI) {
606   return 1;
607 }
608 
609 unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI) {
610   // FIXME: Need to take scratch memory into account.
611   if (isGFX90A(*STI))
612     return 8;
613   if (!isGFX10Plus(*STI))
614     return 10;
615   return hasGFX10_3Insts(*STI) ? 16 : 20;
616 }
617 
618 unsigned getWavesPerEUForWorkGroup(const MCSubtargetInfo *STI,
619                                    unsigned FlatWorkGroupSize) {
620   return divideCeil(getWavesPerWorkGroup(STI, FlatWorkGroupSize),
621                     getEUsPerCU(STI));
622 }
623 
624 unsigned getMinFlatWorkGroupSize(const MCSubtargetInfo *STI) {
625   return 1;
626 }
627 
628 unsigned getMaxFlatWorkGroupSize(const MCSubtargetInfo *STI) {
629   // Some subtargets allow encoding 2048, but this isn't tested or supported.
630   return 1024;
631 }
632 
633 unsigned getWavesPerWorkGroup(const MCSubtargetInfo *STI,
634                               unsigned FlatWorkGroupSize) {
635   return divideCeil(FlatWorkGroupSize, getWavefrontSize(STI));
636 }
637 
638 unsigned getSGPRAllocGranule(const MCSubtargetInfo *STI) {
639   IsaVersion Version = getIsaVersion(STI->getCPU());
640   if (Version.Major >= 10)
641     return getAddressableNumSGPRs(STI);
642   if (Version.Major >= 8)
643     return 16;
644   return 8;
645 }
646 
647 unsigned getSGPREncodingGranule(const MCSubtargetInfo *STI) {
648   return 8;
649 }
650 
651 unsigned getTotalNumSGPRs(const MCSubtargetInfo *STI) {
652   IsaVersion Version = getIsaVersion(STI->getCPU());
653   if (Version.Major >= 8)
654     return 800;
655   return 512;
656 }
657 
658 unsigned getAddressableNumSGPRs(const MCSubtargetInfo *STI) {
659   if (STI->getFeatureBits().test(FeatureSGPRInitBug))
660     return FIXED_NUM_SGPRS_FOR_INIT_BUG;
661 
662   IsaVersion Version = getIsaVersion(STI->getCPU());
663   if (Version.Major >= 10)
664     return 106;
665   if (Version.Major >= 8)
666     return 102;
667   return 104;
668 }
669 
670 unsigned getMinNumSGPRs(const MCSubtargetInfo *STI, unsigned WavesPerEU) {
671   assert(WavesPerEU != 0);
672 
673   IsaVersion Version = getIsaVersion(STI->getCPU());
674   if (Version.Major >= 10)
675     return 0;
676 
677   if (WavesPerEU >= getMaxWavesPerEU(STI))
678     return 0;
679 
680   unsigned MinNumSGPRs = getTotalNumSGPRs(STI) / (WavesPerEU + 1);
681   if (STI->getFeatureBits().test(FeatureTrapHandler))
682     MinNumSGPRs -= std::min(MinNumSGPRs, (unsigned)TRAP_NUM_SGPRS);
683   MinNumSGPRs = alignDown(MinNumSGPRs, getSGPRAllocGranule(STI)) + 1;
684   return std::min(MinNumSGPRs, getAddressableNumSGPRs(STI));
685 }
686 
687 unsigned getMaxNumSGPRs(const MCSubtargetInfo *STI, unsigned WavesPerEU,
688                         bool Addressable) {
689   assert(WavesPerEU != 0);
690 
691   unsigned AddressableNumSGPRs = getAddressableNumSGPRs(STI);
692   IsaVersion Version = getIsaVersion(STI->getCPU());
693   if (Version.Major >= 10)
694     return Addressable ? AddressableNumSGPRs : 108;
695   if (Version.Major >= 8 && !Addressable)
696     AddressableNumSGPRs = 112;
697   unsigned MaxNumSGPRs = getTotalNumSGPRs(STI) / WavesPerEU;
698   if (STI->getFeatureBits().test(FeatureTrapHandler))
699     MaxNumSGPRs -= std::min(MaxNumSGPRs, (unsigned)TRAP_NUM_SGPRS);
700   MaxNumSGPRs = alignDown(MaxNumSGPRs, getSGPRAllocGranule(STI));
701   return std::min(MaxNumSGPRs, AddressableNumSGPRs);
702 }
703 
704 unsigned getNumExtraSGPRs(const MCSubtargetInfo *STI, bool VCCUsed,
705                           bool FlatScrUsed, bool XNACKUsed) {
706   unsigned ExtraSGPRs = 0;
707   if (VCCUsed)
708     ExtraSGPRs = 2;
709 
710   IsaVersion Version = getIsaVersion(STI->getCPU());
711   if (Version.Major >= 10)
712     return ExtraSGPRs;
713 
714   if (Version.Major < 8) {
715     if (FlatScrUsed)
716       ExtraSGPRs = 4;
717   } else {
718     if (XNACKUsed)
719       ExtraSGPRs = 4;
720 
721     if (FlatScrUsed ||
722         STI->getFeatureBits().test(AMDGPU::FeatureArchitectedFlatScratch))
723       ExtraSGPRs = 6;
724   }
725 
726   return ExtraSGPRs;
727 }
728 
729 unsigned getNumExtraSGPRs(const MCSubtargetInfo *STI, bool VCCUsed,
730                           bool FlatScrUsed) {
731   return getNumExtraSGPRs(STI, VCCUsed, FlatScrUsed,
732                           STI->getFeatureBits().test(AMDGPU::FeatureXNACK));
733 }
734 
735 unsigned getNumSGPRBlocks(const MCSubtargetInfo *STI, unsigned NumSGPRs) {
736   NumSGPRs = alignTo(std::max(1u, NumSGPRs), getSGPREncodingGranule(STI));
737   // SGPRBlocks is actual number of SGPR blocks minus 1.
738   return NumSGPRs / getSGPREncodingGranule(STI) - 1;
739 }
740 
741 unsigned getVGPRAllocGranule(const MCSubtargetInfo *STI,
742                              Optional<bool> EnableWavefrontSize32) {
743   if (STI->getFeatureBits().test(FeatureGFX90AInsts))
744     return 8;
745 
746   bool IsWave32 = EnableWavefrontSize32 ?
747       *EnableWavefrontSize32 :
748       STI->getFeatureBits().test(FeatureWavefrontSize32);
749 
750   if (hasGFX10_3Insts(*STI))
751     return IsWave32 ? 16 : 8;
752 
753   return IsWave32 ? 8 : 4;
754 }
755 
756 unsigned getVGPREncodingGranule(const MCSubtargetInfo *STI,
757                                 Optional<bool> EnableWavefrontSize32) {
758   if (STI->getFeatureBits().test(FeatureGFX90AInsts))
759     return 8;
760 
761   bool IsWave32 = EnableWavefrontSize32 ?
762       *EnableWavefrontSize32 :
763       STI->getFeatureBits().test(FeatureWavefrontSize32);
764 
765   return IsWave32 ? 8 : 4;
766 }
767 
768 unsigned getTotalNumVGPRs(const MCSubtargetInfo *STI) {
769   if (STI->getFeatureBits().test(FeatureGFX90AInsts))
770     return 512;
771   if (!isGFX10Plus(*STI))
772     return 256;
773   return STI->getFeatureBits().test(FeatureWavefrontSize32) ? 1024 : 512;
774 }
775 
776 unsigned getAddressableNumVGPRs(const MCSubtargetInfo *STI) {
777   if (STI->getFeatureBits().test(FeatureGFX90AInsts))
778     return 512;
779   return 256;
780 }
781 
782 unsigned getMinNumVGPRs(const MCSubtargetInfo *STI, unsigned WavesPerEU) {
783   assert(WavesPerEU != 0);
784 
785   if (WavesPerEU >= getMaxWavesPerEU(STI))
786     return 0;
787   unsigned MinNumVGPRs =
788       alignDown(getTotalNumVGPRs(STI) / (WavesPerEU + 1),
789                 getVGPRAllocGranule(STI)) + 1;
790   return std::min(MinNumVGPRs, getAddressableNumVGPRs(STI));
791 }
792 
793 unsigned getMaxNumVGPRs(const MCSubtargetInfo *STI, unsigned WavesPerEU) {
794   assert(WavesPerEU != 0);
795 
796   unsigned MaxNumVGPRs = alignDown(getTotalNumVGPRs(STI) / WavesPerEU,
797                                    getVGPRAllocGranule(STI));
798   unsigned AddressableNumVGPRs = getAddressableNumVGPRs(STI);
799   return std::min(MaxNumVGPRs, AddressableNumVGPRs);
800 }
801 
802 unsigned getNumVGPRBlocks(const MCSubtargetInfo *STI, unsigned NumVGPRs,
803                           Optional<bool> EnableWavefrontSize32) {
804   NumVGPRs = alignTo(std::max(1u, NumVGPRs),
805                      getVGPREncodingGranule(STI, EnableWavefrontSize32));
806   // VGPRBlocks is actual number of VGPR blocks minus 1.
807   return NumVGPRs / getVGPREncodingGranule(STI, EnableWavefrontSize32) - 1;
808 }
809 
810 } // end namespace IsaInfo
811 
812 void initDefaultAMDKernelCodeT(amd_kernel_code_t &Header,
813                                const MCSubtargetInfo *STI) {
814   IsaVersion Version = getIsaVersion(STI->getCPU());
815 
816   memset(&Header, 0, sizeof(Header));
817 
818   Header.amd_kernel_code_version_major = 1;
819   Header.amd_kernel_code_version_minor = 2;
820   Header.amd_machine_kind = 1; // AMD_MACHINE_KIND_AMDGPU
821   Header.amd_machine_version_major = Version.Major;
822   Header.amd_machine_version_minor = Version.Minor;
823   Header.amd_machine_version_stepping = Version.Stepping;
824   Header.kernel_code_entry_byte_offset = sizeof(Header);
825   Header.wavefront_size = 6;
826 
827   // If the code object does not support indirect functions, then the value must
828   // be 0xffffffff.
829   Header.call_convention = -1;
830 
831   // These alignment values are specified in powers of two, so alignment =
832   // 2^n.  The minimum alignment is 2^4 = 16.
833   Header.kernarg_segment_alignment = 4;
834   Header.group_segment_alignment = 4;
835   Header.private_segment_alignment = 4;
836 
837   if (Version.Major >= 10) {
838     if (STI->getFeatureBits().test(FeatureWavefrontSize32)) {
839       Header.wavefront_size = 5;
840       Header.code_properties |= AMD_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
841     }
842     Header.compute_pgm_resource_registers |=
843       S_00B848_WGP_MODE(STI->getFeatureBits().test(FeatureCuMode) ? 0 : 1) |
844       S_00B848_MEM_ORDERED(1);
845   }
846 }
847 
848 amdhsa::kernel_descriptor_t getDefaultAmdhsaKernelDescriptor(
849     const MCSubtargetInfo *STI) {
850   IsaVersion Version = getIsaVersion(STI->getCPU());
851 
852   amdhsa::kernel_descriptor_t KD;
853   memset(&KD, 0, sizeof(KD));
854 
855   AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
856                   amdhsa::COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_16_64,
857                   amdhsa::FLOAT_DENORM_MODE_FLUSH_NONE);
858   AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
859                   amdhsa::COMPUTE_PGM_RSRC1_ENABLE_DX10_CLAMP, 1);
860   AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
861                   amdhsa::COMPUTE_PGM_RSRC1_ENABLE_IEEE_MODE, 1);
862   AMDHSA_BITS_SET(KD.compute_pgm_rsrc2,
863                   amdhsa::COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_X, 1);
864   if (Version.Major >= 10) {
865     AMDHSA_BITS_SET(KD.kernel_code_properties,
866                     amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32,
867                     STI->getFeatureBits().test(FeatureWavefrontSize32) ? 1 : 0);
868     AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
869                     amdhsa::COMPUTE_PGM_RSRC1_WGP_MODE,
870                     STI->getFeatureBits().test(FeatureCuMode) ? 0 : 1);
871     AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
872                     amdhsa::COMPUTE_PGM_RSRC1_MEM_ORDERED, 1);
873   }
874   if (AMDGPU::isGFX90A(*STI)) {
875     AMDHSA_BITS_SET(KD.compute_pgm_rsrc3,
876                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
877                     STI->getFeatureBits().test(FeatureTgSplit) ? 1 : 0);
878   }
879   return KD;
880 }
881 
882 bool isGroupSegment(const GlobalValue *GV) {
883   return GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS;
884 }
885 
886 bool isGlobalSegment(const GlobalValue *GV) {
887   return GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS;
888 }
889 
890 bool isReadOnlySegment(const GlobalValue *GV) {
891   unsigned AS = GV->getAddressSpace();
892   return AS == AMDGPUAS::CONSTANT_ADDRESS ||
893          AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT;
894 }
895 
896 bool shouldEmitConstantsToTextSection(const Triple &TT) {
897   return TT.getArch() == Triple::r600;
898 }
899 
900 int getIntegerAttribute(const Function &F, StringRef Name, int Default) {
901   Attribute A = F.getFnAttribute(Name);
902   int Result = Default;
903 
904   if (A.isStringAttribute()) {
905     StringRef Str = A.getValueAsString();
906     if (Str.getAsInteger(0, Result)) {
907       LLVMContext &Ctx = F.getContext();
908       Ctx.emitError("can't parse integer attribute " + Name);
909     }
910   }
911 
912   return Result;
913 }
914 
915 std::pair<int, int> getIntegerPairAttribute(const Function &F,
916                                             StringRef Name,
917                                             std::pair<int, int> Default,
918                                             bool OnlyFirstRequired) {
919   Attribute A = F.getFnAttribute(Name);
920   if (!A.isStringAttribute())
921     return Default;
922 
923   LLVMContext &Ctx = F.getContext();
924   std::pair<int, int> Ints = Default;
925   std::pair<StringRef, StringRef> Strs = A.getValueAsString().split(',');
926   if (Strs.first.trim().getAsInteger(0, Ints.first)) {
927     Ctx.emitError("can't parse first integer attribute " + Name);
928     return Default;
929   }
930   if (Strs.second.trim().getAsInteger(0, Ints.second)) {
931     if (!OnlyFirstRequired || !Strs.second.trim().empty()) {
932       Ctx.emitError("can't parse second integer attribute " + Name);
933       return Default;
934     }
935   }
936 
937   return Ints;
938 }
939 
940 unsigned getVmcntBitMask(const IsaVersion &Version) {
941   unsigned VmcntLo = (1 << getVmcntBitWidthLo()) - 1;
942   if (Version.Major < 9)
943     return VmcntLo;
944 
945   unsigned VmcntHi = ((1 << getVmcntBitWidthHi()) - 1) << getVmcntBitWidthLo();
946   return VmcntLo | VmcntHi;
947 }
948 
949 unsigned getExpcntBitMask(const IsaVersion &Version) {
950   return (1 << getExpcntBitWidth()) - 1;
951 }
952 
953 unsigned getLgkmcntBitMask(const IsaVersion &Version) {
954   return (1 << getLgkmcntBitWidth(Version.Major)) - 1;
955 }
956 
957 unsigned getWaitcntBitMask(const IsaVersion &Version) {
958   unsigned VmcntLo = getBitMask(getVmcntBitShiftLo(), getVmcntBitWidthLo());
959   unsigned Expcnt = getBitMask(getExpcntBitShift(), getExpcntBitWidth());
960   unsigned Lgkmcnt = getBitMask(getLgkmcntBitShift(),
961                                 getLgkmcntBitWidth(Version.Major));
962   unsigned Waitcnt = VmcntLo | Expcnt | Lgkmcnt;
963   if (Version.Major < 9)
964     return Waitcnt;
965 
966   unsigned VmcntHi = getBitMask(getVmcntBitShiftHi(), getVmcntBitWidthHi());
967   return Waitcnt | VmcntHi;
968 }
969 
970 unsigned decodeVmcnt(const IsaVersion &Version, unsigned Waitcnt) {
971   unsigned VmcntLo =
972       unpackBits(Waitcnt, getVmcntBitShiftLo(), getVmcntBitWidthLo());
973   if (Version.Major < 9)
974     return VmcntLo;
975 
976   unsigned VmcntHi =
977       unpackBits(Waitcnt, getVmcntBitShiftHi(), getVmcntBitWidthHi());
978   VmcntHi <<= getVmcntBitWidthLo();
979   return VmcntLo | VmcntHi;
980 }
981 
982 unsigned decodeExpcnt(const IsaVersion &Version, unsigned Waitcnt) {
983   return unpackBits(Waitcnt, getExpcntBitShift(), getExpcntBitWidth());
984 }
985 
986 unsigned decodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt) {
987   return unpackBits(Waitcnt, getLgkmcntBitShift(),
988                     getLgkmcntBitWidth(Version.Major));
989 }
990 
991 void decodeWaitcnt(const IsaVersion &Version, unsigned Waitcnt,
992                    unsigned &Vmcnt, unsigned &Expcnt, unsigned &Lgkmcnt) {
993   Vmcnt = decodeVmcnt(Version, Waitcnt);
994   Expcnt = decodeExpcnt(Version, Waitcnt);
995   Lgkmcnt = decodeLgkmcnt(Version, Waitcnt);
996 }
997 
998 Waitcnt decodeWaitcnt(const IsaVersion &Version, unsigned Encoded) {
999   Waitcnt Decoded;
1000   Decoded.VmCnt = decodeVmcnt(Version, Encoded);
1001   Decoded.ExpCnt = decodeExpcnt(Version, Encoded);
1002   Decoded.LgkmCnt = decodeLgkmcnt(Version, Encoded);
1003   return Decoded;
1004 }
1005 
1006 unsigned encodeVmcnt(const IsaVersion &Version, unsigned Waitcnt,
1007                      unsigned Vmcnt) {
1008   Waitcnt =
1009       packBits(Vmcnt, Waitcnt, getVmcntBitShiftLo(), getVmcntBitWidthLo());
1010   if (Version.Major < 9)
1011     return Waitcnt;
1012 
1013   Vmcnt >>= getVmcntBitWidthLo();
1014   return packBits(Vmcnt, Waitcnt, getVmcntBitShiftHi(), getVmcntBitWidthHi());
1015 }
1016 
1017 unsigned encodeExpcnt(const IsaVersion &Version, unsigned Waitcnt,
1018                       unsigned Expcnt) {
1019   return packBits(Expcnt, Waitcnt, getExpcntBitShift(), getExpcntBitWidth());
1020 }
1021 
1022 unsigned encodeLgkmcnt(const IsaVersion &Version, unsigned Waitcnt,
1023                        unsigned Lgkmcnt) {
1024   return packBits(Lgkmcnt, Waitcnt, getLgkmcntBitShift(),
1025                                     getLgkmcntBitWidth(Version.Major));
1026 }
1027 
1028 unsigned encodeWaitcnt(const IsaVersion &Version,
1029                        unsigned Vmcnt, unsigned Expcnt, unsigned Lgkmcnt) {
1030   unsigned Waitcnt = getWaitcntBitMask(Version);
1031   Waitcnt = encodeVmcnt(Version, Waitcnt, Vmcnt);
1032   Waitcnt = encodeExpcnt(Version, Waitcnt, Expcnt);
1033   Waitcnt = encodeLgkmcnt(Version, Waitcnt, Lgkmcnt);
1034   return Waitcnt;
1035 }
1036 
1037 unsigned encodeWaitcnt(const IsaVersion &Version, const Waitcnt &Decoded) {
1038   return encodeWaitcnt(Version, Decoded.VmCnt, Decoded.ExpCnt, Decoded.LgkmCnt);
1039 }
1040 
1041 //===----------------------------------------------------------------------===//
1042 // Custom Operands.
1043 //
1044 // A table of custom operands shall describe "primary" operand names
1045 // first followed by aliases if any. It is not required but recommended
1046 // to arrange operands so that operand encoding match operand position
1047 // in the table. This will make disassembly a bit more efficient.
1048 // Unused slots in the table shall have an empty name.
1049 //
1050 //===----------------------------------------------------------------------===//
1051 
1052 template <class T>
1053 static bool isValidOpr(int Idx, const CustomOperand<T> OpInfo[], int OpInfoSize,
1054                        T Context) {
1055   return 0 <= Idx && Idx < OpInfoSize && !OpInfo[Idx].Name.empty() &&
1056          (!OpInfo[Idx].Cond || OpInfo[Idx].Cond(Context));
1057 }
1058 
1059 template <class T>
1060 static int getOprIdx(std::function<bool(const CustomOperand<T> &)> Test,
1061                      const CustomOperand<T> OpInfo[], int OpInfoSize,
1062                      T Context) {
1063   int InvalidIdx = OPR_ID_UNKNOWN;
1064   for (int Idx = 0; Idx < OpInfoSize; ++Idx) {
1065     if (Test(OpInfo[Idx])) {
1066       if (!OpInfo[Idx].Cond || OpInfo[Idx].Cond(Context))
1067         return Idx;
1068       InvalidIdx = OPR_ID_UNSUPPORTED;
1069     }
1070   }
1071   return InvalidIdx;
1072 }
1073 
1074 template <class T>
1075 static int getOprIdx(const StringRef Name, const CustomOperand<T> OpInfo[],
1076                      int OpInfoSize, T Context) {
1077   auto Test = [=](const CustomOperand<T> &Op) { return Op.Name == Name; };
1078   return getOprIdx<T>(Test, OpInfo, OpInfoSize, Context);
1079 }
1080 
1081 template <class T>
1082 static int getOprIdx(int Id, const CustomOperand<T> OpInfo[], int OpInfoSize,
1083                      T Context, bool QuickCheck = true) {
1084   auto Test = [=](const CustomOperand<T> &Op) {
1085     return Op.Encoding == Id && !Op.Name.empty();
1086   };
1087   // This is an optimization that should work in most cases.
1088   // As a side effect, it may cause selection of an alias
1089   // instead of a primary operand name in case of sparse tables.
1090   if (QuickCheck && isValidOpr<T>(Id, OpInfo, OpInfoSize, Context) &&
1091       OpInfo[Id].Encoding == Id) {
1092     return Id;
1093   }
1094   return getOprIdx<T>(Test, OpInfo, OpInfoSize, Context);
1095 }
1096 
1097 //===----------------------------------------------------------------------===//
1098 // hwreg
1099 //===----------------------------------------------------------------------===//
1100 
1101 namespace Hwreg {
1102 
1103 int64_t getHwregId(const StringRef Name, const MCSubtargetInfo &STI) {
1104   int Idx = getOprIdx<const MCSubtargetInfo &>(Name, Opr, OPR_SIZE, STI);
1105   return (Idx < 0) ? Idx : Opr[Idx].Encoding;
1106 }
1107 
1108 bool isValidHwreg(int64_t Id) {
1109   return 0 <= Id && isUInt<ID_WIDTH_>(Id);
1110 }
1111 
1112 bool isValidHwregOffset(int64_t Offset) {
1113   return 0 <= Offset && isUInt<OFFSET_WIDTH_>(Offset);
1114 }
1115 
1116 bool isValidHwregWidth(int64_t Width) {
1117   return 0 <= (Width - 1) && isUInt<WIDTH_M1_WIDTH_>(Width - 1);
1118 }
1119 
1120 uint64_t encodeHwreg(uint64_t Id, uint64_t Offset, uint64_t Width) {
1121   return (Id << ID_SHIFT_) |
1122          (Offset << OFFSET_SHIFT_) |
1123          ((Width - 1) << WIDTH_M1_SHIFT_);
1124 }
1125 
1126 StringRef getHwreg(unsigned Id, const MCSubtargetInfo &STI) {
1127   int Idx = getOprIdx<const MCSubtargetInfo &>(Id, Opr, OPR_SIZE, STI);
1128   return (Idx < 0) ? "" : Opr[Idx].Name;
1129 }
1130 
1131 void decodeHwreg(unsigned Val, unsigned &Id, unsigned &Offset, unsigned &Width) {
1132   Id = (Val & ID_MASK_) >> ID_SHIFT_;
1133   Offset = (Val & OFFSET_MASK_) >> OFFSET_SHIFT_;
1134   Width = ((Val & WIDTH_M1_MASK_) >> WIDTH_M1_SHIFT_) + 1;
1135 }
1136 
1137 } // namespace Hwreg
1138 
1139 //===----------------------------------------------------------------------===//
1140 // exp tgt
1141 //===----------------------------------------------------------------------===//
1142 
1143 namespace Exp {
1144 
1145 struct ExpTgt {
1146   StringLiteral Name;
1147   unsigned Tgt;
1148   unsigned MaxIndex;
1149 };
1150 
1151 static constexpr ExpTgt ExpTgtInfo[] = {
1152   {{"null"},  ET_NULL,   ET_NULL_MAX_IDX},
1153   {{"mrtz"},  ET_MRTZ,   ET_MRTZ_MAX_IDX},
1154   {{"prim"},  ET_PRIM,   ET_PRIM_MAX_IDX},
1155   {{"mrt"},   ET_MRT0,   ET_MRT_MAX_IDX},
1156   {{"pos"},   ET_POS0,   ET_POS_MAX_IDX},
1157   {{"param"}, ET_PARAM0, ET_PARAM_MAX_IDX},
1158 };
1159 
1160 bool getTgtName(unsigned Id, StringRef &Name, int &Index) {
1161   for (const ExpTgt &Val : ExpTgtInfo) {
1162     if (Val.Tgt <= Id && Id <= Val.Tgt + Val.MaxIndex) {
1163       Index = (Val.MaxIndex == 0) ? -1 : (Id - Val.Tgt);
1164       Name = Val.Name;
1165       return true;
1166     }
1167   }
1168   return false;
1169 }
1170 
1171 unsigned getTgtId(const StringRef Name) {
1172 
1173   for (const ExpTgt &Val : ExpTgtInfo) {
1174     if (Val.MaxIndex == 0 && Name == Val.Name)
1175       return Val.Tgt;
1176 
1177     if (Val.MaxIndex > 0 && Name.startswith(Val.Name)) {
1178       StringRef Suffix = Name.drop_front(Val.Name.size());
1179 
1180       unsigned Id;
1181       if (Suffix.getAsInteger(10, Id) || Id > Val.MaxIndex)
1182         return ET_INVALID;
1183 
1184       // Disable leading zeroes
1185       if (Suffix.size() > 1 && Suffix[0] == '0')
1186         return ET_INVALID;
1187 
1188       return Val.Tgt + Id;
1189     }
1190   }
1191   return ET_INVALID;
1192 }
1193 
1194 bool isSupportedTgtId(unsigned Id, const MCSubtargetInfo &STI) {
1195   return (Id != ET_POS4 && Id != ET_PRIM) || isGFX10Plus(STI);
1196 }
1197 
1198 } // namespace Exp
1199 
1200 //===----------------------------------------------------------------------===//
1201 // MTBUF Format
1202 //===----------------------------------------------------------------------===//
1203 
1204 namespace MTBUFFormat {
1205 
1206 int64_t getDfmt(const StringRef Name) {
1207   for (int Id = DFMT_MIN; Id <= DFMT_MAX; ++Id) {
1208     if (Name == DfmtSymbolic[Id])
1209       return Id;
1210   }
1211   return DFMT_UNDEF;
1212 }
1213 
1214 StringRef getDfmtName(unsigned Id) {
1215   assert(Id <= DFMT_MAX);
1216   return DfmtSymbolic[Id];
1217 }
1218 
1219 static StringLiteral const *getNfmtLookupTable(const MCSubtargetInfo &STI) {
1220   if (isSI(STI) || isCI(STI))
1221     return NfmtSymbolicSICI;
1222   if (isVI(STI) || isGFX9(STI))
1223     return NfmtSymbolicVI;
1224   return NfmtSymbolicGFX10;
1225 }
1226 
1227 int64_t getNfmt(const StringRef Name, const MCSubtargetInfo &STI) {
1228   auto lookupTable = getNfmtLookupTable(STI);
1229   for (int Id = NFMT_MIN; Id <= NFMT_MAX; ++Id) {
1230     if (Name == lookupTable[Id])
1231       return Id;
1232   }
1233   return NFMT_UNDEF;
1234 }
1235 
1236 StringRef getNfmtName(unsigned Id, const MCSubtargetInfo &STI) {
1237   assert(Id <= NFMT_MAX);
1238   return getNfmtLookupTable(STI)[Id];
1239 }
1240 
1241 bool isValidDfmtNfmt(unsigned Id, const MCSubtargetInfo &STI) {
1242   unsigned Dfmt;
1243   unsigned Nfmt;
1244   decodeDfmtNfmt(Id, Dfmt, Nfmt);
1245   return isValidNfmt(Nfmt, STI);
1246 }
1247 
1248 bool isValidNfmt(unsigned Id, const MCSubtargetInfo &STI) {
1249   return !getNfmtName(Id, STI).empty();
1250 }
1251 
1252 int64_t encodeDfmtNfmt(unsigned Dfmt, unsigned Nfmt) {
1253   return (Dfmt << DFMT_SHIFT) | (Nfmt << NFMT_SHIFT);
1254 }
1255 
1256 void decodeDfmtNfmt(unsigned Format, unsigned &Dfmt, unsigned &Nfmt) {
1257   Dfmt = (Format >> DFMT_SHIFT) & DFMT_MASK;
1258   Nfmt = (Format >> NFMT_SHIFT) & NFMT_MASK;
1259 }
1260 
1261 int64_t getUnifiedFormat(const StringRef Name) {
1262   for (int Id = UFMT_FIRST; Id <= UFMT_LAST; ++Id) {
1263     if (Name == UfmtSymbolic[Id])
1264       return Id;
1265   }
1266   return UFMT_UNDEF;
1267 }
1268 
1269 StringRef getUnifiedFormatName(unsigned Id) {
1270   return isValidUnifiedFormat(Id) ? UfmtSymbolic[Id] : "";
1271 }
1272 
1273 bool isValidUnifiedFormat(unsigned Id) {
1274   return Id <= UFMT_LAST;
1275 }
1276 
1277 int64_t convertDfmtNfmt2Ufmt(unsigned Dfmt, unsigned Nfmt) {
1278   int64_t Fmt = encodeDfmtNfmt(Dfmt, Nfmt);
1279   for (int Id = UFMT_FIRST; Id <= UFMT_LAST; ++Id) {
1280     if (Fmt == DfmtNfmt2UFmt[Id])
1281       return Id;
1282   }
1283   return UFMT_UNDEF;
1284 }
1285 
1286 bool isValidFormatEncoding(unsigned Val, const MCSubtargetInfo &STI) {
1287   return isGFX10Plus(STI) ? (Val <= UFMT_MAX) : (Val <= DFMT_NFMT_MAX);
1288 }
1289 
1290 unsigned getDefaultFormatEncoding(const MCSubtargetInfo &STI) {
1291   if (isGFX10Plus(STI))
1292     return UFMT_DEFAULT;
1293   return DFMT_NFMT_DEFAULT;
1294 }
1295 
1296 } // namespace MTBUFFormat
1297 
1298 //===----------------------------------------------------------------------===//
1299 // SendMsg
1300 //===----------------------------------------------------------------------===//
1301 
1302 namespace SendMsg {
1303 
1304 int64_t getMsgId(const StringRef Name) {
1305   for (int i = ID_GAPS_FIRST_; i < ID_GAPS_LAST_; ++i) {
1306     if (IdSymbolic[i] && Name == IdSymbolic[i])
1307       return i;
1308   }
1309   return ID_UNKNOWN_;
1310 }
1311 
1312 bool isValidMsgId(int64_t MsgId, const MCSubtargetInfo &STI, bool Strict) {
1313   if (Strict) {
1314     switch (MsgId) {
1315     case ID_SAVEWAVE:
1316       return isVI(STI) || isGFX9Plus(STI);
1317     case ID_STALL_WAVE_GEN:
1318     case ID_HALT_WAVES:
1319     case ID_ORDERED_PS_DONE:
1320     case ID_GS_ALLOC_REQ:
1321     case ID_GET_DOORBELL:
1322       return isGFX9Plus(STI);
1323     case ID_EARLY_PRIM_DEALLOC:
1324       return isGFX9(STI);
1325     case ID_GET_DDID:
1326       return isGFX10Plus(STI);
1327     default:
1328       return 0 <= MsgId && MsgId < ID_GAPS_LAST_ && IdSymbolic[MsgId];
1329     }
1330   } else {
1331     return 0 <= MsgId && isUInt<ID_WIDTH_>(MsgId);
1332   }
1333 }
1334 
1335 StringRef getMsgName(int64_t MsgId) {
1336   assert(0 <= MsgId && MsgId < ID_GAPS_LAST_);
1337   return IdSymbolic[MsgId];
1338 }
1339 
1340 int64_t getMsgOpId(int64_t MsgId, const StringRef Name) {
1341   const char* const *S = (MsgId == ID_SYSMSG) ? OpSysSymbolic : OpGsSymbolic;
1342   const int F = (MsgId == ID_SYSMSG) ? OP_SYS_FIRST_ : OP_GS_FIRST_;
1343   const int L = (MsgId == ID_SYSMSG) ? OP_SYS_LAST_ : OP_GS_LAST_;
1344   for (int i = F; i < L; ++i) {
1345     if (Name == S[i]) {
1346       return i;
1347     }
1348   }
1349   return OP_UNKNOWN_;
1350 }
1351 
1352 bool isValidMsgOp(int64_t MsgId, int64_t OpId, const MCSubtargetInfo &STI,
1353                   bool Strict) {
1354   assert(isValidMsgId(MsgId, STI, Strict));
1355 
1356   if (!Strict)
1357     return 0 <= OpId && isUInt<OP_WIDTH_>(OpId);
1358 
1359   switch(MsgId)
1360   {
1361   case ID_GS:
1362     return (OP_GS_FIRST_ <= OpId && OpId < OP_GS_LAST_) && OpId != OP_GS_NOP;
1363   case ID_GS_DONE:
1364     return OP_GS_FIRST_ <= OpId && OpId < OP_GS_LAST_;
1365   case ID_SYSMSG:
1366     return OP_SYS_FIRST_ <= OpId && OpId < OP_SYS_LAST_;
1367   default:
1368     return OpId == OP_NONE_;
1369   }
1370 }
1371 
1372 StringRef getMsgOpName(int64_t MsgId, int64_t OpId) {
1373   assert(msgRequiresOp(MsgId));
1374   return (MsgId == ID_SYSMSG)? OpSysSymbolic[OpId] : OpGsSymbolic[OpId];
1375 }
1376 
1377 bool isValidMsgStream(int64_t MsgId, int64_t OpId, int64_t StreamId,
1378                       const MCSubtargetInfo &STI, bool Strict) {
1379   assert(isValidMsgOp(MsgId, OpId, STI, Strict));
1380 
1381   if (!Strict)
1382     return 0 <= StreamId && isUInt<STREAM_ID_WIDTH_>(StreamId);
1383 
1384   switch(MsgId)
1385   {
1386   case ID_GS:
1387     return STREAM_ID_FIRST_ <= StreamId && StreamId < STREAM_ID_LAST_;
1388   case ID_GS_DONE:
1389     return (OpId == OP_GS_NOP)?
1390            (StreamId == STREAM_ID_NONE_) :
1391            (STREAM_ID_FIRST_ <= StreamId && StreamId < STREAM_ID_LAST_);
1392   default:
1393     return StreamId == STREAM_ID_NONE_;
1394   }
1395 }
1396 
1397 bool msgRequiresOp(int64_t MsgId) {
1398   return MsgId == ID_GS || MsgId == ID_GS_DONE || MsgId == ID_SYSMSG;
1399 }
1400 
1401 bool msgSupportsStream(int64_t MsgId, int64_t OpId) {
1402   return (MsgId == ID_GS || MsgId == ID_GS_DONE) && OpId != OP_GS_NOP;
1403 }
1404 
1405 void decodeMsg(unsigned Val,
1406                uint16_t &MsgId,
1407                uint16_t &OpId,
1408                uint16_t &StreamId) {
1409   MsgId = Val & ID_MASK_;
1410   OpId = (Val & OP_MASK_) >> OP_SHIFT_;
1411   StreamId = (Val & STREAM_ID_MASK_) >> STREAM_ID_SHIFT_;
1412 }
1413 
1414 uint64_t encodeMsg(uint64_t MsgId,
1415                    uint64_t OpId,
1416                    uint64_t StreamId) {
1417   return (MsgId << ID_SHIFT_) |
1418          (OpId << OP_SHIFT_) |
1419          (StreamId << STREAM_ID_SHIFT_);
1420 }
1421 
1422 } // namespace SendMsg
1423 
1424 //===----------------------------------------------------------------------===//
1425 //
1426 //===----------------------------------------------------------------------===//
1427 
1428 unsigned getInitialPSInputAddr(const Function &F) {
1429   return getIntegerAttribute(F, "InitialPSInputAddr", 0);
1430 }
1431 
1432 bool getHasColorExport(const Function &F) {
1433   // As a safe default always respond as if PS has color exports.
1434   return getIntegerAttribute(
1435              F, "amdgpu-color-export",
1436              F.getCallingConv() == CallingConv::AMDGPU_PS ? 1 : 0) != 0;
1437 }
1438 
1439 bool getHasDepthExport(const Function &F) {
1440   return getIntegerAttribute(F, "amdgpu-depth-export", 0) != 0;
1441 }
1442 
1443 bool isShader(CallingConv::ID cc) {
1444   switch(cc) {
1445     case CallingConv::AMDGPU_VS:
1446     case CallingConv::AMDGPU_LS:
1447     case CallingConv::AMDGPU_HS:
1448     case CallingConv::AMDGPU_ES:
1449     case CallingConv::AMDGPU_GS:
1450     case CallingConv::AMDGPU_PS:
1451     case CallingConv::AMDGPU_CS:
1452       return true;
1453     default:
1454       return false;
1455   }
1456 }
1457 
1458 bool isGraphics(CallingConv::ID cc) {
1459   return isShader(cc) || cc == CallingConv::AMDGPU_Gfx;
1460 }
1461 
1462 bool isCompute(CallingConv::ID cc) {
1463   return !isGraphics(cc) || cc == CallingConv::AMDGPU_CS;
1464 }
1465 
1466 bool isEntryFunctionCC(CallingConv::ID CC) {
1467   switch (CC) {
1468   case CallingConv::AMDGPU_KERNEL:
1469   case CallingConv::SPIR_KERNEL:
1470   case CallingConv::AMDGPU_VS:
1471   case CallingConv::AMDGPU_GS:
1472   case CallingConv::AMDGPU_PS:
1473   case CallingConv::AMDGPU_CS:
1474   case CallingConv::AMDGPU_ES:
1475   case CallingConv::AMDGPU_HS:
1476   case CallingConv::AMDGPU_LS:
1477     return true;
1478   default:
1479     return false;
1480   }
1481 }
1482 
1483 bool isModuleEntryFunctionCC(CallingConv::ID CC) {
1484   switch (CC) {
1485   case CallingConv::AMDGPU_Gfx:
1486     return true;
1487   default:
1488     return isEntryFunctionCC(CC);
1489   }
1490 }
1491 
1492 bool isKernelCC(const Function *Func) {
1493   return AMDGPU::isModuleEntryFunctionCC(Func->getCallingConv());
1494 }
1495 
1496 bool hasXNACK(const MCSubtargetInfo &STI) {
1497   return STI.getFeatureBits()[AMDGPU::FeatureXNACK];
1498 }
1499 
1500 bool hasSRAMECC(const MCSubtargetInfo &STI) {
1501   return STI.getFeatureBits()[AMDGPU::FeatureSRAMECC];
1502 }
1503 
1504 bool hasMIMG_R128(const MCSubtargetInfo &STI) {
1505   return STI.getFeatureBits()[AMDGPU::FeatureMIMG_R128] && !STI.getFeatureBits()[AMDGPU::FeatureR128A16];
1506 }
1507 
1508 bool hasGFX10A16(const MCSubtargetInfo &STI) {
1509   return STI.getFeatureBits()[AMDGPU::FeatureGFX10A16];
1510 }
1511 
1512 bool hasG16(const MCSubtargetInfo &STI) {
1513   return STI.getFeatureBits()[AMDGPU::FeatureG16];
1514 }
1515 
1516 bool hasPackedD16(const MCSubtargetInfo &STI) {
1517   return !STI.getFeatureBits()[AMDGPU::FeatureUnpackedD16VMem];
1518 }
1519 
1520 bool isSI(const MCSubtargetInfo &STI) {
1521   return STI.getFeatureBits()[AMDGPU::FeatureSouthernIslands];
1522 }
1523 
1524 bool isCI(const MCSubtargetInfo &STI) {
1525   return STI.getFeatureBits()[AMDGPU::FeatureSeaIslands];
1526 }
1527 
1528 bool isVI(const MCSubtargetInfo &STI) {
1529   return STI.getFeatureBits()[AMDGPU::FeatureVolcanicIslands];
1530 }
1531 
1532 bool isGFX9(const MCSubtargetInfo &STI) {
1533   return STI.getFeatureBits()[AMDGPU::FeatureGFX9];
1534 }
1535 
1536 bool isGFX9_GFX10(const MCSubtargetInfo &STI) {
1537   return isGFX9(STI) || isGFX10(STI);
1538 }
1539 
1540 bool isGFX9Plus(const MCSubtargetInfo &STI) {
1541   return isGFX9(STI) || isGFX10Plus(STI);
1542 }
1543 
1544 bool isGFX10(const MCSubtargetInfo &STI) {
1545   return STI.getFeatureBits()[AMDGPU::FeatureGFX10];
1546 }
1547 
1548 bool isGFX10Plus(const MCSubtargetInfo &STI) { return isGFX10(STI); }
1549 
1550 bool isGCN3Encoding(const MCSubtargetInfo &STI) {
1551   return STI.getFeatureBits()[AMDGPU::FeatureGCN3Encoding];
1552 }
1553 
1554 bool isGFX10_AEncoding(const MCSubtargetInfo &STI) {
1555   return STI.getFeatureBits()[AMDGPU::FeatureGFX10_AEncoding];
1556 }
1557 
1558 bool isGFX10_BEncoding(const MCSubtargetInfo &STI) {
1559   return STI.getFeatureBits()[AMDGPU::FeatureGFX10_BEncoding];
1560 }
1561 
1562 bool hasGFX10_3Insts(const MCSubtargetInfo &STI) {
1563   return STI.getFeatureBits()[AMDGPU::FeatureGFX10_3Insts];
1564 }
1565 
1566 bool isGFX90A(const MCSubtargetInfo &STI) {
1567   return STI.getFeatureBits()[AMDGPU::FeatureGFX90AInsts];
1568 }
1569 
1570 bool isGFX940(const MCSubtargetInfo &STI) {
1571   return STI.getFeatureBits()[AMDGPU::FeatureGFX940Insts];
1572 }
1573 
1574 bool hasArchitectedFlatScratch(const MCSubtargetInfo &STI) {
1575   return STI.getFeatureBits()[AMDGPU::FeatureArchitectedFlatScratch];
1576 }
1577 
1578 bool hasMAIInsts(const MCSubtargetInfo &STI) {
1579   return STI.getFeatureBits()[AMDGPU::FeatureMAIInsts];
1580 }
1581 
1582 int32_t getTotalNumVGPRs(bool has90AInsts, int32_t ArgNumAGPR,
1583                          int32_t ArgNumVGPR) {
1584   if (has90AInsts && ArgNumAGPR)
1585     return alignTo(ArgNumVGPR, 4) + ArgNumAGPR;
1586   return std::max(ArgNumVGPR, ArgNumAGPR);
1587 }
1588 
1589 bool isSGPR(unsigned Reg, const MCRegisterInfo* TRI) {
1590   const MCRegisterClass SGPRClass = TRI->getRegClass(AMDGPU::SReg_32RegClassID);
1591   const unsigned FirstSubReg = TRI->getSubReg(Reg, AMDGPU::sub0);
1592   return SGPRClass.contains(FirstSubReg != 0 ? FirstSubReg : Reg) ||
1593     Reg == AMDGPU::SCC;
1594 }
1595 
1596 #define MAP_REG2REG \
1597   using namespace AMDGPU; \
1598   switch(Reg) { \
1599   default: return Reg; \
1600   CASE_CI_VI(FLAT_SCR) \
1601   CASE_CI_VI(FLAT_SCR_LO) \
1602   CASE_CI_VI(FLAT_SCR_HI) \
1603   CASE_VI_GFX9PLUS(TTMP0) \
1604   CASE_VI_GFX9PLUS(TTMP1) \
1605   CASE_VI_GFX9PLUS(TTMP2) \
1606   CASE_VI_GFX9PLUS(TTMP3) \
1607   CASE_VI_GFX9PLUS(TTMP4) \
1608   CASE_VI_GFX9PLUS(TTMP5) \
1609   CASE_VI_GFX9PLUS(TTMP6) \
1610   CASE_VI_GFX9PLUS(TTMP7) \
1611   CASE_VI_GFX9PLUS(TTMP8) \
1612   CASE_VI_GFX9PLUS(TTMP9) \
1613   CASE_VI_GFX9PLUS(TTMP10) \
1614   CASE_VI_GFX9PLUS(TTMP11) \
1615   CASE_VI_GFX9PLUS(TTMP12) \
1616   CASE_VI_GFX9PLUS(TTMP13) \
1617   CASE_VI_GFX9PLUS(TTMP14) \
1618   CASE_VI_GFX9PLUS(TTMP15) \
1619   CASE_VI_GFX9PLUS(TTMP0_TTMP1) \
1620   CASE_VI_GFX9PLUS(TTMP2_TTMP3) \
1621   CASE_VI_GFX9PLUS(TTMP4_TTMP5) \
1622   CASE_VI_GFX9PLUS(TTMP6_TTMP7) \
1623   CASE_VI_GFX9PLUS(TTMP8_TTMP9) \
1624   CASE_VI_GFX9PLUS(TTMP10_TTMP11) \
1625   CASE_VI_GFX9PLUS(TTMP12_TTMP13) \
1626   CASE_VI_GFX9PLUS(TTMP14_TTMP15) \
1627   CASE_VI_GFX9PLUS(TTMP0_TTMP1_TTMP2_TTMP3) \
1628   CASE_VI_GFX9PLUS(TTMP4_TTMP5_TTMP6_TTMP7) \
1629   CASE_VI_GFX9PLUS(TTMP8_TTMP9_TTMP10_TTMP11) \
1630   CASE_VI_GFX9PLUS(TTMP12_TTMP13_TTMP14_TTMP15) \
1631   CASE_VI_GFX9PLUS(TTMP0_TTMP1_TTMP2_TTMP3_TTMP4_TTMP5_TTMP6_TTMP7) \
1632   CASE_VI_GFX9PLUS(TTMP4_TTMP5_TTMP6_TTMP7_TTMP8_TTMP9_TTMP10_TTMP11) \
1633   CASE_VI_GFX9PLUS(TTMP8_TTMP9_TTMP10_TTMP11_TTMP12_TTMP13_TTMP14_TTMP15) \
1634   CASE_VI_GFX9PLUS(TTMP0_TTMP1_TTMP2_TTMP3_TTMP4_TTMP5_TTMP6_TTMP7_TTMP8_TTMP9_TTMP10_TTMP11_TTMP12_TTMP13_TTMP14_TTMP15) \
1635   }
1636 
1637 #define CASE_CI_VI(node) \
1638   assert(!isSI(STI)); \
1639   case node: return isCI(STI) ? node##_ci : node##_vi;
1640 
1641 #define CASE_VI_GFX9PLUS(node) \
1642   case node: return isGFX9Plus(STI) ? node##_gfx9plus : node##_vi;
1643 
1644 unsigned getMCReg(unsigned Reg, const MCSubtargetInfo &STI) {
1645   if (STI.getTargetTriple().getArch() == Triple::r600)
1646     return Reg;
1647   MAP_REG2REG
1648 }
1649 
1650 #undef CASE_CI_VI
1651 #undef CASE_VI_GFX9PLUS
1652 
1653 #define CASE_CI_VI(node)   case node##_ci: case node##_vi:   return node;
1654 #define CASE_VI_GFX9PLUS(node) case node##_vi: case node##_gfx9plus: return node;
1655 
1656 unsigned mc2PseudoReg(unsigned Reg) {
1657   MAP_REG2REG
1658 }
1659 
1660 #undef CASE_CI_VI
1661 #undef CASE_VI_GFX9PLUS
1662 #undef MAP_REG2REG
1663 
1664 bool isSISrcOperand(const MCInstrDesc &Desc, unsigned OpNo) {
1665   assert(OpNo < Desc.NumOperands);
1666   unsigned OpType = Desc.OpInfo[OpNo].OperandType;
1667   return OpType >= AMDGPU::OPERAND_SRC_FIRST &&
1668          OpType <= AMDGPU::OPERAND_SRC_LAST;
1669 }
1670 
1671 bool isSISrcFPOperand(const MCInstrDesc &Desc, unsigned OpNo) {
1672   assert(OpNo < Desc.NumOperands);
1673   unsigned OpType = Desc.OpInfo[OpNo].OperandType;
1674   switch (OpType) {
1675   case AMDGPU::OPERAND_REG_IMM_FP32:
1676   case AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED:
1677   case AMDGPU::OPERAND_REG_IMM_FP64:
1678   case AMDGPU::OPERAND_REG_IMM_FP16:
1679   case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED:
1680   case AMDGPU::OPERAND_REG_IMM_V2FP16:
1681   case AMDGPU::OPERAND_REG_IMM_V2INT16:
1682   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
1683   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
1684   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
1685   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
1686   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
1687   case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
1688   case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
1689   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16:
1690   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
1691   case AMDGPU::OPERAND_REG_IMM_V2FP32:
1692   case AMDGPU::OPERAND_REG_INLINE_C_V2FP32:
1693   case AMDGPU::OPERAND_REG_INLINE_AC_FP64:
1694     return true;
1695   default:
1696     return false;
1697   }
1698 }
1699 
1700 bool isSISrcInlinableOperand(const MCInstrDesc &Desc, unsigned OpNo) {
1701   assert(OpNo < Desc.NumOperands);
1702   unsigned OpType = Desc.OpInfo[OpNo].OperandType;
1703   return OpType >= AMDGPU::OPERAND_REG_INLINE_C_FIRST &&
1704          OpType <= AMDGPU::OPERAND_REG_INLINE_C_LAST;
1705 }
1706 
1707 // Avoid using MCRegisterClass::getSize, since that function will go away
1708 // (move from MC* level to Target* level). Return size in bits.
1709 unsigned getRegBitWidth(unsigned RCID) {
1710   switch (RCID) {
1711   case AMDGPU::VGPR_LO16RegClassID:
1712   case AMDGPU::VGPR_HI16RegClassID:
1713   case AMDGPU::SGPR_LO16RegClassID:
1714   case AMDGPU::AGPR_LO16RegClassID:
1715     return 16;
1716   case AMDGPU::SGPR_32RegClassID:
1717   case AMDGPU::VGPR_32RegClassID:
1718   case AMDGPU::VRegOrLds_32RegClassID:
1719   case AMDGPU::AGPR_32RegClassID:
1720   case AMDGPU::VS_32RegClassID:
1721   case AMDGPU::AV_32RegClassID:
1722   case AMDGPU::SReg_32RegClassID:
1723   case AMDGPU::SReg_32_XM0RegClassID:
1724   case AMDGPU::SRegOrLds_32RegClassID:
1725     return 32;
1726   case AMDGPU::SGPR_64RegClassID:
1727   case AMDGPU::VS_64RegClassID:
1728   case AMDGPU::SReg_64RegClassID:
1729   case AMDGPU::VReg_64RegClassID:
1730   case AMDGPU::AReg_64RegClassID:
1731   case AMDGPU::SReg_64_XEXECRegClassID:
1732   case AMDGPU::VReg_64_Align2RegClassID:
1733   case AMDGPU::AReg_64_Align2RegClassID:
1734   case AMDGPU::AV_64RegClassID:
1735   case AMDGPU::AV_64_Align2RegClassID:
1736     return 64;
1737   case AMDGPU::SGPR_96RegClassID:
1738   case AMDGPU::SReg_96RegClassID:
1739   case AMDGPU::VReg_96RegClassID:
1740   case AMDGPU::AReg_96RegClassID:
1741   case AMDGPU::VReg_96_Align2RegClassID:
1742   case AMDGPU::AReg_96_Align2RegClassID:
1743   case AMDGPU::AV_96RegClassID:
1744   case AMDGPU::AV_96_Align2RegClassID:
1745     return 96;
1746   case AMDGPU::SGPR_128RegClassID:
1747   case AMDGPU::SReg_128RegClassID:
1748   case AMDGPU::VReg_128RegClassID:
1749   case AMDGPU::AReg_128RegClassID:
1750   case AMDGPU::VReg_128_Align2RegClassID:
1751   case AMDGPU::AReg_128_Align2RegClassID:
1752   case AMDGPU::AV_128RegClassID:
1753   case AMDGPU::AV_128_Align2RegClassID:
1754     return 128;
1755   case AMDGPU::SGPR_160RegClassID:
1756   case AMDGPU::SReg_160RegClassID:
1757   case AMDGPU::VReg_160RegClassID:
1758   case AMDGPU::AReg_160RegClassID:
1759   case AMDGPU::VReg_160_Align2RegClassID:
1760   case AMDGPU::AReg_160_Align2RegClassID:
1761   case AMDGPU::AV_160RegClassID:
1762   case AMDGPU::AV_160_Align2RegClassID:
1763     return 160;
1764   case AMDGPU::SGPR_192RegClassID:
1765   case AMDGPU::SReg_192RegClassID:
1766   case AMDGPU::VReg_192RegClassID:
1767   case AMDGPU::AReg_192RegClassID:
1768   case AMDGPU::VReg_192_Align2RegClassID:
1769   case AMDGPU::AReg_192_Align2RegClassID:
1770   case AMDGPU::AV_192RegClassID:
1771   case AMDGPU::AV_192_Align2RegClassID:
1772     return 192;
1773   case AMDGPU::SGPR_224RegClassID:
1774   case AMDGPU::SReg_224RegClassID:
1775   case AMDGPU::VReg_224RegClassID:
1776   case AMDGPU::AReg_224RegClassID:
1777   case AMDGPU::VReg_224_Align2RegClassID:
1778   case AMDGPU::AReg_224_Align2RegClassID:
1779   case AMDGPU::AV_224RegClassID:
1780   case AMDGPU::AV_224_Align2RegClassID:
1781     return 224;
1782   case AMDGPU::SGPR_256RegClassID:
1783   case AMDGPU::SReg_256RegClassID:
1784   case AMDGPU::VReg_256RegClassID:
1785   case AMDGPU::AReg_256RegClassID:
1786   case AMDGPU::VReg_256_Align2RegClassID:
1787   case AMDGPU::AReg_256_Align2RegClassID:
1788   case AMDGPU::AV_256RegClassID:
1789   case AMDGPU::AV_256_Align2RegClassID:
1790     return 256;
1791   case AMDGPU::SGPR_512RegClassID:
1792   case AMDGPU::SReg_512RegClassID:
1793   case AMDGPU::VReg_512RegClassID:
1794   case AMDGPU::AReg_512RegClassID:
1795   case AMDGPU::VReg_512_Align2RegClassID:
1796   case AMDGPU::AReg_512_Align2RegClassID:
1797   case AMDGPU::AV_512RegClassID:
1798   case AMDGPU::AV_512_Align2RegClassID:
1799     return 512;
1800   case AMDGPU::SGPR_1024RegClassID:
1801   case AMDGPU::SReg_1024RegClassID:
1802   case AMDGPU::VReg_1024RegClassID:
1803   case AMDGPU::AReg_1024RegClassID:
1804   case AMDGPU::VReg_1024_Align2RegClassID:
1805   case AMDGPU::AReg_1024_Align2RegClassID:
1806   case AMDGPU::AV_1024RegClassID:
1807   case AMDGPU::AV_1024_Align2RegClassID:
1808     return 1024;
1809   default:
1810     llvm_unreachable("Unexpected register class");
1811   }
1812 }
1813 
1814 unsigned getRegBitWidth(const MCRegisterClass &RC) {
1815   return getRegBitWidth(RC.getID());
1816 }
1817 
1818 unsigned getRegOperandSize(const MCRegisterInfo *MRI, const MCInstrDesc &Desc,
1819                            unsigned OpNo) {
1820   assert(OpNo < Desc.NumOperands);
1821   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1822   return getRegBitWidth(MRI->getRegClass(RCID)) / 8;
1823 }
1824 
1825 bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi) {
1826   if (isInlinableIntLiteral(Literal))
1827     return true;
1828 
1829   uint64_t Val = static_cast<uint64_t>(Literal);
1830   return (Val == DoubleToBits(0.0)) ||
1831          (Val == DoubleToBits(1.0)) ||
1832          (Val == DoubleToBits(-1.0)) ||
1833          (Val == DoubleToBits(0.5)) ||
1834          (Val == DoubleToBits(-0.5)) ||
1835          (Val == DoubleToBits(2.0)) ||
1836          (Val == DoubleToBits(-2.0)) ||
1837          (Val == DoubleToBits(4.0)) ||
1838          (Val == DoubleToBits(-4.0)) ||
1839          (Val == 0x3fc45f306dc9c882 && HasInv2Pi);
1840 }
1841 
1842 bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi) {
1843   if (isInlinableIntLiteral(Literal))
1844     return true;
1845 
1846   // The actual type of the operand does not seem to matter as long
1847   // as the bits match one of the inline immediate values.  For example:
1848   //
1849   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
1850   // so it is a legal inline immediate.
1851   //
1852   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
1853   // floating-point, so it is a legal inline immediate.
1854 
1855   uint32_t Val = static_cast<uint32_t>(Literal);
1856   return (Val == FloatToBits(0.0f)) ||
1857          (Val == FloatToBits(1.0f)) ||
1858          (Val == FloatToBits(-1.0f)) ||
1859          (Val == FloatToBits(0.5f)) ||
1860          (Val == FloatToBits(-0.5f)) ||
1861          (Val == FloatToBits(2.0f)) ||
1862          (Val == FloatToBits(-2.0f)) ||
1863          (Val == FloatToBits(4.0f)) ||
1864          (Val == FloatToBits(-4.0f)) ||
1865          (Val == 0x3e22f983 && HasInv2Pi);
1866 }
1867 
1868 bool isInlinableLiteral16(int16_t Literal, bool HasInv2Pi) {
1869   if (!HasInv2Pi)
1870     return false;
1871 
1872   if (isInlinableIntLiteral(Literal))
1873     return true;
1874 
1875   uint16_t Val = static_cast<uint16_t>(Literal);
1876   return Val == 0x3C00 || // 1.0
1877          Val == 0xBC00 || // -1.0
1878          Val == 0x3800 || // 0.5
1879          Val == 0xB800 || // -0.5
1880          Val == 0x4000 || // 2.0
1881          Val == 0xC000 || // -2.0
1882          Val == 0x4400 || // 4.0
1883          Val == 0xC400 || // -4.0
1884          Val == 0x3118;   // 1/2pi
1885 }
1886 
1887 bool isInlinableLiteralV216(int32_t Literal, bool HasInv2Pi) {
1888   assert(HasInv2Pi);
1889 
1890   if (isInt<16>(Literal) || isUInt<16>(Literal)) {
1891     int16_t Trunc = static_cast<int16_t>(Literal);
1892     return AMDGPU::isInlinableLiteral16(Trunc, HasInv2Pi);
1893   }
1894   if (!(Literal & 0xffff))
1895     return AMDGPU::isInlinableLiteral16(Literal >> 16, HasInv2Pi);
1896 
1897   int16_t Lo16 = static_cast<int16_t>(Literal);
1898   int16_t Hi16 = static_cast<int16_t>(Literal >> 16);
1899   return Lo16 == Hi16 && isInlinableLiteral16(Lo16, HasInv2Pi);
1900 }
1901 
1902 bool isInlinableIntLiteralV216(int32_t Literal) {
1903   int16_t Lo16 = static_cast<int16_t>(Literal);
1904   if (isInt<16>(Literal) || isUInt<16>(Literal))
1905     return isInlinableIntLiteral(Lo16);
1906 
1907   int16_t Hi16 = static_cast<int16_t>(Literal >> 16);
1908   if (!(Literal & 0xffff))
1909     return isInlinableIntLiteral(Hi16);
1910   return Lo16 == Hi16 && isInlinableIntLiteral(Lo16);
1911 }
1912 
1913 bool isFoldableLiteralV216(int32_t Literal, bool HasInv2Pi) {
1914   assert(HasInv2Pi);
1915 
1916   int16_t Lo16 = static_cast<int16_t>(Literal);
1917   if (isInt<16>(Literal) || isUInt<16>(Literal))
1918     return true;
1919 
1920   int16_t Hi16 = static_cast<int16_t>(Literal >> 16);
1921   if (!(Literal & 0xffff))
1922     return true;
1923   return Lo16 == Hi16;
1924 }
1925 
1926 bool isArgPassedInSGPR(const Argument *A) {
1927   const Function *F = A->getParent();
1928 
1929   // Arguments to compute shaders are never a source of divergence.
1930   CallingConv::ID CC = F->getCallingConv();
1931   switch (CC) {
1932   case CallingConv::AMDGPU_KERNEL:
1933   case CallingConv::SPIR_KERNEL:
1934     return true;
1935   case CallingConv::AMDGPU_VS:
1936   case CallingConv::AMDGPU_LS:
1937   case CallingConv::AMDGPU_HS:
1938   case CallingConv::AMDGPU_ES:
1939   case CallingConv::AMDGPU_GS:
1940   case CallingConv::AMDGPU_PS:
1941   case CallingConv::AMDGPU_CS:
1942   case CallingConv::AMDGPU_Gfx:
1943     // For non-compute shaders, SGPR inputs are marked with either inreg or byval.
1944     // Everything else is in VGPRs.
1945     return F->getAttributes().hasParamAttr(A->getArgNo(), Attribute::InReg) ||
1946            F->getAttributes().hasParamAttr(A->getArgNo(), Attribute::ByVal);
1947   default:
1948     // TODO: Should calls support inreg for SGPR inputs?
1949     return false;
1950   }
1951 }
1952 
1953 static bool hasSMEMByteOffset(const MCSubtargetInfo &ST) {
1954   return isGCN3Encoding(ST) || isGFX10Plus(ST);
1955 }
1956 
1957 static bool hasSMRDSignedImmOffset(const MCSubtargetInfo &ST) {
1958   return isGFX9Plus(ST);
1959 }
1960 
1961 bool isLegalSMRDEncodedUnsignedOffset(const MCSubtargetInfo &ST,
1962                                       int64_t EncodedOffset) {
1963   return hasSMEMByteOffset(ST) ? isUInt<20>(EncodedOffset)
1964                                : isUInt<8>(EncodedOffset);
1965 }
1966 
1967 bool isLegalSMRDEncodedSignedOffset(const MCSubtargetInfo &ST,
1968                                     int64_t EncodedOffset,
1969                                     bool IsBuffer) {
1970   return !IsBuffer &&
1971          hasSMRDSignedImmOffset(ST) &&
1972          isInt<21>(EncodedOffset);
1973 }
1974 
1975 static bool isDwordAligned(uint64_t ByteOffset) {
1976   return (ByteOffset & 3) == 0;
1977 }
1978 
1979 uint64_t convertSMRDOffsetUnits(const MCSubtargetInfo &ST,
1980                                 uint64_t ByteOffset) {
1981   if (hasSMEMByteOffset(ST))
1982     return ByteOffset;
1983 
1984   assert(isDwordAligned(ByteOffset));
1985   return ByteOffset >> 2;
1986 }
1987 
1988 Optional<int64_t> getSMRDEncodedOffset(const MCSubtargetInfo &ST,
1989                                        int64_t ByteOffset, bool IsBuffer) {
1990   // The signed version is always a byte offset.
1991   if (!IsBuffer && hasSMRDSignedImmOffset(ST)) {
1992     assert(hasSMEMByteOffset(ST));
1993     return isInt<20>(ByteOffset) ? Optional<int64_t>(ByteOffset) : None;
1994   }
1995 
1996   if (!isDwordAligned(ByteOffset) && !hasSMEMByteOffset(ST))
1997     return None;
1998 
1999   int64_t EncodedOffset = convertSMRDOffsetUnits(ST, ByteOffset);
2000   return isLegalSMRDEncodedUnsignedOffset(ST, EncodedOffset)
2001              ? Optional<int64_t>(EncodedOffset)
2002              : None;
2003 }
2004 
2005 Optional<int64_t> getSMRDEncodedLiteralOffset32(const MCSubtargetInfo &ST,
2006                                                 int64_t ByteOffset) {
2007   if (!isCI(ST) || !isDwordAligned(ByteOffset))
2008     return None;
2009 
2010   int64_t EncodedOffset = convertSMRDOffsetUnits(ST, ByteOffset);
2011   return isUInt<32>(EncodedOffset) ? Optional<int64_t>(EncodedOffset) : None;
2012 }
2013 
2014 unsigned getNumFlatOffsetBits(const MCSubtargetInfo &ST, bool Signed) {
2015   // Address offset is 12-bit signed for GFX10, 13-bit for GFX9.
2016   if (AMDGPU::isGFX10(ST))
2017     return Signed ? 12 : 11;
2018 
2019   return Signed ? 13 : 12;
2020 }
2021 
2022 // Given Imm, split it into the values to put into the SOffset and ImmOffset
2023 // fields in an MUBUF instruction. Return false if it is not possible (due to a
2024 // hardware bug needing a workaround).
2025 //
2026 // The required alignment ensures that individual address components remain
2027 // aligned if they are aligned to begin with. It also ensures that additional
2028 // offsets within the given alignment can be added to the resulting ImmOffset.
2029 bool splitMUBUFOffset(uint32_t Imm, uint32_t &SOffset, uint32_t &ImmOffset,
2030                       const GCNSubtarget *Subtarget, Align Alignment) {
2031   const uint32_t MaxImm = alignDown(4095, Alignment.value());
2032   uint32_t Overflow = 0;
2033 
2034   if (Imm > MaxImm) {
2035     if (Imm <= MaxImm + 64) {
2036       // Use an SOffset inline constant for 4..64
2037       Overflow = Imm - MaxImm;
2038       Imm = MaxImm;
2039     } else {
2040       // Try to keep the same value in SOffset for adjacent loads, so that
2041       // the corresponding register contents can be re-used.
2042       //
2043       // Load values with all low-bits (except for alignment bits) set into
2044       // SOffset, so that a larger range of values can be covered using
2045       // s_movk_i32.
2046       //
2047       // Atomic operations fail to work correctly when individual address
2048       // components are unaligned, even if their sum is aligned.
2049       uint32_t High = (Imm + Alignment.value()) & ~4095;
2050       uint32_t Low = (Imm + Alignment.value()) & 4095;
2051       Imm = Low;
2052       Overflow = High - Alignment.value();
2053     }
2054   }
2055 
2056   // There is a hardware bug in SI and CI which prevents address clamping in
2057   // MUBUF instructions from working correctly with SOffsets. The immediate
2058   // offset is unaffected.
2059   if (Overflow > 0 &&
2060       Subtarget->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
2061     return false;
2062 
2063   ImmOffset = Imm;
2064   SOffset = Overflow;
2065   return true;
2066 }
2067 
2068 SIModeRegisterDefaults::SIModeRegisterDefaults(const Function &F) {
2069   *this = getDefaultForCallingConv(F.getCallingConv());
2070 
2071   StringRef IEEEAttr = F.getFnAttribute("amdgpu-ieee").getValueAsString();
2072   if (!IEEEAttr.empty())
2073     IEEE = IEEEAttr == "true";
2074 
2075   StringRef DX10ClampAttr
2076     = F.getFnAttribute("amdgpu-dx10-clamp").getValueAsString();
2077   if (!DX10ClampAttr.empty())
2078     DX10Clamp = DX10ClampAttr == "true";
2079 
2080   StringRef DenormF32Attr = F.getFnAttribute("denormal-fp-math-f32").getValueAsString();
2081   if (!DenormF32Attr.empty()) {
2082     DenormalMode DenormMode = parseDenormalFPAttribute(DenormF32Attr);
2083     FP32InputDenormals = DenormMode.Input == DenormalMode::IEEE;
2084     FP32OutputDenormals = DenormMode.Output == DenormalMode::IEEE;
2085   }
2086 
2087   StringRef DenormAttr = F.getFnAttribute("denormal-fp-math").getValueAsString();
2088   if (!DenormAttr.empty()) {
2089     DenormalMode DenormMode = parseDenormalFPAttribute(DenormAttr);
2090 
2091     if (DenormF32Attr.empty()) {
2092       FP32InputDenormals = DenormMode.Input == DenormalMode::IEEE;
2093       FP32OutputDenormals = DenormMode.Output == DenormalMode::IEEE;
2094     }
2095 
2096     FP64FP16InputDenormals = DenormMode.Input == DenormalMode::IEEE;
2097     FP64FP16OutputDenormals = DenormMode.Output == DenormalMode::IEEE;
2098   }
2099 }
2100 
2101 namespace {
2102 
2103 struct SourceOfDivergence {
2104   unsigned Intr;
2105 };
2106 const SourceOfDivergence *lookupSourceOfDivergence(unsigned Intr);
2107 
2108 #define GET_SourcesOfDivergence_IMPL
2109 #define GET_Gfx9BufferFormat_IMPL
2110 #define GET_Gfx10PlusBufferFormat_IMPL
2111 #include "AMDGPUGenSearchableTables.inc"
2112 
2113 } // end anonymous namespace
2114 
2115 bool isIntrinsicSourceOfDivergence(unsigned IntrID) {
2116   return lookupSourceOfDivergence(IntrID);
2117 }
2118 
2119 const GcnBufferFormatInfo *getGcnBufferFormatInfo(uint8_t BitsPerComp,
2120                                                   uint8_t NumComponents,
2121                                                   uint8_t NumFormat,
2122                                                   const MCSubtargetInfo &STI) {
2123   return isGFX10Plus(STI)
2124              ? getGfx10PlusBufferFormatInfo(BitsPerComp, NumComponents,
2125                                             NumFormat)
2126              : getGfx9BufferFormatInfo(BitsPerComp, NumComponents, NumFormat);
2127 }
2128 
2129 const GcnBufferFormatInfo *getGcnBufferFormatInfo(uint8_t Format,
2130                                                   const MCSubtargetInfo &STI) {
2131   return isGFX10Plus(STI) ? getGfx10PlusBufferFormatInfo(Format)
2132                           : getGfx9BufferFormatInfo(Format);
2133 }
2134 
2135 } // namespace AMDGPU
2136 
2137 raw_ostream &operator<<(raw_ostream &OS,
2138                         const AMDGPU::IsaInfo::TargetIDSetting S) {
2139   switch (S) {
2140   case (AMDGPU::IsaInfo::TargetIDSetting::Unsupported):
2141     OS << "Unsupported";
2142     break;
2143   case (AMDGPU::IsaInfo::TargetIDSetting::Any):
2144     OS << "Any";
2145     break;
2146   case (AMDGPU::IsaInfo::TargetIDSetting::Off):
2147     OS << "Off";
2148     break;
2149   case (AMDGPU::IsaInfo::TargetIDSetting::On):
2150     OS << "On";
2151     break;
2152   }
2153   return OS;
2154 }
2155 
2156 } // namespace llvm
2157