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