1//===--- SPIRVUtils.h ---- SPIR-V Utility Functions -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains miscellaneous utility functions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_TARGET_SPIRV_SPIRVUTILS_H
14#define LLVM_LIB_TARGET_SPIRV_SPIRVUTILS_H
15
16#include "MCTargetDesc/SPIRVBaseInfo.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/TypedPointerType.h"
26#include <queue>
27#include <set>
28#include <string>
29
30#include "SPIRVTypeInst.h"
31
32namespace llvm {
33class MCInst;
34class MachineFunction;
35class MachineInstrBuilder;
36class MachineIRBuilder;
37class MachineRegisterInfo;
38class Register;
39class StringRef;
40class SPIRVInstrInfo;
41class SPIRVSubtarget;
42class SPIRVGlobalRegistry;
43
44// This class implements a partial ordering visitor, which visits a cyclic graph
45// in natural topological-like ordering. Topological ordering is not defined for
46// directed graphs with cycles, so this assumes cycles are a single node, and
47// ignores back-edges. The cycle is visited from the entry in the same
48// topological-like ordering.
49//
50// Note: this visitor REQUIRES a reducible graph.
51//
52// This means once we visit a node, we know all the possible ancestors have been
53// visited.
54//
55// clang-format off
56//
57// Given this graph:
58//
59// ,-> B -\
60// A -+ +---> D ----> E -> F -> G -> H
61// `-> C -/ ^ |
62// +-----------------+
63//
64// Visit order is:
65// A, [B, C in any order], D, E, F, G, H
66//
67// clang-format on
68//
69// Changing the function CFG between the construction of the visitor and
70// visiting is undefined. The visitor can be reused, but if the CFG is updated,
71// the visitor must be rebuilt.
72class PartialOrderingVisitor {
73 DomTreeBuilder::BBDomTree DT;
74 LoopInfo LI;
75
76 SmallPtrSet<BasicBlock *, 0> Queued;
77 std::queue<BasicBlock *> ToVisit;
78
79 struct OrderInfo {
80 size_t Rank;
81 size_t TraversalIndex;
82 };
83
84 using BlockToOrderInfoMap = DenseMap<BasicBlock *, OrderInfo>;
85 BlockToOrderInfoMap BlockToOrder;
86 std::vector<BasicBlock *> Order;
87
88 // Get all basic-blocks reachable from Start.
89 SmallPtrSet<BasicBlock *, 0> getReachableFrom(BasicBlock *Start);
90
91 // Internal function used to determine the partial ordering.
92 // Visits |BB| with the current rank being |Rank|.
93 size_t visit(BasicBlock *BB, size_t Rank);
94
95 bool CanBeVisited(BasicBlock *BB) const;
96
97public:
98 size_t GetNodeRank(BasicBlock *BB) const;
99
100 // Build the visitor to operate on the function F.
101 PartialOrderingVisitor(Function &F);
102
103 // Returns true is |LHS| comes before |RHS| in the partial ordering.
104 // If |LHS| and |RHS| have the same rank, the traversal order determines the
105 // order (order is stable).
106 bool compare(const BasicBlock *LHS, const BasicBlock *RHS) const;
107
108 // Visit the function starting from the basic block |Start|, and calling |Op|
109 // on each visited BB. This traversal ignores back-edges, meaning this won't
110 // visit a node to which |Start| is not an ancestor.
111 // If Op returns |true|, the visitor continues. If |Op| returns false, the
112 // visitor will stop at that rank. This means if 2 nodes share the same rank,
113 // and Op returns false when visiting the first, the second will be visited
114 // afterwards. But none of their successors will.
115 void partialOrderVisit(BasicBlock &Start,
116 std::function<bool(BasicBlock *)> Op);
117};
118
119namespace SPIRV {
120struct FPFastMathDefaultInfo {
121 const Type *Ty = nullptr;
122 unsigned FastMathFlags = 0;
123 // When SPV_KHR_float_controls2 ContractionOff and SignzeroInfNanPreserve are
124 // deprecated, and we replace them with FPFastMathDefault appropriate flags
125 // instead. However, we have no guarantee about the order in which we will
126 // process execution modes. Therefore it could happen that we first process
127 // ContractionOff, setting AllowContraction bit to 0, and then we process
128 // FPFastMathDefault enabling AllowContraction bit, effectively invalidating
129 // ContractionOff. Because of that, it's best to keep separate bits for the
130 // different execution modes, and we will try and combine them later when we
131 // emit OpExecutionMode instructions.
132 bool ContractionOff = false;
133 bool SignedZeroInfNanPreserve = false;
134 bool FPFastMathDefault = false;
135
136 FPFastMathDefaultInfo() = default;
137 FPFastMathDefaultInfo(const Type *Ty, unsigned FastMathFlags)
138 : Ty(Ty), FastMathFlags(FastMathFlags) {}
139 bool operator==(const FPFastMathDefaultInfo &Other) const {
140 return Ty == Other.Ty && FastMathFlags == Other.FastMathFlags &&
141 ContractionOff == Other.ContractionOff &&
142 SignedZeroInfNanPreserve == Other.SignedZeroInfNanPreserve &&
143 FPFastMathDefault == Other.FPFastMathDefault;
144 }
145};
146
147struct FPFastMathDefaultInfoVector
148 : public SmallVector<SPIRV::FPFastMathDefaultInfo, 3> {
149 static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth) {
150 switch (BitWidth) {
151 case 16: // half
152 return 0;
153 case 32: // float
154 return 1;
155 case 64: // double
156 return 2;
157 default:
158 report_fatal_error(reason: "Expected BitWidth to be 16, 32, 64", gen_crash_diag: false);
159 }
160 llvm_unreachable(
161 "Unreachable code in computeFPFastMathDefaultInfoVecIndex");
162 }
163};
164
165// This code restores function args/retvalue types for composite cases
166// because the final types should still be aggregate whereas they're i32
167// during the translation to cope with aggregate flattening etc.
168FunctionType *getOriginalFunctionType(const Function &F);
169FunctionType *getOriginalFunctionType(const CallBase &CB);
170// This handles retrieving the original ASM constraints, which we had to spoof
171// into having a single output.
172StringRef getOriginalAsmConstraints(const CallBase &CB);
173} // namespace SPIRV
174
175// Add the given string as a series of integer operand, inserting null
176// terminators and padding to make sure the operands all have 32-bit
177// little-endian words.
178void addStringImm(StringRef Str, MCInst &Inst);
179void addStringImm(StringRef Str, MachineInstrBuilder &MIB);
180
181// Read the series of integer operands back as a null-terminated string using
182// the reverse of the logic in addStringImm.
183std::string getStringImm(const MachineInstr &MI, unsigned StartIndex);
184
185// Returns the string constant that the register refers to. It is assumed that
186// Reg is a global value that contains a string.
187std::string getStringValueFromReg(Register Reg, MachineRegisterInfo &MRI);
188
189// Add the given numerical immediate to MIB.
190void addNumImm(const APInt &Imm, MachineInstrBuilder &MIB);
191
192// Add an OpName instruction for the given target register.
193void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder);
194void buildOpName(Register Target, StringRef Name, MachineInstr &I,
195 const SPIRVInstrInfo &TII);
196
197// Add an OpDecorate instruction for the given Reg.
198void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder,
199 SPIRV::Decoration::Decoration Dec,
200 ArrayRef<uint32_t> DecArgs, StringRef StrImm = "");
201void buildOpDecorate(Register Reg, MachineInstr &I, const SPIRVInstrInfo &TII,
202 SPIRV::Decoration::Decoration Dec,
203 ArrayRef<uint32_t> DecArgs, StringRef StrImm = "");
204
205// Add an OpDecorate instruction for the given Reg.
206void buildOpMemberDecorate(Register Reg, MachineIRBuilder &MIRBuilder,
207 SPIRV::Decoration::Decoration Dec, uint32_t Member,
208 ArrayRef<uint32_t> DecArgs, StringRef StrImm = "");
209
210// Add an OpDecorate instruction by "spirv.Decorations" metadata node.
211void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder,
212 const MDNode *GVarMD, const SPIRVSubtarget &ST);
213
214// Return a valid position for the OpVariable instruction inside a function,
215// i.e., at the beginning of the first block of the function.
216MachineBasicBlock::iterator getOpVariableMBBIt(MachineFunction &MF);
217
218// Return a valid position for the instruction at the end of the block before
219// terminators and debug instructions.
220MachineBasicBlock::iterator getInsertPtValidEnd(MachineBasicBlock *MBB);
221
222// Returns true if a pointer to the storage class can be casted to/from a
223// pointer to the Generic storage class.
224constexpr bool isGenericCastablePtr(SPIRV::StorageClass::StorageClass SC) {
225 switch (SC) {
226 case SPIRV::StorageClass::Workgroup:
227 case SPIRV::StorageClass::CrossWorkgroup:
228 case SPIRV::StorageClass::Function:
229 case SPIRV::StorageClass::CodeSectionINTEL:
230 return true;
231 default:
232 return false;
233 }
234}
235
236// Convert a SPIR-V storage class to the corresponding LLVM IR address space.
237// TODO: maybe the following two functions should be handled in the subtarget
238// to allow for different OpenCL vs Vulkan handling.
239constexpr unsigned
240storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC) {
241 switch (SC) {
242 case SPIRV::StorageClass::Function:
243 return 0;
244 case SPIRV::StorageClass::CrossWorkgroup:
245 return 1;
246 case SPIRV::StorageClass::UniformConstant:
247 return 2;
248 case SPIRV::StorageClass::Workgroup:
249 return 3;
250 case SPIRV::StorageClass::Generic:
251 return 4;
252 case SPIRV::StorageClass::DeviceOnlyINTEL:
253 return 5;
254 case SPIRV::StorageClass::HostOnlyINTEL:
255 return 6;
256 case SPIRV::StorageClass::Input:
257 return 7;
258 case SPIRV::StorageClass::Output:
259 return 8;
260 case SPIRV::StorageClass::CodeSectionINTEL:
261 return 9;
262 case SPIRV::StorageClass::Private:
263 return 10;
264 case SPIRV::StorageClass::StorageBuffer:
265 return 11;
266 case SPIRV::StorageClass::Uniform:
267 return 12;
268 case SPIRV::StorageClass::PushConstant:
269 return 13;
270 default:
271 report_fatal_error(reason: "Unable to get address space id");
272 }
273}
274
275// Convert an LLVM IR address space to a SPIR-V storage class.
276SPIRV::StorageClass::StorageClass
277addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI);
278
279SPIRV::MemorySemantics::MemorySemantics
280getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC);
281
282SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord);
283
284SPIRV::Scope::Scope getMemScope(LLVMContext &Ctx, SyncScope::ID Id);
285
286// Find def instruction for the given ConstReg, walking through
287// spv_track_constant and ASSIGN_TYPE instructions. Updates ConstReg by def
288// of OpConstant instruction.
289MachineInstr *getDefInstrMaybeConstant(Register &ConstReg,
290 const MachineRegisterInfo *MRI);
291
292// Get constant integer value of the given ConstReg.
293uint64_t getIConstVal(Register ConstReg, const MachineRegisterInfo *MRI);
294
295// Get constant integer value of the given ConstReg, sign-extended.
296int64_t getIConstValSext(Register ConstReg, const MachineRegisterInfo *MRI);
297
298// Check if MI is a SPIR-V specific intrinsic call.
299bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID);
300// Check if it's a SPIR-V specific intrinsic call.
301bool isSpvIntrinsic(const Value *Arg);
302
303// Get type of i-th operand of the metadata node.
304Type *getMDOperandAsType(const MDNode *N, unsigned I);
305
306// Get the i-th operand of the metadata node as a ConstantInt, or nullptr if it
307// is out of range or not a ConstantInt.
308ConstantInt *getMDOperandAsConstInt(const MDNode *N, unsigned I);
309
310// If OpenCL or SPIR-V builtin function name is recognized, return a demangled
311// name, otherwise return an empty string.
312std::string getOclOrSpirvBuiltinDemangledName(StringRef Name);
313
314// Check if a string contains a builtin prefix.
315bool hasBuiltinTypePrefix(StringRef Name);
316
317// Check if given LLVM type is a special opaque builtin type.
318bool isSpecialOpaqueType(const Type *Ty);
319
320// Check if the function is an SPIR-V entry point
321bool isEntryPoint(const Function &F);
322
323// Parse basic scalar type name, substring TypeName, and return LLVM type.
324Type *parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx);
325
326// Sort blocks in a partial ordering, so each block is after all its
327// dominators. This should match both the SPIR-V and the MIR requirements.
328// Returns true if the function was changed.
329bool sortBlocks(Function &F);
330
331// Create a stack slot in the entry block of F for a value of the given type.
332AllocaInst *createVariable(Function &F, Type *Type);
333
334// Create a value in BB set to the value associated with the branch the block
335// terminator will take.
336Value *
337createExitVariable(BasicBlock *BB,
338 const DenseMap<BasicBlock *, ConstantInt *> &TargetToValue);
339
340// Check for peeled array structs and recursively reconstitute them. In HLSL
341// CBuffers, arrays may have padding between the elements, but not after the
342// last element. To represent this in LLVM IR an array [N x T] will be
343// represented as {[N-1 x {T, spirv.Padding}], T}. The function
344// matchPeeledArrayPattern recognizes this pattern retrieving the type {T,
345// spirv.Padding}, and the size N.
346bool matchPeeledArrayPattern(const StructType *Ty, Type *&OriginalElementType,
347 uint64_t &TotalSize);
348
349// This function will turn the type {[N-1 x {T, spirv.Padding}], T} back into
350// [N x {T, spirv.Padding}]. So it can be translated into SPIR-V. The offset
351// decorations will be such that there will be no padding after the array when
352// relevant.
353Type *reconstitutePeeledArrayType(Type *Ty);
354
355inline bool hasInitializer(const GlobalVariable *GV) {
356 if (!GV->hasInitializer())
357 return false;
358 if (const auto *Init = GV->getInitializer(); isa<UndefValue>(Val: Init))
359 return GV->isConstant() && Init->getType()->isAggregateType();
360 return true;
361}
362
363// True if this is an instance of TypedPointerType.
364inline bool isTypedPointerTy(const Type *T) {
365 return T && T->getTypeID() == Type::TypedPointerTyID;
366}
367
368// True if this is an instance of PointerType.
369inline bool isUntypedPointerTy(const Type *T) {
370 return T && T->getTypeID() == Type::PointerTyID;
371}
372
373// True if this is an instance of PointerType or TypedPointerType.
374inline bool isPointerTy(const Type *T) {
375 return isUntypedPointerTy(T) || isTypedPointerTy(T);
376}
377
378// True if this is a vector whose element type is an (untyped) PointerType.
379inline bool isUntypedPointerVectorTy(const Type *T) {
380 return isa_and_nonnull<VectorType>(Val: T) &&
381 isUntypedPointerTy(T: T->getScalarType());
382}
383
384// Get the address space of this pointer or pointer vector type for instances of
385// PointerType or TypedPointerType.
386inline unsigned getPointerAddressSpace(const Type *T) {
387 Type *SubT = T->getScalarType();
388 return SubT->getTypeID() == Type::PointerTyID
389 ? cast<PointerType>(Val: SubT)->getAddressSpace()
390 : cast<TypedPointerType>(Val: SubT)->getAddressSpace();
391}
392
393// Return true if the Argument is decorated with a pointee type
394inline bool hasPointeeTypeAttr(Argument *Arg) {
395 return Arg->hasByValAttr() || Arg->hasByRefAttr() || Arg->hasStructRetAttr();
396}
397
398// Return the pointee type of the argument or nullptr otherwise
399inline Type *getPointeeTypeByAttr(Argument *Arg) {
400 if (Arg->hasByValAttr())
401 return Arg->getParamByValType();
402 if (Arg->hasStructRetAttr())
403 return Arg->getParamStructRetType();
404 if (Arg->hasByRefAttr())
405 return Arg->getParamByRefType();
406 return nullptr;
407}
408
409#define TYPED_PTR_TARGET_EXT_NAME "spirv.$TypedPointerType"
410inline Type *getTypedPointerWrapper(Type *ElemTy, unsigned AS) {
411 return TargetExtType::get(Context&: ElemTy->getContext(), TYPED_PTR_TARGET_EXT_NAME,
412 Types: {ElemTy}, Ints: {AS});
413}
414
415inline bool isTypedPointerWrapper(const TargetExtType *ExtTy) {
416 return ExtTy->getName() == TYPED_PTR_TARGET_EXT_NAME &&
417 ExtTy->getNumIntParameters() == 1 &&
418 ExtTy->getNumTypeParameters() == 1;
419}
420
421// True if this is an instance of PointerType or TypedPointerType.
422inline bool isPointerTyOrWrapper(const Type *Ty) {
423 if (auto *ExtTy = dyn_cast<TargetExtType>(Val: Ty))
424 return isTypedPointerWrapper(ExtTy);
425 return isPointerTy(T: Ty);
426}
427
428inline Type *applyWrappers(Type *Ty) {
429 if (auto *ExtTy = dyn_cast<TargetExtType>(Val: Ty)) {
430 if (isTypedPointerWrapper(ExtTy))
431 return TypedPointerType::get(ElementType: applyWrappers(Ty: ExtTy->getTypeParameter(i: 0)),
432 AddressSpace: ExtTy->getIntParameter(i: 0));
433 } else if (auto *VecTy = dyn_cast<VectorType>(Val: Ty)) {
434 Type *ElemTy = VecTy->getElementType();
435 Type *NewElemTy = ElemTy->isTargetExtTy() ? applyWrappers(Ty: ElemTy) : ElemTy;
436 if (NewElemTy != ElemTy)
437 return VectorType::get(ElementType: NewElemTy, EC: VecTy->getElementCount());
438 }
439 return Ty;
440}
441
442inline Type *getPointeeType(const Type *Ty) {
443 if (Ty) {
444 if (auto PType = dyn_cast<TypedPointerType>(Val: Ty))
445 return PType->getElementType();
446 else if (auto *ExtTy = dyn_cast<TargetExtType>(Val: Ty))
447 if (isTypedPointerWrapper(ExtTy))
448 return ExtTy->getTypeParameter(i: 0);
449 }
450 return nullptr;
451}
452
453inline bool isUntypedEquivalentToTyExt(Type *Ty1, Type *Ty2) {
454 if (!isUntypedPointerTy(T: Ty1) || !Ty2)
455 return false;
456 if (auto *ExtTy = dyn_cast<TargetExtType>(Val: Ty2))
457 if (isTypedPointerWrapper(ExtTy) &&
458 ExtTy->getTypeParameter(i: 0) ==
459 IntegerType::getInt8Ty(C&: Ty1->getContext()) &&
460 ExtTy->getIntParameter(i: 0) == cast<PointerType>(Val: Ty1)->getAddressSpace())
461 return true;
462 return false;
463}
464
465inline bool isEquivalentTypes(Type *Ty1, Type *Ty2) {
466 return isUntypedEquivalentToTyExt(Ty1, Ty2) ||
467 isUntypedEquivalentToTyExt(Ty1: Ty2, Ty2: Ty1);
468}
469
470inline Type *toTypedPointer(Type *Ty) {
471 if (Type *NewTy = applyWrappers(Ty); NewTy != Ty)
472 return NewTy;
473 return isUntypedPointerTy(T: Ty)
474 ? TypedPointerType::get(ElementType: IntegerType::getInt8Ty(C&: Ty->getContext()),
475 AddressSpace: getPointerAddressSpace(T: Ty))
476 : Ty;
477}
478
479inline Type *toTypedFunPointer(FunctionType *FTy) {
480 Type *OrigRetTy = FTy->getReturnType();
481 Type *RetTy = toTypedPointer(Ty: OrigRetTy);
482 bool IsUntypedPtr = false;
483 for (Type *PTy : FTy->params()) {
484 if (isUntypedPointerTy(T: PTy)) {
485 IsUntypedPtr = true;
486 break;
487 }
488 }
489 if (!IsUntypedPtr && RetTy == OrigRetTy)
490 return FTy;
491 SmallVector<Type *> ParamTys;
492 for (Type *PTy : FTy->params())
493 ParamTys.push_back(Elt: toTypedPointer(Ty: PTy));
494 return FunctionType::get(Result: RetTy, Params: ParamTys, isVarArg: FTy->isVarArg());
495}
496
497inline const Type *unifyPtrType(const Type *Ty) {
498 if (auto FTy = dyn_cast<FunctionType>(Val: Ty))
499 return toTypedFunPointer(FTy: const_cast<FunctionType *>(FTy));
500 return toTypedPointer(Ty: const_cast<Type *>(Ty));
501}
502
503inline bool isVector1(Type *Ty) {
504 auto *FVTy = dyn_cast<FixedVectorType>(Val: Ty);
505 return FVTy && FVTy->getNumElements() == 1;
506}
507
508// Modify an LLVM type to conform with future transformations in IRTranslator.
509// At the moment use cases comprise only a <1 x Type> vector. To extend when/if
510// needed.
511inline Type *normalizeType(Type *Ty) {
512 auto *FVTy = dyn_cast<FixedVectorType>(Val: Ty);
513 if (!FVTy || FVTy->getNumElements() != 1)
514 return Ty;
515 // If it's a <1 x Type> vector type, replace it by the element type, because
516 // it's not a legal vector type in LLT and IRTranslator will represent it as
517 // the scalar eventually.
518 return normalizeType(Ty: FVTy->getElementType());
519}
520
521inline PoisonValue *getNormalizedPoisonValue(Type *Ty) {
522 return PoisonValue::get(T: normalizeType(Ty));
523}
524
525inline MetadataAsValue *buildMD(Value *Arg) {
526 LLVMContext &Ctx = Arg->getContext();
527 return MetadataAsValue::get(
528 Context&: Ctx, MD: MDNode::get(Context&: Ctx, MDs: ValueAsMetadata::getConstant(C: Arg)));
529}
530
531CallInst *buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef<Type *> Types,
532 Value *Arg, Value *Arg2, ArrayRef<Constant *> Imms,
533 IRBuilder<> &B);
534
535MachineInstr *getVRegDef(MachineRegisterInfo &MRI, Register Reg);
536
537#define SPIRV_BACKEND_SERVICE_FUN_NAME "__spirv_backend_service_fun"
538#define SPIRV_WAS_AVAILABLE_EXTERNALLY_ATTR "spv.was-available-externally"
539
540void setRegClassType(Register Reg, const Type *Ty, SPIRVGlobalRegistry *GR,
541 MachineIRBuilder &MIRBuilder,
542 SPIRV::AccessQualifier::AccessQualifier AccessQual,
543 bool EmitIR, bool Force = false);
544void setRegClassType(Register Reg, SPIRVTypeInst SpvType,
545 SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI,
546 const MachineFunction &MF, bool Force = false);
547Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR,
548 MachineRegisterInfo *MRI,
549 const MachineFunction &MF);
550Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR,
551 MachineIRBuilder &MIRBuilder);
552Register createVirtualRegister(
553 const Type *Ty, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder,
554 SPIRV::AccessQualifier::AccessQualifier AccessQual, bool EmitIR);
555
556// Return true if there is an opaque pointer type nested in the argument.
557bool isNestedPointer(const Type *Ty);
558
559enum FPDecorationId { NONE, RTE, RTZ, RTP, RTN, SAT };
560
561inline FPDecorationId demangledPostfixToDecorationId(const std::string &S) {
562 static const StringMap<FPDecorationId> Mapping = {
563 {"rte", FPDecorationId::RTE},
564 {"rtz", FPDecorationId::RTZ},
565 {"rtp", FPDecorationId::RTP},
566 {"rtn", FPDecorationId::RTN},
567 {"sat", FPDecorationId::SAT}};
568 auto It = Mapping.find(Key: S);
569 return It == Mapping.end() ? FPDecorationId::NONE : It->second;
570}
571
572SmallVector<MachineInstr *, 4>
573createContinuedInstructions(MachineIRBuilder &MIRBuilder, unsigned Opcode,
574 unsigned MinWC, unsigned ContinuedOpcode,
575 ArrayRef<Register> Args, Register ReturnRegister,
576 Register TypeID);
577
578// Instruction selection directed by type folding.
579const std::set<unsigned> &getTypeFoldingSupportedOpcodes();
580bool isTypeFoldingSupported(unsigned Opcode);
581
582// Get loop controls from llvm.loop. metadata.
583SmallVector<unsigned, 1> getSpirvLoopControlOperandsFromLoopMetadata(Loop *L);
584SmallVector<unsigned, 1>
585getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD);
586
587// Traversing [g]MIR accounting for pseudo-instructions.
588MachineInstr *passCopy(MachineInstr *Def, const MachineRegisterInfo *MRI);
589MachineInstr *getDef(const MachineOperand &MO, const MachineRegisterInfo *MRI);
590MachineInstr *getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI);
591int64_t foldImm(const MachineOperand &MO, const MachineRegisterInfo *MRI);
592unsigned getArrayComponentCount(const MachineRegisterInfo *MRI,
593 const MachineInstr *ResType);
594
595std::optional<SPIRV::LinkageType::LinkageType>
596getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV);
597Function *getOrCreateBackendServiceFunction(Module &M);
598} // namespace llvm
599#endif // LLVM_LIB_TARGET_SPIRV_SPIRVUTILS_H
600