clang 24.0.0git
CGHLSLRuntime.cpp
Go to the documentation of this file.
1//===----- CGHLSLRuntime.cpp - Interface to HLSL Runtimes -----------------===//
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 provides an abstract class for HLSL code generation. Concrete
10// subclasses of this implement code generation for specific HLSL
11// runtime libraries.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGHLSLRuntime.h"
16#include "CGDebugInfo.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
21#include "TargetInfo.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/Expr.h"
29#include "clang/AST/Type.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/Enum.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/ScopeExit.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Frontend/HLSL/HLSLResource.h"
43#include "llvm/Frontend/HLSL/HLSLUtils.h"
44#include "llvm/Frontend/HLSL/RootSignatureMetadata.h"
45#include "llvm/Frontend/HLSL/SemanticSignaturePacking.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/IR/GlobalVariable.h"
49#include "llvm/IR/IntrinsicInst.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/Value.h"
55#include "llvm/Support/Alignment.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/FormatVariadic.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Transforms/Utils/ModuleUtils.h"
60#include <array>
61#include <cstdint>
62#include <optional>
63
64using namespace clang;
65using namespace CodeGen;
66using namespace clang::hlsl;
67using namespace llvm;
68
69using llvm::hlsl::CBufferRowSizeInBytes;
70
71namespace {
72
73enum class SPIRVExecutionMode : uint32_t {
74 DerivativeGroupQuadsKHR = 5289,
75 DerivativeGroupLinearKHR = 5290
76};
77
78void addDxilValVersion(StringRef ValVersionStr, llvm::Module &M) {
79 // The validation of ValVersionStr is done at HLSLToolChain::TranslateArgs.
80 // Assume ValVersionStr is legal here.
81 VersionTuple Version;
82 if (Version.tryParse(ValVersionStr) || Version.getBuild() ||
83 Version.getSubminor() || !Version.getMinor()) {
84 return;
85 }
86
87 uint64_t Major = Version.getMajor();
88 uint64_t Minor = *Version.getMinor();
89
90 auto &Ctx = M.getContext();
91 IRBuilder<> B(M);
92 MDNode *Val = MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(Major)),
93 ConstantAsMetadata::get(B.getInt32(Minor))});
94 StringRef DXILValKey = "dx.valver";
95 auto *DXILValMD = M.getOrInsertNamedMetadata(DXILValKey);
96 DXILValMD->addOperand(Val);
97}
98
99void addRootSignatureMD(llvm::dxbc::RootSignatureVersion RootSigVer,
101 llvm::Function *Fn, llvm::Module &M) {
102 auto &Ctx = M.getContext();
103
104 llvm::hlsl::rootsig::MetadataBuilder RSBuilder(M, Elements);
105 MDNode *RootSignature = RSBuilder.BuildRootSignature();
106
107 ConstantAsMetadata *Version = ConstantAsMetadata::get(ConstantInt::get(
108 llvm::Type::getInt32Ty(Ctx), llvm::to_underlying(RootSigVer)));
109 ValueAsMetadata *EntryFunc = Fn ? ValueAsMetadata::get(Fn) : nullptr;
110 MDNode *MDVals = MDNode::get(Ctx, {EntryFunc, RootSignature, Version});
111
112 StringRef RootSignatureValKey = "dx.rootsignatures";
113 auto *RootSignatureValMD = M.getOrInsertNamedMetadata(RootSignatureValKey);
114 RootSignatureValMD->addOperand(MDVals);
115}
116
117Expected<unsigned> packSemanticSignature(
119 llvm::Triple::EnvironmentType Stage, llvm::hlsl::IOType IOTy,
121 bool UseNative16BitTypes) {
122 using namespace llvm::hlsl;
123 // Vertex inputs and pixel outputs have fixed packing rules, independent of
124 // the packing mode used between programmable stages.
125 if (Stage == llvm::Triple::Vertex && IOTy == IOType::In)
126 return packSignatureStacked(Elements, Stage, IOTy);
127 if (Stage == llvm::Triple::Pixel && IOTy == IOType::Out)
128 return packSignatureIndexed(Elements, Stage, IOTy);
130 return packSignatureOptimized(Elements, Stage, IOTy, UseNative16BitTypes);
131 return packSignaturePrefixStable(Elements, Stage, IOTy, UseNative16BitTypes);
132}
133
134MDNode *buildSemanticSignatureMD(
135 ArrayRef<llvm::hlsl::SemanticSignatureElement> Elements, LLVMContext &Ctx) {
136 if (Elements.empty())
137 return nullptr;
138
139 SmallVector<Metadata *> ElementMD;
140 for (const llvm::hlsl::SemanticSignatureElement &Element : Elements)
141 ElementMD.push_back(Element.toMetadata(Ctx));
142 return MDNode::get(Ctx, ElementMD);
143}
144
145void addSemanticSignatureMD(
148 llvm::Function *Fn, llvm::Module &M) {
149 if (InputElements.empty() && OutputElements.empty())
150 return;
151
152 LLVMContext &Ctx = M.getContext();
153 MDNode *InputSignature = buildSemanticSignatureMD(InputElements, Ctx);
154 MDNode *OutputSignature = buildSemanticSignatureMD(OutputElements, Ctx);
155 MDNode *MDVals = MDNode::get(
156 Ctx, {ValueAsMetadata::get(Fn), InputSignature, OutputSignature});
157
158 M.getOrInsertNamedMetadata("dx.semantic.signatures")->addOperand(MDVals);
159}
160
161static void copyGlobalResource(CodeGenFunction &CGF, const VarDecl *ResourceVD,
162 AggValueSlot &DestSlot) {
163 GlobalVariable *ResGV =
165 assert(ResGV && "expected valid global variable");
166 CGF.Builder.CreateStore(ResGV, DestSlot.getAddress());
167}
168
169// Given a MemberExpr of a resource or resource array type, find the parent
170// VarDecl of the struct or class instance that contains this resource and
171// build the full resource name based on the member access path.
172//
173// For example, for a member access like "myStructArray[0].memberA",
174// this function will find the VarDecl of "myStructArray" and use the
175// EmbeddedResourceNameBuilder to build the resource name
176// "myStructArray.0.memberA".
177//
178// This also works for a record type expression that has some embedded
179// resources. It finds the parent VarDecl of that record and builds a partial
180// name which is the prefix of the resource globals associated with the
181// declaration.
182static const VarDecl *findStructResourceParentDeclAndBuildName(
183 const Expr *E, EmbeddedResourceNameBuilder &NameBuilder) {
184
186 const VarDecl *VD = nullptr;
187
188 for (;;) {
189 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
190 assert(isa<VarDecl>(DRE->getDecl()) &&
191 "member expr base is not a var decl");
192 VD = cast<VarDecl>(DRE->getDecl());
193 NameBuilder.pushName(VD->getName());
194 break;
195 }
196
197 WorkList.push_back(E);
198 if (const auto *MExp = dyn_cast<MemberExpr>(E))
199 E = MExp->getBase();
200 else if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
201 E = ICE->getSubExpr();
202 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
203 E = ASE->getBase();
204 else if (isa<CXXThisExpr>(E))
205 // Resource member access on "this" pointer not yet implemented
206 // (llvm/llvm-project#190299)
207 return nullptr;
208 else
209 llvm_unreachable("unexpected expr type in resource member access");
210
211 assert(E && "expected valid expression");
212 }
213
214 while (!WorkList.empty()) {
215 E = WorkList.pop_back_val();
216 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
217 NameBuilder.pushName(
218 ME->getMemberNameInfo().getName().getAsIdentifierInfo()->getName());
219 } else if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
220 if (ICE->getCastKind() == CK_UncheckedDerivedToBase) {
221 CXXRecordDecl *DerivedRD =
222 ICE->getSubExpr()->getType()->getAsCXXRecordDecl();
223 CXXRecordDecl *BaseRD = ICE->getType()->getAsCXXRecordDecl();
224 NameBuilder.pushBaseNameHierarchy(DerivedRD, BaseRD);
225 }
226 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
227 const Expr *IdxExpr = ASE->getIdx();
228 std::optional<llvm::APSInt> Value =
230 assert(Value &&
231 "expected constant index in struct with resource array access");
232 NameBuilder.pushArrayIndex(Value->getZExtValue());
233 } else {
234 llvm_unreachable("unexpected expr type in resource member access");
235 }
236 }
237 return VD;
238}
239
240// Given a MemberExpr of a resource or resource array type, find the
241// corresponding global resource declaration associated with the owning struct
242// or class instance via HLSLAssociatedResourceDeclAttr.
243static const VarDecl *
244findAssociatedResourceDeclForStruct(ASTContext &AST, const MemberExpr *ME) {
245
246 EmbeddedResourceNameBuilder NameBuilder;
247 const VarDecl *ParentVD =
248 findStructResourceParentDeclAndBuildName(ME, NameBuilder);
249 if (!ParentVD)
250 return nullptr;
251
252 if (!ParentVD->hasGlobalStorage())
253 return nullptr;
254
255 IdentifierInfo *II = NameBuilder.getNameAsIdentifier(AST);
256 for (const Attr *A : ParentVD->getAttrs()) {
257 if (const auto *ADA = dyn_cast<HLSLAssociatedResourceDeclAttr>(A)) {
258 VarDecl *AssocResVD = ADA->getResDecl();
259 if (AssocResVD->getIdentifier() == II)
260 return AssocResVD;
261 }
262 }
263 return nullptr;
264}
265
266void addSourceInfo(CodeGenModule &CGM, llvm::Module &M) {
267 auto &SM = CGM.getContext().getSourceManager();
268 auto &Macros = CGM.getPreprocessorOpts().Macros;
269 auto &CodeGenOpts = CGM.getCodeGenOpts();
270 auto &Ctx = M.getContext();
271
272 // Names and content of shader source code files.
273 llvm::NamedMDNode *DXContents =
274 M.getOrInsertNamedMetadata("dx.source.contents");
275 auto addFile = [&](const std::pair<StringRef, StringRef> &NameContent) {
276 llvm::MDTuple *FileInfo =
277 llvm::MDNode::get(Ctx, {llvm::MDString::get(Ctx, NameContent.first),
278 llvm::MDString::get(Ctx, NameContent.second)});
279 DXContents->addOperand(FileInfo);
280 };
281
282 bool Invalid = false;
283 const SrcMgr::SLocEntry *MainLocEntry =
284 &SM.getSLocEntry(SM.getMainFileID(), &Invalid);
285 assert(!Invalid && "Main file SLocEntry must not be invalid!");
286 const SrcMgr::ContentCache &MainCCEntry =
287 MainLocEntry->getFile().getContentCache();
288
290 std::optional<SmallString<256>> MainFileName;
291 Files.reserve(SM.local_sloc_entry_size());
292 for (unsigned I : llvm::seq(SM.local_sloc_entry_size())) {
293 const SrcMgr::SLocEntry &LocEntry = SM.getLocalSLocEntry(I);
294 if (!LocEntry.isFile())
295 continue;
296
297 const SrcMgr::FileInfo &FInfo = LocEntry.getFile();
298 if (isSystem(FInfo.getFileCharacteristic()))
299 continue;
300
301 const SrcMgr::ContentCache &CCEntry = FInfo.getContentCache();
302 OptionalFileEntryRef FEntry = CCEntry.OrigEntry;
303 if (!FEntry)
304 continue;
305
306 llvm::SmallString<256> Path = FEntry->getName();
307 llvm::sys::path::native(Path);
308 std::optional<llvm::MemoryBufferRef> Buffer = CCEntry.getBufferOrNone(
309 SM.getDiagnostics(), SM.getFileManager(), SourceLocation());
310 if (!Buffer) {
311 SM.getDiagnostics().Report(diag::warn_hlsl_failed_to_embed_source)
312 << Path;
313 continue;
314 }
315
316 if (&MainCCEntry != &CCEntry) {
317 Files.emplace_back(Path, Buffer->getBuffer());
318 } else {
319 // Main file should be at first position.
320 addFile(std::make_pair(Path, Buffer->getBuffer()));
321 MainFileName.emplace(Path);
322 }
323 }
324 assert(MainFileName && "Main file not found.");
325
326 // Files other that main one should be sorted by name.
327 llvm::sort(Files);
328#ifndef NDEBUG
329 for (unsigned I = 1; I < Files.size(); ++I)
330 assert((Files[I - 1].first != Files[I].first) &&
331 "duplicate files in dx.source.contents");
332#endif
333 llvm::for_each(Files, addFile);
334
336 Defines.reserve(Macros.size());
337 for (const auto &Macro : Macros) {
338 // Ignore undefs.
339 if (!Macro.second)
340 Defines.emplace_back(llvm::MDString::get(Ctx, Macro.first));
341 }
342 M.getOrInsertNamedMetadata("dx.source.defines")
343 ->addOperand(llvm::MDNode::get(Ctx, Defines));
344
345 if (!CodeGenOpts.MainFileName.empty())
346 llvm::sys::path::native(CodeGenOpts.MainFileName, *MainFileName);
347 M.getOrInsertNamedMetadata("dx.source.mainFileName")
348 ->addOperand(
349 llvm::MDNode::get(Ctx, llvm::MDString::get(Ctx, *MainFileName)));
350
352 Args.reserve(CodeGenOpts.HLSLParsedCommandLine.size());
353 if (!CodeGenOpts.HLSLParsedCommandLine.empty())
354 for (const auto &Arg : llvm::drop_begin(CodeGenOpts.HLSLParsedCommandLine))
355 Args.push_back(llvm::MDString::get(Ctx, Arg));
356 M.getOrInsertNamedMetadata("dx.source.args")
357 ->addOperand(llvm::MDNode::get(Ctx, Args));
358}
359
360// Find array variable declaration from DeclRef expression
361static const ValueDecl *getArrayDecl(ASTContext &AST, const Expr *E) {
362 E = E->IgnoreImpCasts();
363 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
364 return DRE->getDecl();
365 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
366 E = OVE->getSourceExpr()->IgnoreImpCasts();
367 if (isa<MemberExpr>(E))
368 return findAssociatedResourceDeclForStruct(AST, cast<MemberExpr>(E));
369 return nullptr;
370}
371
372// Find array variable declaration from nested array subscript AST nodes
373static const ValueDecl *getArrayDecl(ASTContext &AST,
374 const ArraySubscriptExpr *ASE) {
375 const Expr *E = nullptr;
376 while (ASE != nullptr) {
377 E = ASE->getBase()->IgnoreImpCasts();
378 if (!E)
379 return nullptr;
380 ASE = dyn_cast<ArraySubscriptExpr>(E);
381 }
382 return getArrayDecl(AST, E);
383}
384
385// Get the total size of the array, or 0 if the array is unbounded.
386static int getTotalArraySize(ASTContext &AST, const clang::Type *Ty) {
388 assert(Ty->isArrayType() && "expected array type");
389 if (Ty->isIncompleteArrayType())
390 return 0;
392}
393
394static Value *buildNameForResource(llvm::StringRef BaseName,
395 CodeGenModule &CGM) {
396 llvm::SmallString<64> GlobalName = {BaseName, ".str"};
397 return CGM.GetAddrOfConstantCString(BaseName.str(), GlobalName.c_str())
398 .getPointer();
399}
400
401static CXXMethodDecl *lookupMethod(CXXRecordDecl *Record, StringRef Name,
402 StorageClass SC = SC_None) {
403 for (auto *Method : Record->methods()) {
404 if (Method->getStorageClass() == SC && Method->getName() == Name)
405 return Method;
406 }
407 return nullptr;
408}
409
410static CXXMethodDecl *lookupResourceInitMethodAndSetupArgs(
411 CodeGenModule &CGM, CXXRecordDecl *ResourceDecl, llvm::Value *Range,
412 llvm::Value *Index, StringRef Name, ResourceBindingAttrs &Binding,
413 CallArgList &Args) {
414 assert(Binding.hasBinding() && "at least one binding attribute expected");
415
416 ASTContext &AST = CGM.getContext();
417 CXXMethodDecl *CreateMethod = nullptr;
418 Value *NameStr = buildNameForResource(Name, CGM);
419 Value *Space = llvm::ConstantInt::get(CGM.IntTy, Binding.getSpace());
420
421 bool HasCounter = hasCounterHandle(ResourceDecl);
422 assert((!HasCounter || Binding.hasCounterImplicitOrderID()) &&
423 "resources with counter handle must have a binding with counter "
424 "implicit order ID");
425 if (Binding.isExplicit()) {
426 // explicit binding
427 auto *RegSlot = llvm::ConstantInt::get(CGM.IntTy, Binding.getSlot());
428 Args.add(RValue::get(RegSlot), AST.UnsignedIntTy);
429 const char *Name = Binding.hasCounterImplicitOrderID()
430 ? "__createFromBindingWithImplicitCounter"
431 : "__createFromBinding";
432 CreateMethod = lookupMethod(ResourceDecl, Name, SC_Static);
433 } else {
434 // implicit binding
435 auto *OrderID =
436 llvm::ConstantInt::get(CGM.IntTy, Binding.getImplicitOrderID());
437 Args.add(RValue::get(OrderID), AST.UnsignedIntTy);
438 const char *Name = Binding.hasCounterImplicitOrderID()
439 ? "__createFromImplicitBindingWithImplicitCounter"
440 : "__createFromImplicitBinding";
441 CreateMethod = lookupMethod(ResourceDecl, Name, SC_Static);
442 }
443 Args.add(RValue::get(Space), AST.UnsignedIntTy);
444 Args.add(RValue::get(Range), AST.IntTy);
445 Args.add(RValue::get(Index), AST.UnsignedIntTy);
446 Args.add(RValue::get(NameStr), AST.getPointerType(AST.CharTy.withConst()));
447 if (HasCounter) {
448 uint32_t CounterBinding = Binding.getCounterImplicitOrderID();
449 auto *CounterOrderID = llvm::ConstantInt::get(CGM.IntTy, CounterBinding);
450 Args.add(RValue::get(CounterOrderID), AST.UnsignedIntTy);
451 }
452
453 return CreateMethod;
454}
455
456static void callResourceInitMethod(CodeGenFunction &CGF,
457 CXXMethodDecl *CreateMethod,
458 CallArgList &Args, Address ReturnAddress) {
459 llvm::Constant *CalleeFn = CGF.CGM.GetAddrOfFunction(CreateMethod);
460 const FunctionProtoType *Proto =
461 CreateMethod->getType()->getAs<FunctionProtoType>();
462 // HLSL code generation is restricted to DXIL and SPIR-V targets, so no
463 // caller declaration is needed for x86 SysV ABI selection.
465 Args, Proto, false, /*ABIInfoFD=*/nullptr);
466 ReturnValueSlot ReturnValue(ReturnAddress, false);
467 CGCallee Callee(CGCalleeInfo(Proto), CalleeFn);
468 CGF.EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr);
469}
470
471// Initializes local resource array variable with global resource array
472// elements. For multi-dimensional arrays it calls itself recursively to
473// initialize its sub-arrays. The Index used in the resource constructor calls
474// will begin at StartIndex and will be incremented for each array element. The
475// last used resource Index is returned to the caller. If the function returns
476// std::nullopt, it indicates an error.
477static std::optional<llvm::Value *> initializeResourceArrayFromGlobal(
478 CodeGenFunction &CGF, CXXRecordDecl *ResourceDecl,
479 const ConstantArrayType *ArrayTy, AggValueSlot &ValueSlot,
480 llvm::Value *Range, llvm::Value *StartIndex, StringRef ResourceName,
481 ResourceBindingAttrs &Binding, ArrayRef<llvm::Value *> PrevGEPIndices) {
482
483 ASTContext &AST = CGF.getContext();
484 llvm::IntegerType *IntTy = CGF.CGM.IntTy;
485 llvm::Value *Index = StartIndex;
486 llvm::Value *One = llvm::ConstantInt::get(IntTy, 1);
487 const uint64_t ArraySize = ArrayTy->getSExtSize();
488 QualType ElemType = ArrayTy->getElementType();
489 Address TmpArrayAddr = ValueSlot.getAddress();
490
491 // Add additional index to the getelementptr call indices.
492 // This index will be updated for each array element in the loops below.
493 SmallVector<llvm::Value *> GEPIndices(PrevGEPIndices);
494 GEPIndices.push_back(llvm::ConstantInt::get(IntTy, 0));
495
496 // For array of arrays, recursively initialize the sub-arrays.
497 if (ElemType->isArrayType()) {
498 const ConstantArrayType *SubArrayTy = cast<ConstantArrayType>(ElemType);
499 for (uint64_t I = 0; I < ArraySize; I++) {
500 if (I > 0) {
501 Index = CGF.Builder.CreateAdd(Index, One);
502 GEPIndices.back() = llvm::ConstantInt::get(IntTy, I);
503 }
504 std::optional<llvm::Value *> MaybeIndex =
505 initializeResourceArrayFromGlobal(CGF, ResourceDecl, SubArrayTy,
506 ValueSlot, Range, Index,
507 ResourceName, Binding, GEPIndices);
508 if (!MaybeIndex)
509 return std::nullopt;
510 Index = *MaybeIndex;
511 }
512 return Index;
513 }
514
515 // For array of resources, initialize each resource in the array.
516 llvm::Type *Ty = CGF.ConvertTypeForMem(ElemType);
517 CharUnits ElemSize = AST.getTypeSizeInChars(ElemType);
518 CharUnits Align =
519 TmpArrayAddr.getAlignment().alignmentOfArrayElement(ElemSize);
520
521 for (uint64_t I = 0; I < ArraySize; I++) {
522 if (I > 0) {
523 Index = CGF.Builder.CreateAdd(Index, One);
524 GEPIndices.back() = llvm::ConstantInt::get(IntTy, I);
525 }
526 Address ReturnAddress =
527 CGF.Builder.CreateGEP(TmpArrayAddr, GEPIndices, Ty, Align);
528
529 CallArgList Args;
530 CXXMethodDecl *CreateMethod = lookupResourceInitMethodAndSetupArgs(
531 CGF.CGM, ResourceDecl, Range, Index, ResourceName, Binding, Args);
532
533 if (!CreateMethod)
534 // This can happen if someone creates an array of structs that looks like
535 // an HLSL resource record array but it does not have the required static
536 // create method. No binding will be generated for it.
537 return std::nullopt;
538
539 callResourceInitMethod(CGF, CreateMethod, Args, ReturnAddress);
540 }
541 return Index;
542}
543
544/// Utility for emitting copies following the HLSL buffer layout rules (ie,
545/// copying out of a cbuffer).
546class HLSLBufferCopyEmitter {
547 CodeGenFunction &CGF;
548 Address DstPtr;
549 Address SrcPtr;
550 llvm::Type *LayoutTy = nullptr;
551
552 SmallVector<llvm::Value *> CurStoreIndices;
553 SmallVector<llvm::Value *> CurLoadIndices;
554
555 using EmitResourceFnTy = llvm::function_ref<void(AggValueSlot &)>;
556
557 // Creates & returns either a structured.gep or a ptradd/gep depending on
558 // langopts.
559 llvm::Value *emitAccessChain(llvm::Type *BaseTy, llvm::Value *Base,
560 ArrayRef<llvm::Value *> Indices) {
561 bool EmitLogical = CGF.getLangOpts().EmitLogicalPointer;
562 if (EmitLogical)
563 return CGF.Builder.CreateAccessChain(EmitLogical, BaseTy, Base, Indices);
564
565 llvm::SmallVector<llvm::Value *> GEPIndices;
566 GEPIndices.reserve(Indices.size() + 1);
567 GEPIndices.push_back(llvm::ConstantInt::get(CGF.IntTy, 0));
568 GEPIndices.append(Indices.begin(), Indices.end());
569 return CGF.Builder.CreateAccessChain(EmitLogical, BaseTy, Base, GEPIndices);
570 }
571
572 bool isBufferLayoutArray(llvm::StructType *ST) {
573 // A buffer layout array is a struct with two elements: the padded array,
574 // and the last element. That is, is should look something like this:
575 //
576 // { [%n x { %type, %padding }], %type }
577 //
578 if (!ST || ST->getNumElements() != 2)
579 return false;
580
581 auto *PaddedEltsTy = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
582 if (!PaddedEltsTy)
583 return false;
584
585 auto *PaddedTy = dyn_cast<llvm::StructType>(PaddedEltsTy->getElementType());
586 if (!PaddedTy || PaddedTy->getNumElements() != 2)
587 return false;
588
589 if (!CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(
590 PaddedTy->getElementType(1)))
591 return false;
592
593 llvm::Type *ElementTy = ST->getElementType(1);
594 if (PaddedTy->getElementType(0) != ElementTy)
595 return false;
596 return true;
597 }
598
599 // Returns true if the type is either a struct representing a resource record,
600 // or an array of structs that are resource records. This assumes a struct is
601 // a resource record if the first element is a target type (resource handle).
602 // This is the case for all target types used by HLSL except the padding type
603 // ("{dx|spirv.Padding"), but padding will never be the first element of a
604 // struct.
605 bool isResourceOrResourceArray(llvm::Type *Ty) {
606 while (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
607 Ty = AT->getElementType();
608
609 auto *ST = dyn_cast<llvm::StructType>(Ty);
610 if (!ST || ST->getNumElements() < 1)
611 return false;
612
613 auto *TargetTy = dyn_cast<llvm::TargetExtType>(ST->getElementType(0));
614 return TargetTy != nullptr;
615 }
616
617 void emitResourceOrResourceArray(Value *Dst, llvm::Type *DstTy,
618 EmitResourceFnTy EmitResFn) {
619 CharUnits DstAlign =
620 CharUnits::fromQuantity(CGF.CGM.getDataLayout().getABITypeAlign(DstTy));
621 Address DstAddr(Dst, DstTy, DstAlign);
622 AggValueSlot Slot = AggValueSlot::forAddr(
623 DstAddr, Qualifiers(), AggValueSlot::IsDestructed_t(true),
626
627 EmitResFn(Slot);
628 }
629
630 void emitBufferLayoutCopy(Value *Src, llvm::StructType *SrcTy, Value *Dst,
631 llvm::ArrayType *DstTy,
632 EmitResourceFnTy EmitResFn) {
633 // Those assumptions are checked by isBufferLayoutArray.
634 auto *SrcPaddedArrayTy = cast<llvm::ArrayType>(SrcTy->getElementType(0));
635 assert(SrcPaddedArrayTy->getNumElements() + 1 == DstTy->getNumElements());
636 assert(cast<llvm::StructType>(SrcPaddedArrayTy->getElementType())
637 ->getElementType(0) == SrcTy->getElementType(1));
638
639 auto *SrcDataTy = SrcTy->getElementType(1);
640 auto Zero = llvm::ConstantInt::get(CGF.IntTy, 0);
641
642 for (unsigned I = 0; I < SrcPaddedArrayTy->getNumElements(); ++I) {
643 auto Index = llvm::ConstantInt::get(CGF.IntTy, I);
644 auto *SrcElt = emitAccessChain(SrcTy, Src, {Zero, Index, Zero});
645 auto *DstElt = emitAccessChain(DstTy, Dst, {Index});
646 emitElementCopy(SrcElt, SrcDataTy, DstElt, DstTy->getElementType(),
647 EmitResFn);
648 }
649
650 auto *SrcElt =
651 emitAccessChain(SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, 1)});
652 auto *DstElt = emitAccessChain(
653 DstTy, Dst,
654 {llvm::ConstantInt::get(CGF.IntTy, DstTy->getNumElements() - 1)});
655 emitElementCopy(SrcElt, SrcDataTy, DstElt, DstTy->getElementType(),
656 EmitResFn);
657 }
658
659 void emitCopy(Value *Src, llvm::StructType *SrcTy, Value *Dst,
660 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
661 assert(!isResourceOrResourceArray(DstTy) &&
662 "direct access to resources or resource arrays should be handled "
663 "separately");
664
665 if (isBufferLayoutArray(SrcTy))
666 return emitBufferLayoutCopy(Src, SrcTy, Dst, cast<llvm::ArrayType>(DstTy),
667 EmitResFn);
668
669 unsigned SrcIndex = 0;
670 unsigned DstIndex = 0;
671
672 // DstTy layout is in default address space and can include resource types.
673 // SrcTy is in cbuffer layout where resources are filtered out, so the
674 // number of elements in SrcTy can be less than the number of elements in
675 // DstTy.
676 auto *DstST = cast<llvm::StructType>(DstTy);
677 while (DstIndex < DstST->getNumElements()) {
678 llvm::Type *DstEltTy = DstST->getElementType(DstIndex);
679 if (CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(DstEltTy)) {
680 DstIndex += 1;
681 continue;
682 }
683 if (isResourceOrResourceArray(DstEltTy)) {
684 auto *DstElt = emitAccessChain(
685 DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, DstIndex)});
686 emitResourceOrResourceArray(DstElt, DstEltTy, EmitResFn);
687 DstIndex += 1;
688 continue;
689 }
690
691 assert(SrcIndex < SrcTy->getNumElements());
692 llvm::Type *SrcEltTy = SrcTy->getElementType(SrcIndex);
693 if (CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(SrcEltTy)) {
694 SrcIndex += 1;
695 continue;
696 }
697
698 auto *SrcElt = emitAccessChain(
699 SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, SrcIndex)});
700 auto *DstElt = emitAccessChain(
701 DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, DstIndex)});
702 emitElementCopy(SrcElt, SrcEltTy, DstElt, DstEltTy, EmitResFn);
703 DstIndex += 1;
704 SrcIndex += 1;
705 }
706 }
707
708 void emitCopy(Value *Src, llvm::ArrayType *SrcTy, Value *Dst,
709 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
710 for (unsigned I = 0, E = SrcTy->getNumElements(); I < E; ++I) {
711 auto *SrcElt =
712 emitAccessChain(SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, I)});
713 auto *DstElt =
714 emitAccessChain(DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, I)});
715 emitElementCopy(SrcElt, SrcTy->getElementType(), DstElt,
716 cast<llvm::ArrayType>(DstTy)->getElementType(),
717 EmitResFn);
718 }
719 }
720
721 void emitElementCopy(Value *Src, llvm::Type *SrcTy, Value *Dst,
722 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
723 if (auto *AT = dyn_cast<llvm::ArrayType>(SrcTy))
724 return emitCopy(Src, AT, Dst, DstTy, EmitResFn);
725 if (auto *ST = dyn_cast<llvm::StructType>(SrcTy))
726 return emitCopy(Src, ST, Dst, DstTy, EmitResFn);
727
728 // When we have a scalar or vector element we can emit the copy.
729 CharUnits SrcAlign =
730 CharUnits::fromQuantity(CGF.CGM.getDataLayout().getABITypeAlign(SrcTy));
731 CharUnits DstAlign =
732 CharUnits::fromQuantity(CGF.CGM.getDataLayout().getABITypeAlign(DstTy));
733 Address SrcAddr(Src, SrcTy, SrcAlign);
734 Address DstAddr(Dst, DstTy, DstAlign);
735 llvm::Value *Load = CGF.Builder.CreateLoad(SrcAddr, "cbuf.load");
736 CGF.Builder.CreateStore(Load, DstAddr);
737 }
738
739public:
740 HLSLBufferCopyEmitter(CodeGenFunction &CGF, Address DstPtr, Address SrcPtr)
741 : CGF(CGF), DstPtr(DstPtr), SrcPtr(SrcPtr) {}
742
743 bool emitCopy(QualType CType, EmitResourceFnTy EmitResFn = nullptr) {
744 LayoutTy = HLSLBufferLayoutBuilder(CGF.CGM).layOutType(CType);
745
746 // TODO: We should be able to fall back to a regular memcpy if the layout
747 // type doesn't have any padding, but that runs into issues in the backend
748 // currently.
749 //
750 // See https://github.com/llvm/wg-hlsl/issues/351
751 emitElementCopy(SrcPtr.getBasePointer(), LayoutTy, DstPtr.getBasePointer(),
752 DstPtr.getElementType(), EmitResFn);
753 return true;
754 }
755};
756
757// Represents a list resources associated with a global struct whose name
758// starts with the specified prefix.
759// The order of HLSLAssociatedResourceDeclAttr attributes is identical to the
760// order of the depth-first traversal of the corresponding fields in the struct.
761// The resources are always returned in that order, which is the same order
762// we need when a struct is copied element-by-element.
763class AssociatedResourcesList {
764 // Iterator pointers for the associated resource attributes that match the
765 // prefix. Begin = begin of the range of attributes that match the prefix End
766 // = end of the range of attributes that match the prefix Next = the current
767 // attribute in the iteration to be returned by getNextResource
768 specific_attr_iterator<HLSLAssociatedResourceDeclAttr> Begin, End, Next;
769
770public:
771 AssociatedResourcesList(const VarDecl *StructVD,
772 StringRef ResourceNamePrefix) {
773 auto I = StructVD->specific_attr_begin<HLSLAssociatedResourceDeclAttr>();
774 auto E = StructVD->specific_attr_end<HLSLAssociatedResourceDeclAttr>();
775
776 // Skip over associated resources that don't match the prefix.
777 while (I != E &&
778 !I->getResDecl()->getName().starts_with(ResourceNamePrefix))
779 ++I;
780 assert(I != E && "expected associated resource not found");
781 Begin = End = I;
782
783 // Scan over associated resources that do match the prefix to find the end
784 // of the range.
785 while (I != E && ((HLSLAssociatedResourceDeclAttr *)*I)
786 ->getResDecl()
787 ->getName()
788 .starts_with(ResourceNamePrefix))
789 End = ++I;
790
791 Next = Begin;
792 }
793
794 const VarDecl *getNextResource() {
795 if (Next == End)
796 return nullptr;
797
798 const VarDecl *Res = Next->getResDecl();
799 ++Next;
800 return Res;
801 }
802};
803
804} // namespace
805
806llvm::Type *
808 const CGHLSLOffsetInfo &OffsetInfo) {
809 assert(T->isHLSLSpecificType() && "Not an HLSL specific type!");
810
811 // Check if the target has a specific translation for this type first.
812 if (llvm::Type *TargetTy =
813 CGM.getTargetCodeGenInfo().getHLSLType(CGM, T, OffsetInfo))
814 return TargetTy;
815
816 llvm_unreachable("Generic handling of HLSL types is not supported.");
817}
818
819llvm::Triple::ArchType CGHLSLRuntime::getArch() {
820 return CGM.getTarget().getTriple().getArch();
821}
822
823// Emits constant global variables for buffer constants declarations
824// and creates metadata linking the constant globals with the buffer global.
825void CGHLSLRuntime::emitBufferGlobalsAndMetadata(
826 const HLSLBufferDecl *BufDecl, llvm::GlobalVariable *BufGV,
827 const CGHLSLOffsetInfo &OffsetInfo) {
828 LLVMContext &Ctx = CGM.getLLVMContext();
829
830 // get the layout struct from constant buffer target type
831 llvm::Type *BufType = BufGV->getValueType();
832 llvm::StructType *LayoutStruct = cast<llvm::StructType>(
833 cast<llvm::TargetExtType>(BufType)->getTypeParameter(0));
834
836 size_t OffsetIdx = 0;
837 for (Decl *D : BufDecl->buffer_decls()) {
839 // Nothing to do for this declaration.
840 continue;
841 if (isa<FunctionDecl>(D)) {
842 // A function within an cbuffer is effectively a top-level function.
844 continue;
845 }
846 VarDecl *VD = dyn_cast<VarDecl>(D);
847 if (!VD)
848 continue;
849
850 QualType VDTy = VD->getType();
852 if (VD->getStorageClass() == SC_Static ||
855 // Emit static and groupshared variables and resource classes inside
856 // cbuffer as regular globals
857 CGM.EmitGlobal(VD);
858 }
859 continue;
860 }
861
862 DeclsWithOffset.emplace_back(VD, OffsetInfo[OffsetIdx++]);
863 }
864
865 if (!OffsetInfo.empty())
866 llvm::stable_sort(DeclsWithOffset, [](const auto &LHS, const auto &RHS) {
867 return CGHLSLOffsetInfo::compareOffsets(LHS.second, RHS.second);
868 });
869
870 // Associate the buffer global variable with its constants
871 SmallVector<llvm::Metadata *> BufGlobals;
872 BufGlobals.reserve(DeclsWithOffset.size() + 1);
873 BufGlobals.push_back(ValueAsMetadata::get(BufGV));
874
875 auto ElemIt = LayoutStruct->element_begin();
876 for (auto &[VD, _] : DeclsWithOffset) {
877 if (CGM.getTargetCodeGenInfo().isHLSLPadding(*ElemIt))
878 ++ElemIt;
879
880 assert(ElemIt != LayoutStruct->element_end() &&
881 "number of elements in layout struct does not match");
882 llvm::Type *LayoutType = *ElemIt++;
883
884 GlobalVariable *ElemGV =
885 cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD, LayoutType));
886 BufGlobals.push_back(ValueAsMetadata::get(ElemGV));
887 }
888 assert(ElemIt == LayoutStruct->element_end() &&
889 "number of elements in layout struct does not match");
890
891 // add buffer metadata to the module
892 CGM.getModule()
893 .getOrInsertNamedMetadata("hlsl.cbs")
894 ->addOperand(MDNode::get(Ctx, BufGlobals));
895}
896
897// Creates resource handle type for the HLSL buffer declaration
898static const clang::HLSLAttributedResourceType *
900 ASTContext &AST = BufDecl->getASTContext();
902 AST.HLSLResourceTy, AST.getCanonicalTagType(BufDecl->getLayoutStruct()),
903 HLSLAttributedResourceType::Attributes(ResourceClass::CBuffer));
905}
906
909
910 // If we don't have packoffset info, just return an empty result.
911 if (!BufDecl.hasValidPackoffset())
912 return Result;
913
914 for (Decl *D : BufDecl.buffer_decls()) {
916 continue;
917 }
918 VarDecl *VD = dyn_cast<VarDecl>(D);
919 if (!VD || VD->getType().getAddressSpace() != LangAS::hlsl_constant)
920 continue;
921
922 if (!VD->hasAttrs()) {
923 Result.Offsets.push_back(Unspecified);
924 continue;
925 }
926
927 uint32_t Offset = Unspecified;
928 for (auto *Attr : VD->getAttrs()) {
929 if (auto *POA = dyn_cast<HLSLPackOffsetAttr>(Attr)) {
930 Offset = POA->getOffsetInBytes();
931 break;
932 }
933 auto *RBA = dyn_cast<HLSLResourceBindingAttr>(Attr);
934 if (RBA &&
935 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
936 Offset = RBA->getSlotNumber() * CBufferRowSizeInBytes;
937 break;
938 }
939 }
940 Result.Offsets.push_back(Offset);
941 }
942 return Result;
943}
944
945// Codegen for HLSLBufferDecl
947
948 assert(BufDecl->isCBuffer() && "tbuffer codegen is not supported yet");
949
950 // create resource handle type for the buffer
951 const clang::HLSLAttributedResourceType *ResHandleTy =
952 createBufferHandleType(BufDecl);
953
954 // empty constant buffer is ignored
955 if (ResHandleTy->getContainedType()->getAsCXXRecordDecl()->isEmpty())
956 return;
957
958 // create global variable for the constant buffer
959 CGHLSLOffsetInfo OffsetInfo = CGHLSLOffsetInfo::fromDecl(*BufDecl);
960 llvm::Type *LayoutTy = convertHLSLSpecificType(ResHandleTy, OffsetInfo);
961 llvm::GlobalVariable *BufGV = new GlobalVariable(
962 LayoutTy, /*isConstant*/ false,
963 GlobalValue::LinkageTypes::InternalLinkage, PoisonValue::get(LayoutTy),
964 llvm::formatv("{0}{1}", BufDecl->getName(),
965 BufDecl->isCBuffer() ? ".cb" : ".tb"),
966 GlobalValue::NotThreadLocal);
967
968 llvm::Module &M = CGM.getModule();
969 M.insertGlobalVariable(BufGV);
970
971 // Add the global variable to the compiler used list so it does not
972 // get optimized away by GlobalOptPass before it reaches
973 // {DXIL|SPIRV}CBufferAccess pass.
974 llvm::appendToCompilerUsed(M, {BufGV});
975
976 // Add globals for constant buffer elements and create metadata nodes
977 emitBufferGlobalsAndMetadata(BufDecl, BufGV, OffsetInfo);
978
979 // Initialize cbuffer from binding (implicit or explicit)
980 initializeBufferFromBinding(BufDecl, BufGV);
981}
982
984 const HLSLRootSignatureDecl *SignatureDecl) {
985 llvm::Module &M = CGM.getModule();
986 Triple T(M.getTargetTriple());
987
988 // Generated later with the function decl if not targeting root signature
989 if (T.getEnvironment() != Triple::EnvironmentType::RootSignature)
990 return;
991
992 addRootSignatureMD(SignatureDecl->getVersion(),
993 SignatureDecl->getRootElements(), nullptr, M);
994}
995
996llvm::StructType *
997CGHLSLRuntime::getHLSLBufferLayoutType(const RecordType *StructType) {
998 const auto Entry = LayoutTypes.find(StructType);
999 if (Entry != LayoutTypes.end())
1000 return Entry->getSecond();
1001 return nullptr;
1002}
1003
1004void CGHLSLRuntime::addHLSLBufferLayoutType(const RecordType *StructType,
1005 llvm::StructType *LayoutTy) {
1006 assert(getHLSLBufferLayoutType(StructType) == nullptr &&
1007 "layout type for this struct already exist");
1008 LayoutTypes[StructType] = LayoutTy;
1009}
1010
1012 llvm::Module &M = CGM.getModule();
1013 Function *QuadAll =
1014 Intrinsic::getDeclarationIfExists(&M, Intrinsic::spv_quad_all);
1015 if (!QuadAll)
1016 return;
1017
1018 SmallVector<Function *, 8> Worklist{QuadAll};
1020 IRBuilder<> B(M);
1021 while (!Worklist.empty()) {
1022 Function *F = Worklist.pop_back_val();
1023 if (!Visited.insert(F).second)
1024 continue;
1025
1026 Attribute NumThreadsAttr = F->getFnAttribute("hlsl.numthreads");
1027 if (NumThreadsAttr.isValid()) {
1028 std::array<uint32_t, 3> Threads;
1029 llvm::hlsl::parseThreadCounts(NumThreadsAttr.getValueAsString(),
1030 Threads[0], Threads[1], Threads[2]);
1031 bool IsLinear = Threads[1] == 1 && Threads[2] == 1;
1032 // QuadAll needs derivative groups for SPIR-V compute entry points.
1033 // Linear groups need complete sets of four threads. Quad groups need
1034 // complete 2-by-2 quads in the X and Y dimensions.
1035 bool InvalidThreads;
1036 SPIRVExecutionMode Mode;
1037 if (IsLinear) {
1038 InvalidThreads =
1039 (uint64_t(Threads[0]) * Threads[1] * Threads[2]) % 4 != 0;
1040 Mode = SPIRVExecutionMode::DerivativeGroupLinearKHR;
1041 } else {
1042 InvalidThreads = Threads[0] % 2 != 0 || Threads[1] % 2 != 0;
1043 Mode = SPIRVExecutionMode::DerivativeGroupQuadsKHR;
1044 }
1045 if (InvalidThreads) {
1046 CGM.getDiags().Report(diag::err_hlsl_spirv_derivative_group_numthreads)
1047 << F->getName() << IsLinear;
1048 CGM.getDiags().Report(
1049 diag::note_hlsl_spirv_derivative_group_requirement)
1050 << "QuadAll" << F->getName();
1051 continue;
1052 }
1053 MDNode *MD = MDNode::get(
1054 M.getContext(),
1055 {ValueAsMetadata::get(F),
1056 ConstantAsMetadata::get(B.getInt32(llvm::to_underlying(Mode)))});
1057 M.getOrInsertNamedMetadata("spirv.ExecutionMode")->addOperand(MD);
1058 }
1059
1060 for (User *U : F->users())
1061 if (auto *Call = dyn_cast<CallBase>(U))
1062 Worklist.push_back(Call->getFunction());
1063 }
1064}
1065
1067 auto &TargetOpts = CGM.getTarget().getTargetOpts();
1068 auto &CodeGenOpts = CGM.getCodeGenOpts();
1069 auto &LangOpts = CGM.getLangOpts();
1070 llvm::Module &M = CGM.getModule();
1071 Triple T(M.getTargetTriple());
1072 if (T.getArch() == Triple::ArchType::dxil)
1073 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
1074 if (!CodeGenOpts.DisableDXSourceMetadata &&
1075 CodeGenOpts.getDebugInfo() >=
1076 llvm::codegenoptions::DebugInfoKind::DebugInfoConstructor)
1077 addSourceInfo(CGM, M);
1078 if (CodeGenOpts.ResMayAlias)
1079 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error, "dx.resmayalias", 1);
1080 if (CodeGenOpts.AllResourcesBound)
1081 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error,
1082 "dx.allresourcesbound", 1);
1083 if (CodeGenOpts.OptimizationLevel == 0)
1084 M.addModuleFlag(llvm::Module::ModFlagBehavior::Override,
1085 "dx.disable_optimizations", 1);
1086
1087 // NativeHalfType corresponds to the -fnative-half-type clang option which is
1088 // aliased by clang-dxc's -enable-16bit-types option. This option is used to
1089 // set the UseNativeLowPrecision DXIL module flag in the DirectX backend
1090 if (LangOpts.NativeHalfType)
1091 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error, "dx.nativelowprec",
1092 1);
1093
1094 if (LangOpts.HLSLSpvPreserveInterface && T.isSPIRV()) {
1095 // Runs before optimization. Keeps Input/Output globals from GlobalDCE.
1096 const ASTContext &Ctx = CGM.getContext();
1097 unsigned InputAS = Ctx.getTargetAddressSpace(LangAS::hlsl_input);
1098 unsigned OutputAS = Ctx.getTargetAddressSpace(LangAS::hlsl_output);
1099 SmallVector<GlobalValue *, 8> InterfaceVars;
1100 for (GlobalVariable &GV : M.globals()) {
1101 unsigned AS = GV.getAddressSpace();
1102 if (AS == InputAS || AS == OutputAS)
1103 InterfaceVars.push_back(&GV);
1104 }
1105 if (!InterfaceVars.empty())
1106 appendToCompilerUsed(M, InterfaceVars);
1107 }
1108
1110 if (T.isSPIRV())
1112}
1113
1115 const FunctionDecl *FD, llvm::Function *Fn) {
1116 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
1117 assert(ShaderAttr && "All entry functions must have a HLSLShaderAttr");
1118 const StringRef ShaderAttrKindStr = "hlsl.shader";
1119 Fn->addFnAttr(ShaderAttrKindStr,
1120 llvm::Triple::getEnvironmentTypeName(ShaderAttr->getType()));
1121 if (HLSLNumThreadsAttr *NumThreadsAttr = FD->getAttr<HLSLNumThreadsAttr>()) {
1122 const StringRef NumThreadsKindStr = "hlsl.numthreads";
1123 std::string NumThreadsStr =
1124 formatv("{0},{1},{2}", NumThreadsAttr->getX(), NumThreadsAttr->getY(),
1125 NumThreadsAttr->getZ());
1126 Fn->addFnAttr(NumThreadsKindStr, NumThreadsStr);
1127 }
1128 if (HLSLWaveSizeAttr *WaveSizeAttr = FD->getAttr<HLSLWaveSizeAttr>()) {
1129 const StringRef WaveSizeKindStr = "hlsl.wavesize";
1130 std::string WaveSizeStr =
1131 formatv("{0},{1},{2}", WaveSizeAttr->getMin(), WaveSizeAttr->getMax(),
1132 WaveSizeAttr->getPreferred());
1133 Fn->addFnAttr(WaveSizeKindStr, WaveSizeStr);
1134 }
1135 // HLSL entry functions are materialized for module functions with
1136 // HLSLShaderAttr attribute. SetLLVMFunctionAttributesForDefinition called
1137 // later in the compiler-flow for such module functions is not aware of and
1138 // hence not able to set attributes of the newly materialized entry functions.
1139 // So, set attributes of entry function here, as appropriate.
1140 Fn->addFnAttr(llvm::Attribute::NoInline);
1141
1142 if (CGM.getLangOpts().HLSLSpvEnableMaximalReconvergence) {
1143 Fn->addFnAttr("enable-maximal-reconvergence", "true");
1144 }
1145}
1146
1147static Value *buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty) {
1148 // Compute ID intrinsics return i32 components, but the semantic may use
1149 // 16-bit integers. Narrow each component before assembling the input.
1150 if (const auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1151 Value *Result = PoisonValue::get(Ty);
1152 for (unsigned I = 0; I < VT->getNumElements(); ++I) {
1153 Value *Elt = B.CreateCall(F, {B.getInt32(I)});
1154 Elt = B.CreateTrunc(Elt, VT->getElementType());
1155 Result = B.CreateInsertElement(Result, Elt, I);
1156 }
1157 return Result;
1158 }
1159 return B.CreateTrunc(B.CreateCall(F, {B.getInt32(0)}), Ty);
1160}
1161
1162// A fragment shader input interface variable whose base type is an integer or
1163// a 64-bit float (double) cannot be interpolated by the rasterizer. The Vulkan
1164// specification requires these variables to be decorated with Flat (see
1165// VUID-StandaloneSpirv-Flat-04744). Arrays and vectors are unwrapped to inspect
1166// their base scalar type.
1167static bool requiresFlatInterpolation(llvm::Type *Ty) {
1168 while (true) {
1169 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty)) {
1170 Ty = AT->getElementType();
1171 continue;
1172 }
1173 if (auto *VT = dyn_cast<llvm::FixedVectorType>(Ty)) {
1174 Ty = VT->getElementType();
1175 continue;
1176 }
1177 break;
1178 }
1179 return Ty->isIntegerTy() || Ty->isDoubleTy();
1180}
1181
1182static llvm::hlsl::InterpolationMode
1183getSPIRVInterpolationMode(llvm::hlsl::InterpolationMode InterpMode,
1184 llvm::Type *Ty, llvm::Triple::EnvironmentType Stage,
1185 llvm::hlsl::IOType IO) {
1186 using llvm::hlsl::InterpolationMode;
1187 if (!((Stage == llvm::Triple::Pixel && IO == llvm::hlsl::IOType::In) ||
1188 (Stage == llvm::Triple::Vertex && IO == llvm::hlsl::IOType::Out)))
1189 return InterpolationMode::Undefined;
1190 if (InterpMode == InterpolationMode::Undefined &&
1192 return InterpolationMode::Constant;
1193 return InterpMode;
1194}
1195
1196static void
1197addSPIRVInterfaceDecorations(llvm::GlobalVariable *GV,
1198 llvm::hlsl::SPIRVInterfaceDecoration Decoration,
1199 unsigned Operand,
1200 llvm::hlsl::InterpolationMode InterpMode =
1201 llvm::hlsl::InterpolationMode::Undefined) {
1202 using llvm::hlsl::InterpolationMode;
1203 using llvm::hlsl::SPIRVInterpolationMode;
1204
1205 LLVMContext &Ctx = GV->getContext();
1206 IRBuilder<> B(*GV->getParent());
1207 SmallVector<Metadata *, 3> Decorations;
1208 Decorations.push_back(MDNode::get(
1209 Ctx,
1210 {ConstantAsMetadata::get(B.getInt32(llvm::to_underlying(Decoration))),
1211 ConstantAsMetadata::get(B.getInt32(Operand))}));
1212 auto Add = [&](SPIRVInterpolationMode InterpolationDecoration) {
1213 Decorations.push_back(
1214 MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(
1215 llvm::to_underlying(InterpolationDecoration)))}));
1216 };
1217 switch (InterpMode) {
1218 case InterpolationMode::Undefined:
1219 case InterpolationMode::Linear:
1220 break;
1221 case InterpolationMode::Constant:
1222 Add(SPIRVInterpolationMode::Flat);
1223 break;
1224 case InterpolationMode::LinearNoperspective:
1225 Add(SPIRVInterpolationMode::NoPerspective);
1226 break;
1227 case InterpolationMode::LinearNoperspectiveCentroid:
1228 Add(SPIRVInterpolationMode::NoPerspective);
1229 [[fallthrough]];
1230 case InterpolationMode::LinearCentroid:
1231 Add(SPIRVInterpolationMode::Centroid);
1232 break;
1233 case InterpolationMode::LinearNoperspectiveSample:
1234 Add(SPIRVInterpolationMode::NoPerspective);
1235 [[fallthrough]];
1236 case InterpolationMode::LinearSample:
1237 Add(SPIRVInterpolationMode::Sample);
1238 break;
1239 default:
1240 llvm_unreachable("invalid interpolation mode");
1241 }
1242 // The backend consumes one decoration list per global, including both the
1243 // Location or BuiltIn and any interpolation decorations.
1244 GV->addMetadata("spirv.Decorations", *MDNode::get(Ctx, Decorations));
1245}
1246
1247static llvm::Value *createSPIRVInputLoad(
1248 IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty, const Twine &Name,
1249 llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand,
1250 llvm::hlsl::InterpolationMode InterpMode) {
1251 // SPIR-V integer built-ins are 32-bit, so a narrower integer declaration
1252 // loads the 32-bit built-in and truncates it. Other types are loaded as is.
1253 // i1 is excluded: bool built-ins such as FrontFacing are OpTypeBool.
1254 bool Truncate = Decoration == llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn &&
1255 Ty->isIntegerTy() && Ty->getIntegerBitWidth() > 1 &&
1256 Ty->getIntegerBitWidth() < 32;
1257 llvm::Type *LoadTy = Truncate ? B.getInt32Ty() : Ty;
1258 auto *GV = new llvm::GlobalVariable(
1259 M, LoadTy, /* isConstant= */ true, llvm::GlobalValue::ExternalLinkage,
1260 /* Initializer= */ nullptr, Name, /* insertBefore= */ nullptr,
1261 llvm::GlobalVariable::GeneralDynamicTLSModel,
1262 /* AddressSpace */ 7, /* isExternallyInitialized= */ true);
1263 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1264 addSPIRVInterfaceDecorations(GV, Decoration, Operand, InterpMode);
1265 llvm::Value *Value = B.CreateLoad(LoadTy, GV);
1266 return Truncate ? B.CreateTrunc(Value, Ty) : Value;
1267}
1268
1269// For Vulkan builtins which begin counting from a driver-supplied base offset,
1270// where the corresponding HLSL system value is always zero-based within the
1271// current draw call.
1272static llvm::Value *
1273createSPIRVBuiltinDelta(IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty,
1274 const Twine &Name, unsigned BuiltInID,
1275 unsigned BaseBuiltInID,
1276 llvm::hlsl::InterpolationMode InterpMode) {
1277 llvm::Value *Value = createSPIRVInputLoad(
1278 B, M, Ty, Name, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, BuiltInID,
1279 InterpMode);
1280 llvm::Value *Base = createSPIRVInputLoad(
1281 B, M, Ty, Name + Twine(".base"),
1282 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, BaseBuiltInID, InterpMode);
1283 return B.CreateSub(Value, Base);
1284}
1285
1286llvm::Value *CGHLSLRuntime::emitSPIRVUserSemanticLoad(
1287 llvm::IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl,
1288 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1289 llvm::hlsl::InterpolationMode InterpMode) {
1290 Twine BaseName = Twine(Semantic->getAttrName()->getName());
1291 Twine VariableName = BaseName.concat(Twine(Index.value_or(0)));
1292
1293 unsigned Location = SPIRVLastAssignedInputSemanticLocation;
1294 if (auto *L = Decl->getAttr<HLSLVkLocationAttr>())
1295 Location = L->getLocation();
1296
1297 // DXC completely ignores the semantic/index pair. Location are assigned from
1298 // the first semantic to the last.
1299 llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Type);
1300 unsigned ElementCount = AT ? AT->getNumElements() : 1;
1301 SPIRVLastAssignedInputSemanticLocation += ElementCount;
1302
1303 return createSPIRVInputLoad(B, CGM.getModule(), Type, VariableName.str(),
1304 llvm::hlsl::SPIRVInterfaceDecoration::Location,
1305 Location, InterpMode);
1306}
1307
1309 IRBuilder<> &B, llvm::Module &M, llvm::Value *Source, const Twine &Name,
1310 llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand,
1311 llvm::hlsl::InterpolationMode InterpMode, bool IsSigned = false) {
1312 // Integer built-ins are 32-bit scalars in Vulkan. Narrower HLSL
1313 // declarations are extended before they are written to the built-in.
1314 llvm::Type *Ty = Source->getType();
1315 if (Decoration == llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn &&
1316 Ty->isIntegerTy() && Ty->getIntegerBitWidth() < 32)
1317 Source = IsSigned ? B.CreateSExt(Source, B.getInt32Ty())
1318 : B.CreateZExt(Source, B.getInt32Ty());
1319 auto *GV = new llvm::GlobalVariable(
1320 M, Source->getType(), /* isConstant= */ false,
1321 llvm::GlobalValue::ExternalLinkage,
1322 /* Initializer= */ nullptr, Name, /* insertBefore= */ nullptr,
1323 llvm::GlobalVariable::GeneralDynamicTLSModel,
1324 /* AddressSpace */ 8, /* isExternallyInitialized= */ false);
1325 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1326 addSPIRVInterfaceDecorations(GV, Decoration, Operand, InterpMode);
1327 B.CreateStore(Source, GV);
1328}
1329
1330void CGHLSLRuntime::emitSPIRVUserSemanticStore(
1331 llvm::IRBuilder<> &B, llvm::Value *Source,
1332 const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic,
1333 std::optional<unsigned> Index, llvm::hlsl::InterpolationMode InterpMode,
1334 bool UseLocationFromIndex) {
1335 Twine BaseName = Twine(Semantic->getAttrName()->getName());
1336 Twine VariableName = BaseName.concat(Twine(Index.value_or(0)));
1337
1338 unsigned Location;
1339 if (UseLocationFromIndex) {
1340 Location = Index.value_or(0);
1341 } else {
1342 Location = SPIRVLastAssignedOutputSemanticLocation;
1343 llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Source->getType());
1344 // In the case of an array, locations are assigned from the first semantic
1345 // to the last.
1346 SPIRVLastAssignedOutputSemanticLocation += AT ? AT->getNumElements() : 1;
1347 }
1348 if (auto *L = Decl->getAttr<HLSLVkLocationAttr>())
1349 Location = L->getLocation();
1350
1351 createSPIRVOutputStore(B, CGM.getModule(), Source, VariableName.str(),
1352 llvm::hlsl::SPIRVInterfaceDecoration::Location,
1353 Location, InterpMode);
1354}
1355
1356namespace {
1357// Describes how a semantic leaf lowers to signature rows
1358struct SemanticShape {
1359 // Array length followed by matrix major-axis length.
1360 SmallVector<unsigned> Dimensions;
1361 unsigned Cols;
1362 QualType RowType;
1363 bool IsMatrix = false;
1364 bool IsRowMajor = false;
1365
1366 // Direct matrix arguments/results use column-major flattened vectors even
1367 // when their signature (and aggregate memory representation) is row-major.
1368 unsigned getMatrixElementIndex(unsigned Row, unsigned Col) const {
1369 assert(IsMatrix);
1370 unsigned MatrixRow = Row % Dimensions.back();
1371 return IsRowMajor ? Col * Dimensions.back() + MatrixRow
1372 : MatrixRow * Cols + Col;
1373 }
1374
1375 unsigned getNumRows() const {
1376 unsigned Rows = 1;
1377 for (unsigned Dimension : Dimensions)
1378 Rows *= Dimension;
1379 return Rows;
1380 }
1381
1382 SmallVector<unsigned> getArrayIndicesForRow(unsigned Row) const {
1383 assert(Row < getNumRows() && "row exceeds semantic shape");
1384
1385 SmallVector<unsigned> Indices(Dimensions.size());
1386 for (auto [Index, Dimension] :
1387 llvm::zip_equal(llvm::reverse(Indices), llvm::reverse(Dimensions))) {
1388 Index = Row % Dimension;
1389 Row /= Dimension;
1390 }
1391 return Indices;
1392 }
1393};
1394} // namespace
1395
1396// Returns the QualType of a semantic leaf declarator. For a function the
1397// declared return type is used, otherwise the declared type.
1399 if (const auto *FD = dyn_cast<clang::FunctionDecl>(Decl))
1400 return FD->getDeclaredReturnType();
1401 return Decl->getType();
1402}
1403
1404// Collects array dimensions and, for a matrix leaf, its major-axis dimension.
1405// RowType is the scalar or vector transferred by each signature load/store.
1406static SemanticShape getSemanticShape(ASTContext &Ctx, QualType Ty) {
1407 SemanticShape Shape{{}, 1, Ty};
1408 while (const ConstantArrayType *CAT =
1409 Ctx.getAsConstantArrayType(Shape.RowType)) {
1410 Shape.Dimensions.push_back(CAT->getSize().getZExtValue());
1411 Shape.RowType = CAT->getElementType();
1412 }
1413
1414 if (const auto *VT = Shape.RowType->getAs<clang::VectorType>()) {
1415 Shape.Cols = VT->getNumElements();
1416 } else if (const auto *MT =
1417 Shape.RowType->getAs<clang::ConstantMatrixType>()) {
1418 Shape.IsMatrix = true;
1419 Shape.IsRowMajor = isMatrixRowMajor(Ctx.getLangOpts(), Shape.RowType);
1420 Shape.Dimensions.push_back(Shape.IsRowMajor ? MT->getNumRows()
1421 : MT->getNumColumns());
1422 Shape.Cols = Shape.IsRowMajor ? MT->getNumColumns() : MT->getNumRows();
1423 Shape.RowType = Ctx.getExtVectorType(MT->getElementType(), Shape.Cols);
1424 }
1425
1426 return Shape;
1427}
1428
1429static llvm::dxil::ElementType getSignatureComponentType(CodeGenModule &CGM,
1430 QualType Ty) {
1431 if (const auto *VT = Ty->getAs<clang::VectorType>())
1432 Ty = VT->getElementType();
1433
1434 llvm::Type *IRTy = CGM.getTypes().ConvertTypeForMem(Ty);
1435 bool IsSigned = Ty->isSignedIntegerOrEnumerationType();
1436 return llvm::hlsl::getDXILElementType(IRTy, IsSigned);
1437}
1438
1439static llvm::hlsl::SemanticSignatureElement createSemanticSignatureElement(
1440 CodeGenModule &CGM, uint32_t SigId, HLSLAppliedSemanticAttr *Semantic,
1441 std::optional<unsigned> Index, const SemanticShape &Shape) {
1442 StringRef Name = Semantic->getAttrName()->getName();
1443
1444 // One semantic index per row, starting from the declared index.
1445 SmallVector<uint32_t> SemanticIndices;
1446 uint32_t FirstSemanticIndex = Index.value_or(0);
1447 for (uint32_t I = 0, E = Shape.getNumRows(); I < E; ++I)
1448 SemanticIndices.push_back(FirstSemanticIndex + I);
1449
1450 llvm::dxbc::PSV::SemanticKind Kind = llvm::hlsl::getSemanticKind(Name);
1451 llvm::dxil::ElementType CompType =
1452 getSignatureComponentType(CGM, Shape.RowType);
1453 // SV_SampleIndex and SV_PrimitiveID may be declared as int or uint, as in
1454 // DXC. Both are indices generated by the system, so they are never negative
1455 // and a signed declaration reads the same value. DXIL signatures require an
1456 // unsigned component type.
1457 if (Kind == llvm::dxbc::PSV::SemanticKind::SampleIndex ||
1458 Kind == llvm::dxbc::PSV::SemanticKind::PrimitiveID ||
1459 Kind == llvm::dxbc::PSV::SemanticKind::StencilRef) {
1460 if (CompType == llvm::dxil::ElementType::I16)
1461 CompType = llvm::dxil::ElementType::U16;
1462 else if (CompType == llvm::dxil::ElementType::I32)
1463 CompType = llvm::dxil::ElementType::U32;
1464 }
1465
1466 // The remaining members keep their default value and will be filled at a
1467 // later stage, either during packing or analysis of usage. Interpolation
1468 // is set by the load/store traversal after visiting each leaf.
1469 return llvm::hlsl::SemanticSignatureElement(SigId, Name, CompType, Kind,
1470 SemanticIndices,
1471 static_cast<uint8_t>(Shape.Cols));
1472}
1473
1474llvm::Value *CGHLSLRuntime::emitDXILUserSemanticLoad(
1475 llvm::IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl,
1476 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1477 SemanticSignatures &Signature) {
1478 StringRef Name = Semantic->getAttrName()->getName();
1479 SemanticShape Shape =
1481
1482 uint32_t SigId = Signature.size();
1483 Signature.push_back(
1484 createSemanticSignatureElement(CGM, SigId, Semantic, Index, Shape));
1485
1486 llvm::Type *RowTy = CGM.getTypes().ConvertTypeForMem(Shape.RowType);
1487
1488 llvm::Function *IntrFn = llvm::Intrinsic::getOrInsertDeclaration(
1489 B.getModule(), llvm::Intrinsic::dx_load_input, {RowTy});
1490
1491 SmallVector<OperandBundleDef, 1> OB;
1492 if (auto *Token = getConvergenceToken(*B.GetInsertBlock())) {
1493 llvm::Value *bundleArgs[] = {Token};
1494 OB.emplace_back("convergencectrl", bundleArgs);
1495 }
1496
1497 bool IsMatrixValue = Shape.IsMatrix && Type->isVectorTy();
1498 llvm::Type *LeafTy = Shape.IsMatrix && !IsMatrixValue
1499 ? RowTy
1500 : CGM.getTypes().ConvertType(Shape.RowType);
1501 llvm::Value *Result = llvm::PoisonValue::get(Type);
1502
1503 const unsigned NumRows = Shape.getNumRows();
1504
1505 for (unsigned Row = 0; Row < NumRows; ++Row) {
1506 std::array<Value *, 4> Args{
1507 /*SigElementId=*/B.getInt32(SigId),
1508 /*RowIndex=*/B.getInt32(Row),
1509 /*ColIndex=*/B.getInt8(0),
1510 /*GsVertexOrPrimIndex=*/llvm::PoisonValue::get(B.getInt32Ty())};
1511 llvm::Value *Value =
1512 B.CreateCall(IntrFn, Args, OB, Twine(Name).concat(Twine(Row)));
1513 // Booleans use their memory representation in DXIL signatures, but
1514 // function parameters use their value representation.
1515 if (Value->getType() != LeafTy) {
1516 assert(Shape.RowType->hasBooleanRepresentation() &&
1517 "unexpected semantic load type mismatch");
1518 Value = B.CreateICmpNE(
1519 Value, llvm::Constant::getNullValue(Value->getType()), "loadedv");
1520 }
1521
1522 if (IsMatrixValue) {
1523 for (unsigned Col = 0; Col < Shape.Cols; ++Col)
1524 Result =
1525 B.CreateInsertElement(Result, B.CreateExtractElement(Value, Col),
1526 Shape.getMatrixElementIndex(Row, Col));
1527 } else {
1528 SmallVector<unsigned> Indices = Shape.getArrayIndicesForRow(Row);
1529 Result =
1530 Indices.empty() ? Value : B.CreateInsertValue(Result, Value, Indices);
1531 }
1532 }
1533 return Result;
1534}
1535
1536void CGHLSLRuntime::emitDXILUserSemanticStore(llvm::IRBuilder<> &B,
1537 llvm::Value *Source,
1538 const clang::DeclaratorDecl *Decl,
1539 HLSLAppliedSemanticAttr *Semantic,
1540 std::optional<unsigned> Index,
1541 SemanticSignatures &Signature,
1542 bool EnforceOneElementPerRow) {
1543 SemanticShape Shape =
1545 assert(!(EnforceOneElementPerRow && Shape.IsMatrix) &&
1546 "matrices cannot be split into one element per row");
1547
1548 // DXIL pixel shader outputs are not indexable, and each render target must
1549 // be in the signature row of its semantic index. An SV_Target array is
1550 // therefore split into one single-row element per render target.
1551 SemanticShape RowShape{{}, Shape.Cols, Shape.RowType};
1552 uint32_t FirstSigId = Signature.size();
1553 if (!EnforceOneElementPerRow)
1554 Signature.push_back(createSemanticSignatureElement(CGM, FirstSigId,
1555 Semantic, Index, Shape));
1556
1557 llvm::Type *RowTy = CGM.getTypes().ConvertTypeForMem(Shape.RowType);
1558
1559 llvm::Function *IntrFn = llvm::Intrinsic::getOrInsertDeclaration(
1560 B.getModule(), llvm::Intrinsic::dx_store_output, {RowTy});
1561
1562 SmallVector<OperandBundleDef, 1> OB;
1563 if (auto *Token = getConvergenceToken(*B.GetInsertBlock())) {
1564 llvm::Value *bundleArgs[] = {Token};
1565 OB.emplace_back("convergencectrl", bundleArgs);
1566 }
1567
1568 bool IsMatrixValue = Shape.IsMatrix && Source->getType()->isVectorTy();
1569 const unsigned NumRows = Shape.getNumRows();
1570 for (unsigned Row = 0; Row < NumRows; ++Row) {
1571 llvm::Value *Val;
1572 if (IsMatrixValue) {
1573 SmallVector<int, 4> Mask;
1574 for (unsigned Col = 0; Col < Shape.Cols; ++Col)
1575 Mask.push_back(Shape.getMatrixElementIndex(Row, Col));
1576 Val = B.CreateShuffleVector(Source, Mask);
1577 } else {
1578 SmallVector<unsigned> Indices = Shape.getArrayIndicesForRow(Row);
1579 Val = Indices.empty() ? Source : B.CreateExtractValue(Source, Indices);
1580 }
1581
1582 // Booleans use their memory representation in DXIL signatures, but direct
1583 // function results use their value representation.
1584 if (Val->getType() != RowTy) {
1585 assert(Shape.RowType->hasBooleanRepresentation() &&
1586 "unexpected semantic store type mismatch");
1587 Val = B.CreateZExt(Val, RowTy, "storedv");
1588 }
1589
1590 uint32_t SigId = FirstSigId;
1591 uint32_t SigRow = Row;
1592 if (EnforceOneElementPerRow) {
1593 SigId = Signature.size();
1594 SigRow = 0;
1595 Signature.push_back(createSemanticSignatureElement(
1596 CGM, SigId, Semantic, Index.value_or(0) + Row, RowShape));
1597 }
1598
1599 std::array<Value *, 4> Args{/*SigElementId=*/B.getInt32(SigId),
1600 /*RowIndex=*/B.getInt32(SigRow),
1601 /*ColIndex=*/B.getInt8(0), /*Value=*/Val};
1602 B.CreateCall(IntrFn, Args, OB);
1603 }
1604}
1605
1606llvm::Value *CGHLSLRuntime::emitUserSemanticLoad(
1607 IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl,
1608 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1609 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1610 if (CGM.getTarget().getTriple().isSPIRV())
1611 return emitSPIRVUserSemanticLoad(B, Type, Decl, Semantic, Index,
1612 InterpMode);
1613
1614 if (CGM.getTarget().getTriple().isDXIL())
1615 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index, Signature);
1616
1617 llvm_unreachable("Unsupported target for user-semantic load.");
1618}
1619
1620void CGHLSLRuntime::emitUserSemanticStore(
1621 IRBuilder<> &B, llvm::Value *Source, const clang::DeclaratorDecl *Decl,
1622 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1623 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1624 if (CGM.getTarget().getTriple().isSPIRV())
1625 return emitSPIRVUserSemanticStore(B, Source, Decl, Semantic, Index,
1626 InterpMode);
1627
1628 if (CGM.getTarget().getTriple().isDXIL())
1629 return emitDXILUserSemanticStore(B, Source, Decl, Semantic, Index,
1630 Signature);
1631
1632 llvm_unreachable("Unsupported target for user-semantic load.");
1633}
1634
1636 IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl,
1637 HLSLAppliedSemanticAttr *Semantic,
1638 llvm::dxbc::PSV::SemanticKind SemanticKind,
1639 llvm::Triple::EnvironmentType Stage, std::optional<unsigned> Index,
1640 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1641 switch (SemanticKind) {
1642 case llvm::dxbc::PSV::SemanticKind::Barycentrics:
1643 assert(Stage == llvm::Triple::Pixel &&
1644 "SV_Barycentrics is in an unavailable stage and should have been "
1645 "diagnosed by Sema");
1646 if (CGM.getTarget().getTriple().isSPIRV()) {
1647 using llvm::hlsl::InterpolationMode;
1648 // Perspective is encoded by the built-in; only sampling decorations
1649 // belong on the interface variable.
1650 bool NoPerspective = false;
1651 switch (InterpMode) {
1652 case InterpolationMode::LinearNoperspective:
1653 NoPerspective = true;
1654 InterpMode = InterpolationMode::Linear;
1655 break;
1656 case InterpolationMode::LinearNoperspectiveCentroid:
1657 NoPerspective = true;
1658 InterpMode = InterpolationMode::LinearCentroid;
1659 break;
1660 case InterpolationMode::LinearNoperspectiveSample:
1661 NoPerspective = true;
1662 InterpMode = InterpolationMode::LinearSample;
1663 break;
1664 default:
1665 break;
1666 }
1667 // SPIR-V barycentric built-ins are float3, even for half3 inputs.
1668 llvm::Type *BuiltinType = llvm::FixedVectorType::get(CGM.FloatTy, 3);
1669 llvm::Value *Barycentrics = createSPIRVInputLoad(
1670 B, CGM.getModule(), BuiltinType, Semantic->getSemanticName(),
1671 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1672 NoPerspective ? /* BuiltIn::BaryCoordNoPerspKHR */ 5287
1673 : /* BuiltIn::BaryCoordKHR */ 5286,
1674 InterpMode);
1675 if (Type->getScalarType()->isHalfTy())
1676 return B.CreateFPTrunc(Barycentrics, Type);
1677 return Barycentrics;
1678 }
1679 if (CGM.getTarget().getTriple().isDXIL())
1680 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1681 Signature);
1682 break;
1683 case llvm::dxbc::PSV::SemanticKind::GroupIndex: {
1684 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1685 llvm::Triple::Amplification},
1686 Stage) &&
1687 "SV_GroupIndex is in an unavailable stage and should have been "
1688 "diagnosed by Sema");
1689 assert(Stage != llvm::Triple::Mesh &&
1690 Stage != llvm::Triple::Amplification &&
1691 "FIXME: SV_GroupIndex is not yet implemented for this shader "
1692 "stage");
1693 llvm::Function *GroupIndex =
1694 CGM.getIntrinsic(getFlattenedThreadIdInGroupIntrinsic());
1695 return B.CreateCall(FunctionCallee(GroupIndex));
1696 }
1697 case llvm::dxbc::PSV::SemanticKind::DispatchThreadID: {
1698 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1699 llvm::Triple::Amplification},
1700 Stage) &&
1701 "SV_DispatchThreadID is in an unavailable stage and should have "
1702 "been diagnosed by Sema");
1703 assert(Stage != llvm::Triple::Mesh &&
1704 Stage != llvm::Triple::Amplification &&
1705 "FIXME: SV_DispatchThreadID is not yet implemented for this "
1706 "shader stage");
1707 llvm::Intrinsic::ID IntrinID = getThreadIdIntrinsic();
1708 llvm::Function *ThreadIDIntrinsic =
1709 llvm::Intrinsic::isOverloaded(IntrinID)
1710 ? CGM.getIntrinsic(IntrinID, {CGM.Int32Ty})
1711 : CGM.getIntrinsic(IntrinID);
1712 return buildVectorInput(B, ThreadIDIntrinsic, Type);
1713 }
1714 case llvm::dxbc::PSV::SemanticKind::GroupThreadID: {
1715 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1716 llvm::Triple::Amplification},
1717 Stage) &&
1718 "SV_GroupThreadID is in an unavailable stage and should have been "
1719 "diagnosed by Sema");
1720 assert(Stage != llvm::Triple::Mesh &&
1721 Stage != llvm::Triple::Amplification &&
1722 "FIXME: SV_GroupThreadID is not yet implemented for this shader "
1723 "stage");
1724 llvm::Intrinsic::ID IntrinID = getGroupThreadIdIntrinsic();
1725 llvm::Function *GroupThreadIDIntrinsic =
1726 llvm::Intrinsic::isOverloaded(IntrinID)
1727 ? CGM.getIntrinsic(IntrinID, {CGM.Int32Ty})
1728 : CGM.getIntrinsic(IntrinID);
1729 return buildVectorInput(B, GroupThreadIDIntrinsic, Type);
1730 }
1731 case llvm::dxbc::PSV::SemanticKind::GroupID: {
1732 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1733 llvm::Triple::Amplification},
1734 Stage) &&
1735 "SV_GroupID is in an unavailable stage and should have been "
1736 "diagnosed by Sema");
1737 assert(Stage != llvm::Triple::Mesh &&
1738 Stage != llvm::Triple::Amplification &&
1739 "FIXME: SV_GroupID is not yet implemented for this shader stage");
1740 llvm::Intrinsic::ID IntrinID = getGroupIdIntrinsic();
1741 llvm::Function *GroupIDIntrinsic =
1742 llvm::Intrinsic::isOverloaded(IntrinID)
1743 ? CGM.getIntrinsic(IntrinID, {CGM.Int32Ty})
1744 : CGM.getIntrinsic(IntrinID);
1745 return buildVectorInput(B, GroupIDIntrinsic, Type);
1746 }
1747 case llvm::dxbc::PSV::SemanticKind::Position:
1748 assert(llvm::is_contained({llvm::Triple::Hull, llvm::Triple::Domain,
1749 llvm::Triple::Geometry, llvm::Triple::Pixel},
1750 Stage) &&
1751 "SV_Position is in an unavailable stage and should have been "
1752 "diagnosed by Sema");
1753 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1754 Stage != llvm::Triple::Geometry &&
1755 "FIXME: loading SV_Position is not yet implemented for this "
1756 "shader stage");
1757 if (CGM.getTarget().getTriple().isSPIRV())
1758 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1759 Semantic->getAttrName()->getName(),
1760 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1761 /* FragCoord */ 15, InterpMode);
1762 if (CGM.getTarget().getTriple().isDXIL())
1763 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1764 Signature);
1765 break;
1766 case llvm::dxbc::PSV::SemanticKind::VertexID:
1767 assert(Stage == llvm::Triple::Vertex &&
1768 "SV_VertexID is in an unavailable stage and should have been "
1769 "diagnosed by Sema");
1770 if (CGM.getTarget().getTriple().isSPIRV())
1771 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1772 Semantic->getAttrName()->getName(),
1773 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1774 /* VertexIndex */ 42, InterpMode);
1775 if (CGM.getTarget().getTriple().isDXIL())
1776 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1777 Signature);
1778 break;
1779 case llvm::dxbc::PSV::SemanticKind::InstanceID:
1780 assert(Stage == llvm::Triple::Vertex &&
1781 "SV_InstanceID is in an unavailable stage and should have been "
1782 "diagnosed by Sema");
1783 if (CGM.getTarget().getTriple().isSPIRV()) {
1784 // Matches DXC: only subtract BaseInstance when
1785 // -fvk-support-nonzero-base-instance is given.
1786 if (CGM.getLangOpts().HLSLSpvSupportNonzeroBaseInstance)
1788 B, CGM.getModule(), Type, Semantic->getAttrName()->getName(),
1789 /* InstanceIndex */ 43, /* BaseInstance */ 4425, InterpMode);
1790 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1791 Semantic->getAttrName()->getName(),
1792 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1793 /* InstanceIndex */ 43, InterpMode);
1794 }
1795 if (CGM.getTarget().getTriple().isDXIL())
1796 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1797 Signature);
1798 break;
1799 case llvm::dxbc::PSV::SemanticKind::IsFrontFace:
1800 assert(Stage == llvm::Triple::Pixel &&
1801 "SV_IsFrontFace is in an unavailable stage and should have been "
1802 "diagnosed by Sema");
1803 if (CGM.getTarget().getTriple().isSPIRV()) {
1804 // The FrontFacing BuiltIn is always a bool in SPIR-V, whatever type the
1805 // entry point declares. Load it as bool, then convert below.
1806 llvm::Type *BoolTy = B.getInt1Ty();
1807 // Integer pixel inputs cannot be interpolated and must be Flat.
1808 llvm::Value *FF = createSPIRVInputLoad(
1809 B, CGM.getModule(), BoolTy, Semantic->getAttrName()->getName(),
1810 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1811 /* FrontFacing */ 17, llvm::hlsl::InterpolationMode::Constant);
1812 // Convert to the declared parameter type (eg uint).
1813 return Type == BoolTy ? FF : B.CreateZExt(FF, Type);
1814 }
1815 if (CGM.getTarget().getTriple().isDXIL())
1816 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1817 Signature);
1818 break;
1819 case llvm::dxbc::PSV::SemanticKind::ShadingRate:
1820 assert(llvm::is_contained({llvm::Triple::Hull, llvm::Triple::Domain,
1821 llvm::Triple::Geometry, llvm::Triple::Pixel},
1822 Stage) &&
1823 "SV_ShadingRate is in an unavailable stage and should have been "
1824 "diagnosed by Sema");
1825 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1826 Stage != llvm::Triple::Geometry &&
1827 "FIXME: loading SV_ShadingRate is not yet implemented for this "
1828 "shader stage");
1829 if (CGM.getTarget().getTriple().isSPIRV())
1830 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1831 Semantic->getAttrName()->getName(),
1832 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1833 /* ShadingRateKHR */ 4444, InterpMode);
1834 if (CGM.getTarget().getTriple().isDXIL())
1835 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1836 Signature);
1837 break;
1838 case llvm::dxbc::PSV::SemanticKind::StartVertexLocation:
1839 assert(Stage == llvm::Triple::Vertex &&
1840 "SV_StartVertexLocation is in an unavailable stage and should have "
1841 "been diagnosed by Sema");
1842 if (CGM.getTarget().getTriple().isSPIRV())
1843 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1844 Semantic->getAttrName()->getName(),
1845 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1846 /* BaseVertex */ 4424, InterpMode);
1847 if (CGM.getTarget().getTriple().isDXIL())
1848 return B.CreateCall(
1849 CGM.getIntrinsic(llvm::Intrinsic::dx_start_vertex_location));
1850 break;
1851 case llvm::dxbc::PSV::SemanticKind::PrimitiveID:
1852 assert(Stage == llvm::Triple::Pixel &&
1853 "SV_PrimitiveID is in an unavailable stage and should have been "
1854 "diagnosed by Sema");
1855 if (CGM.getTarget().getTriple().isSPIRV())
1856 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1857 Semantic->getAttrName()->getName(),
1858 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1859 /* PrimitiveId */ 7, InterpMode);
1860 // Pixel shaders read the primitive ID from the input signature. The
1861 // dx.op.primitiveID operation is only available to other stages.
1862 if (CGM.getTarget().getTriple().isDXIL())
1863 return emitDXILUserSemanticLoad(B, Type, Decl, Semantic, Index,
1864 Signature);
1865 break;
1866 case llvm::dxbc::PSV::SemanticKind::SampleIndex:
1867 assert(Stage == llvm::Triple::Pixel &&
1868 "SV_SampleIndex is in an unavailable stage and should have been "
1869 "diagnosed by Sema");
1870 if (CGM.getTarget().getTriple().isSPIRV())
1871 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1872 Semantic->getAttrName()->getName(),
1873 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1874 /* SampleId */ 18, InterpMode);
1875 if (CGM.getTarget().getTriple().isDXIL()) {
1876 assert(Type->isIntegerTy() && Type->getIntegerBitWidth() <= 32 &&
1877 "SV_SampleIndex must be a 16 or 32 bit scalar integer, as "
1878 "diagnosed by Sema");
1879 // The sample index is read with a dedicated operation, but an unpacked
1880 // element is still added to the input signature for compatibility.
1881 SemanticShape Shape =
1883 Signature.push_back(createSemanticSignatureElement(
1884 CGM, Signature.size(), Semantic, Index, Shape));
1885 llvm::Value *SampleIndex =
1886 B.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::dx_sample_index));
1887 // dx.op.sampleIndex only has an i32 overload, so a 16-bit declaration
1888 // narrows the result. The sample index always fits in 16 bits.
1889 if (Type->getIntegerBitWidth() < 32)
1890 SampleIndex = B.CreateTrunc(SampleIndex, Type);
1891 return SampleIndex;
1892 }
1893 break;
1894 case llvm::dxbc::PSV::SemanticKind::ViewID:
1895 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
1896 llvm::Triple::Domain, llvm::Triple::Geometry,
1897 llvm::Triple::Pixel, llvm::Triple::Mesh},
1898 Stage) &&
1899 "SV_ViewID is in an unavailable stage and should have been "
1900 "diagnosed by Sema");
1901 if (CGM.getTarget().getTriple().isSPIRV())
1902 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1903 Semantic->getAttrName()->getName(),
1904 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1905 /* ViewIndex */ 4440, InterpMode);
1906 if (CGM.getTarget().getTriple().isDXIL())
1907 return B.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::dx_view_id));
1908 break;
1909 case llvm::dxbc::PSV::SemanticKind::StartInstanceLocation:
1910 assert(Stage == llvm::Triple::Vertex &&
1911 "SV_StartInstanceLocation is in an unavailable stage and should "
1912 "have been diagnosed by Sema");
1913 if (CGM.getTarget().getTriple().isSPIRV())
1914 return createSPIRVInputLoad(B, CGM.getModule(), Type,
1915 Semantic->getAttrName()->getName(),
1916 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1917 /* BaseInstance */ 4425, InterpMode);
1918 if (CGM.getTarget().getTriple().isDXIL())
1919 return B.CreateCall(
1920 CGM.getIntrinsic(llvm::Intrinsic::dx_start_instance_location));
1921 break;
1922 default:
1923 break;
1924 }
1925
1926 llvm_unreachable(
1927 "Load hasn't been implemented yet for this system semantic. FIXME");
1928}
1929
1930// Maps a [[vk::builtin(...)]] name to its SPIR-V spec `BuiltIn` decoration.
1931// Deliberately not creating dependency on llvm::SPIRV::BuiltIn in front end.
1932// Sema's handleVkBuiltInAttr only allows names handled here to reach CodeGen.
1933static unsigned getSPIRVVkBuiltinID(StringRef BuiltIn) {
1934 unsigned ID = llvm::StringSwitch<unsigned>(BuiltIn)
1935 .Case("PointSize", /* BuiltIn::PointSize */ 1)
1936 .Default(-1);
1937 assert(ID != static_cast<unsigned>(-1) &&
1938 "Sema should only allow builtin names implemented here");
1939 return ID;
1940}
1941
1943 IRBuilder<> &B, llvm::Value *Source, const clang::DeclaratorDecl *Decl,
1944 HLSLAppliedSemanticAttr *Semantic,
1945 llvm::dxbc::PSV::SemanticKind SemanticKind,
1946 llvm::Triple::EnvironmentType Stage, std::optional<unsigned> Index,
1947 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1948 const bool IsSignedInt =
1950 switch (SemanticKind) {
1951 case llvm::dxbc::PSV::SemanticKind::Position:
1952 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
1953 llvm::Triple::Domain, llvm::Triple::Geometry,
1954 llvm::Triple::Mesh},
1955 Stage) &&
1956 "SV_Position is in an unavailable stage and should have been "
1957 "diagnosed by Sema");
1958 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1959 Stage != llvm::Triple::Geometry && Stage != llvm::Triple::Mesh &&
1960 "FIXME: storing SV_Position is not yet implemented for this "
1961 "shader stage");
1962 if (CGM.getTarget().getTriple().isDXIL()) {
1963 emitDXILUserSemanticStore(B, Source, Decl, Semantic, Index, Signature);
1964 return;
1965 }
1966 if (CGM.getTarget().getTriple().isSPIRV()) {
1967 createSPIRVOutputStore(B, CGM.getModule(), Source,
1968 Semantic->getAttrName()->getName(),
1969 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1970 /* Position */ 0, InterpMode);
1971 return;
1972 }
1973 break;
1974 case llvm::dxbc::PSV::SemanticKind::StencilRef:
1975 assert(Stage == llvm::Triple::Pixel &&
1976 "SV_StencilRef is in an unavailable stage and should have been "
1977 "diagnosed by Sema");
1978 // The stencil reference is stored to an output element that is not
1979 // packed into the render-target rows.
1980 if (CGM.getTarget().getTriple().isDXIL()) {
1981 emitDXILUserSemanticStore(B, Source, Decl, Semantic, Index, Signature);
1982 return;
1983 }
1984 if (CGM.getTarget().getTriple().isSPIRV()) {
1986 B, CGM.getModule(), Source, Semantic->getAttrName()->getName(),
1987 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1988 /* FragStencilRefEXT */ 5014, InterpMode, IsSignedInt);
1989 return;
1990 }
1991 break;
1992 case llvm::dxbc::PSV::SemanticKind::Target:
1993 assert(Stage == llvm::Triple::Pixel &&
1994 "SV_Target is in an unavailable stage and should have been "
1995 "diagnosed by Sema");
1996 if (CGM.getTarget().getTriple().isDXIL()) {
1997 emitDXILUserSemanticStore(B, Source, Decl, Semantic, Index, Signature,
1998 /*EnforceOneElementPerRow=*/true);
1999 return;
2000 }
2001 if (CGM.getTarget().getTriple().isSPIRV()) {
2002 emitSPIRVUserSemanticStore(B, Source, Decl, Semantic, Index, InterpMode,
2003 /*UseLocationFromIndex=*/true);
2004 return;
2005 }
2006 break;
2007 case llvm::dxbc::PSV::SemanticKind::ShadingRate:
2008 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
2009 llvm::Triple::Domain, llvm::Triple::Geometry,
2010 llvm::Triple::Mesh},
2011 Stage) &&
2012 "SV_ShadingRate is in an unavailable stage and should have been "
2013 "diagnosed by Sema");
2014 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
2015 Stage != llvm::Triple::Geometry && Stage != llvm::Triple::Mesh &&
2016 "FIXME: storing SV_ShadingRate is not yet implemented for this "
2017 "shader stage");
2018 if (CGM.getTarget().getTriple().isDXIL()) {
2019 emitDXILUserSemanticStore(B, Source, Decl, Semantic, Index, Signature);
2020 return;
2021 }
2022 if (CGM.getTarget().getTriple().isSPIRV()) {
2023 // Matches DXC: the PrimitiveShadingRateKHR built-in output does not
2024 // carry the Flat decoration implied for integer vertex outputs.
2025 createSPIRVOutputStore(B, CGM.getModule(), Source,
2026 Semantic->getAttrName()->getName(),
2027 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2028 /* PrimitiveShadingRateKHR */ 4432,
2029 llvm::hlsl::InterpolationMode::Undefined);
2030 return;
2031 }
2032 break;
2033 default:
2034 break;
2035 }
2036
2037 llvm_unreachable(
2038 "Store hasn't been implemented yet for this system semantic. FIXME");
2039}
2040
2041// A system-value name can have an arbitrary interpretation, for example
2042// SV_Position on a vertex input. Its signature elements are then arbitrary,
2043// although they keep the system-value name.
2046 size_t FirstElement) {
2047 for (auto &Element : llvm::drop_begin(Signature, FirstElement))
2048 Element.SemanticKind = llvm::dxbc::PSV::SemanticKind::Arbitrary;
2049}
2050
2052 IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type,
2053 const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic,
2054 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
2055
2056 // [[vk::builtin(...)]] takes precedence over the recognized-semantic
2057 // dispatch, so without this check they'd always be treated as an arbitrary
2058 // user semantic. The attribute is only ever attached when targeting SPIR-V.
2059 if (const auto *BuiltInAttr = Decl->getAttr<HLSLVkBuiltInAttr>())
2060 return createSPIRVInputLoad(
2061 B, CGM.getModule(), Type, Semantic->getAttrName()->getName(),
2062 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2063 getSPIRVVkBuiltinID(BuiltInAttr->getBuiltIn()), InterpMode);
2064
2065 std::optional<unsigned> Index = Semantic->getSemanticIndex();
2066 llvm::dxbc::PSV::SemanticKind SemanticKind =
2067 llvm::hlsl::getSemanticKind(Semantic->getAttrName()->getName());
2068 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
2069 assert(ShaderAttr && "Entry point has no shader attribute");
2070 llvm::hlsl::SemanticInterpretation Interpretation =
2071 llvm::hlsl::getInterpretationKind(SemanticKind, ShaderAttr->getType(),
2072 llvm::hlsl::IOType::In);
2073 assert(Interpretation != llvm::hlsl::SemanticInterpretation::Invalid &&
2074 "invalid semantic should have been diagnosed by Sema");
2075 if (CGM.getTarget().getTriple().isSPIRV())
2076 InterpMode = getSPIRVInterpolationMode(
2077 InterpMode, Type, ShaderAttr->getType(), llvm::hlsl::IOType::In);
2078 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
2079 size_t FirstElement = Signature.size();
2080 llvm::Value *Value = emitUserSemanticLoad(B, Type, Decl, Semantic, Index,
2081 Signature, InterpMode);
2082 markArbitrarySignatureElements(Signature, FirstElement);
2083 return Value;
2084 }
2085 return emitSystemSemanticLoad(B, Type, Decl, Semantic, SemanticKind,
2086 ShaderAttr->getType(), Index, Signature,
2087 InterpMode);
2088}
2089
2091 IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source,
2092 const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic,
2093 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
2094 // See the matching comment in `handleScalarSemanticLoad`
2095 if (const auto *BuiltInAttr = Decl->getAttr<HLSLVkBuiltInAttr>()) {
2097 B, CGM.getModule(), Source, Semantic->getAttrName()->getName(),
2098 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2099 getSPIRVVkBuiltinID(BuiltInAttr->getBuiltIn()), InterpMode);
2100 return;
2101 }
2102
2103 std::optional<unsigned> Index = Semantic->getSemanticIndex();
2104 llvm::dxbc::PSV::SemanticKind SemanticKind =
2105 llvm::hlsl::getSemanticKind(Semantic->getAttrName()->getName());
2106 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
2107 assert(ShaderAttr && "Entry point has no shader attribute");
2108
2109 llvm::hlsl::SemanticInterpretation Interpretation =
2110 llvm::hlsl::getInterpretationKind(SemanticKind, ShaderAttr->getType(),
2111 llvm::hlsl::IOType::Out);
2112 assert(Interpretation != llvm::hlsl::SemanticInterpretation::Invalid &&
2113 "invalid semantic should have been diagnosed by Sema");
2114 if (CGM.getTarget().getTriple().isSPIRV())
2115 InterpMode = getSPIRVInterpolationMode(InterpMode, Source->getType(),
2116 ShaderAttr->getType(),
2117 llvm::hlsl::IOType::Out);
2118
2119 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
2120 size_t FirstElement = Signature.size();
2121 emitUserSemanticStore(B, Source, Decl, Semantic, Index, Signature,
2122 InterpMode);
2123 markArbitrarySignatureElements(Signature, FirstElement);
2124 return;
2125 }
2126 emitSystemSemanticStore(B, Source, Decl, Semantic, SemanticKind,
2127 ShaderAttr->getType(), Index, Signature, InterpMode);
2128}
2129
2130std::pair<llvm::Value *, specific_attr_iterator<HLSLAppliedSemanticAttr>>
2132 IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type,
2136 SemanticSignatures &Signature,
2137 llvm::hlsl::InterpolationModifier Modifiers) {
2138 const llvm::StructType *ST = cast<StructType>(Type);
2139 const clang::RecordDecl *RD = Decl->getType()->getAsRecordDecl();
2140
2141 assert(RD->getNumFields() == ST->getNumElements());
2142
2143 llvm::Value *Aggregate = llvm::PoisonValue::get(Type);
2144 auto FieldDecl = RD->field_begin();
2145 for (unsigned I = 0; I < ST->getNumElements(); ++I) {
2146 auto [ChildValue, NextAttr] =
2147 handleSemanticLoad(B, FD, ST->getElementType(I), *FieldDecl, AttrBegin,
2148 AttrEnd, Signature, Modifiers);
2149 AttrBegin = NextAttr;
2150 assert(ChildValue);
2151 Aggregate = B.CreateInsertValue(Aggregate, ChildValue, I);
2152 ++FieldDecl;
2153 }
2154
2155 return std::make_pair(Aggregate, AttrBegin);
2156}
2157
2160 IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source,
2164 SemanticSignatures &Signature,
2165 llvm::hlsl::InterpolationModifier Modifiers) {
2166
2167 const llvm::StructType *ST = cast<StructType>(Source->getType());
2168
2169 const clang::RecordDecl *RD = nullptr;
2170 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
2172 else
2173 RD = Decl->getType()->getAsRecordDecl();
2174 assert(RD);
2175
2176 assert(RD->getNumFields() == ST->getNumElements());
2177
2178 auto FieldDecl = RD->field_begin();
2179 for (unsigned I = 0; I < ST->getNumElements(); ++I, ++FieldDecl) {
2180 llvm::Value *Extract = B.CreateExtractValue(Source, I);
2181 AttrBegin = handleSemanticStore(B, FD, Extract, *FieldDecl, AttrBegin,
2182 AttrEnd, Signature, Modifiers);
2183 }
2184
2185 return AttrBegin;
2186}
2187
2188std::pair<llvm::Value *, specific_attr_iterator<HLSLAppliedSemanticAttr>>
2190 IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type,
2194 SemanticSignatures &Signature,
2195 llvm::hlsl::InterpolationModifier Modifiers) {
2196 assert(AttrBegin != AttrEnd);
2197 // Pass the enclosing declaration's mask down the traversal, replacing (not
2198 // merging) it when an inner field has its own interpolation modifiers.
2199 if (const auto *A = Decl->getAttr<HLSLInterpolationModifierAttr>())
2200 Modifiers =
2201 static_cast<llvm::hlsl::InterpolationModifier>(A->getModifiers());
2202 if (Type->isStructTy())
2203 return handleStructSemanticLoad(B, FD, Type, Decl, AttrBegin, AttrEnd,
2204 Signature, Modifiers);
2205
2206 HLSLAppliedSemanticAttr *Attr = *AttrBegin;
2207 ++AttrBegin;
2208 size_t PreviousSize = Signature.size();
2209 auto InterpMode = llvm::hlsl::getInterpolationMode(Modifiers);
2210 llvm::Value *Value =
2211 handleScalarSemanticLoad(B, FD, Type, Decl, Attr, Signature, InterpMode);
2212 // Intrinsic-only system values and SPIR-V loads do not add DXIL signature
2213 // elements. Non-pixel inputs retain Undefined.
2214 if (Signature.size() != PreviousSize) {
2215 auto &Element = Signature.back();
2216 Element.InterpMode = llvm::hlsl::normalizeInterpolationMode(
2217 InterpMode, Element.CompType, Element.SemanticKind,
2218 FD->getAttr<HLSLShaderAttr>()->getType(), llvm::hlsl::IOType::In);
2219 }
2220 return std::make_pair(Value, AttrBegin);
2221}
2222
2225 IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source,
2229 SemanticSignatures &Signature,
2230 llvm::hlsl::InterpolationModifier Modifiers) {
2231 assert(AttrBegin != AttrEnd);
2232 // An inner field overrides the enclosing return declaration's modifiers.
2233 if (const auto *A = Decl->getAttr<HLSLInterpolationModifierAttr>())
2234 Modifiers =
2235 static_cast<llvm::hlsl::InterpolationModifier>(A->getModifiers());
2236 if (Source->getType()->isStructTy())
2237 return handleStructSemanticStore(B, FD, Source, Decl, AttrBegin, AttrEnd,
2238 Signature, Modifiers);
2239
2240 HLSLAppliedSemanticAttr *Attr = *AttrBegin;
2241 ++AttrBegin;
2242 size_t PreviousSize = Signature.size();
2243 auto InterpMode = llvm::hlsl::getInterpolationMode(Modifiers);
2244 handleScalarSemanticStore(B, FD, Source, Decl, Attr, Signature, InterpMode);
2245 // A leaf can add several elements, such as an SV_Target array.
2246 for (auto &Element : llvm::drop_begin(Signature, PreviousSize))
2247 Element.InterpMode = llvm::hlsl::normalizeInterpolationMode(
2248 InterpMode, Element.CompType, Element.SemanticKind,
2249 FD->getAttr<HLSLShaderAttr>()->getType(), llvm::hlsl::IOType::Out);
2250 return AttrBegin;
2251}
2252
2254 llvm::Function *Fn) {
2257
2258 llvm::Module &M = CGM.getModule();
2259 llvm::LLVMContext &Ctx = M.getContext();
2260 auto *EntryTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx), false);
2261 Function *EntryFn =
2262 Function::Create(EntryTy, Function::ExternalLinkage, FD->getName(), &M);
2263
2264 // Copy function attributes over, we have no argument or return attributes
2265 // that can be valid on the real entry.
2266 AttributeList NewAttrs = AttributeList::get(Ctx, AttributeList::FunctionIndex,
2267 Fn->getAttributes().getFnAttrs());
2268 EntryFn->setAttributes(NewAttrs);
2269 setHLSLEntryAttributes(FD, EntryFn);
2270
2271 // Set the called function as internal linkage.
2272 Fn->setLinkage(GlobalValue::InternalLinkage);
2273
2274 BasicBlock *BB = BasicBlock::Create(Ctx, "entry", EntryFn);
2275 IRBuilder<> B(BB);
2277
2279 if (CGM.shouldEmitConvergenceTokens()) {
2280 assert(EntryFn->isConvergent());
2281 llvm::Value *I =
2282 B.CreateIntrinsic(llvm::Intrinsic::experimental_convergence_entry, {});
2283 llvm::Value *bundleArgs[] = {I};
2284 OB.emplace_back("convergencectrl", bundleArgs);
2285 }
2286
2288
2289 unsigned SRetOffset = 0;
2290 for (const auto &Param : Fn->args()) {
2291 if (Param.hasStructRetAttr()) {
2292 SRetOffset = 1;
2293 llvm::Type *VarType = Param.getParamStructRetType();
2294 llvm::Value *Var =
2295 CGM.getLangOpts().EmitLogicalPointer
2296 ? cast<Instruction>(B.CreateStructuredAlloca(VarType))
2297 : cast<Instruction>(B.CreateAlloca(VarType));
2298 OutputSemantic.push_back(std::make_pair(Var, VarType));
2299 Args.push_back(Var);
2300 continue;
2301 }
2302
2303 const ParmVarDecl *PD = FD->getParamDecl(Param.getArgNo() - SRetOffset);
2304 llvm::Value *SemanticValue = nullptr;
2305 // FIXME: support inout/out parameters for semantics.
2306 if ([[maybe_unused]] HLSLParamModifierAttr *MA =
2307 PD->getAttr<HLSLParamModifierAttr>()) {
2308 llvm_unreachable("Not handled yet");
2309 } else {
2310 llvm::Type *ParamType = nullptr;
2311 if (Param.hasByValAttr())
2312 ParamType = Param.getParamByValType();
2313 else if (PD->getType()->isRecordType())
2314 ParamType = CGM.getTypes().ConvertType(PD->getType());
2315 else
2316 ParamType = Param.getType();
2317
2318 auto AttrBegin = PD->specific_attr_begin<HLSLAppliedSemanticAttr>();
2319 auto AttrEnd = PD->specific_attr_end<HLSLAppliedSemanticAttr>();
2320 auto Result = handleSemanticLoad(B, FD, ParamType, PD, AttrBegin, AttrEnd,
2321 InputSignature);
2322 SemanticValue = Result.first;
2323 if (!SemanticValue)
2324 return;
2325 if (Param.hasByValAttr() || PD->getType()->isRecordType()) {
2326 llvm::Value *Var =
2327 CGM.getLangOpts().EmitLogicalPointer
2328 ? cast<Instruction>(B.CreateStructuredAlloca(ParamType))
2329 : cast<Instruction>(B.CreateAlloca(ParamType));
2330 B.CreateStore(SemanticValue, Var);
2331 SemanticValue = Var;
2332 }
2333 }
2334
2335 assert(SemanticValue);
2336 Args.push_back(SemanticValue);
2337 }
2338
2339 CallInst *CI = B.CreateCall(FunctionCallee(Fn), Args, OB);
2340 CI->setCallingConv(Fn->getCallingConv());
2341
2342 if (Fn->getReturnType() != CGM.VoidTy)
2343 // Element type is unused, so set to dummy value (NULL).
2344 OutputSemantic.push_back(std::make_pair(CI, nullptr));
2345
2346 for (auto &SourcePair : OutputSemantic) {
2347 llvm::Value *Source = SourcePair.first;
2348 llvm::Type *ElementType = SourcePair.second;
2349 AllocaInst *AI = dyn_cast<AllocaInst>(Source);
2350 llvm::Value *SourceValue = AI ? B.CreateLoad(ElementType, Source) : Source;
2351
2352 auto AttrBegin = FD->specific_attr_begin<HLSLAppliedSemanticAttr>();
2353 auto AttrEnd = FD->specific_attr_end<HLSLAppliedSemanticAttr>();
2354 handleSemanticStore(B, FD, SourceValue, FD, AttrBegin, AttrEnd,
2355 OutputSignature);
2356 }
2357
2358 B.CreateRetVoid();
2359
2360 // Add and identify root signature to function, if applicable
2361 for (const Attr *Attr : FD->getAttrs()) {
2362 if (const auto *RSAttr = dyn_cast<RootSignatureAttr>(Attr)) {
2363 auto *RSDecl = RSAttr->getSignatureDecl();
2364 addRootSignatureMD(RSDecl->getVersion(), RSDecl->getRootElements(),
2365 EntryFn, M);
2366 }
2367 }
2368
2369 if (CGM.getTarget().getTriple().isDXIL()) {
2370 // Use the entry's shader stage, not the target environment, which may be
2371 // 'library' when compiling multiple entry points.
2372 auto Stage = FD->getAttr<HLSLShaderAttr>()->getType();
2374 auto Mode = CGM.getCodeGenOpts().getHLSLSemanticSignaturePacking();
2375 for (auto IOTy : {llvm::hlsl::IOType::In, llvm::hlsl::IOType::Out}) {
2376 bool IsOutput = IOTy == llvm::hlsl::IOType::Out;
2377 auto &Signature = IsOutput ? OutputSignature : InputSignature;
2378 auto Packed = packSemanticSignature(Signature, Stage, IOTy, Mode,
2379 CGM.getLangOpts().NativeHalfType);
2380 if (!Packed) {
2381 CGM.getDiags().Report(FD->getLocation(),
2382 diag::err_hlsl_signature_packing)
2383 << IsOutput << llvm::toString(Packed.takeError());
2384 return;
2385 }
2386 // Library entry points retain stage-specific packing without warnings.
2387 if (Mode != PackingMode::Default &&
2388 CGM.getTarget().getTriple().getEnvironment() !=
2389 llvm::Triple::Library &&
2390 ((Stage == llvm::Triple::Vertex && !IsOutput) ||
2391 (Stage == llvm::Triple::Pixel && IsOutput)))
2392 CGM.getDiags().Report(FD->getLocation(),
2393 diag::warn_hlsl_signature_packing_ignored)
2394 << (Mode == PackingMode::Optimized ? "optimized" : "prefix-stable")
2395 << IsOutput;
2396 }
2397 }
2398
2399 addSemanticSignatureMD(InputSignature, OutputSignature, EntryFn, M);
2400}
2401
2402static void gatherFunctions(SmallVectorImpl<Function *> &Fns, llvm::Module &M,
2403 bool CtorOrDtor) {
2404 const auto *GV =
2405 M.getNamedGlobal(CtorOrDtor ? "llvm.global_ctors" : "llvm.global_dtors");
2406 if (!GV)
2407 return;
2408 const auto *CA = dyn_cast<ConstantArray>(GV->getInitializer());
2409 if (!CA)
2410 return;
2411 // The global_ctor array elements are a struct [Priority, Fn *, COMDat].
2412 // HLSL neither supports priorities or COMDat values, so we will check those
2413 // in an assert but not handle them.
2414
2415 for (const auto &Ctor : CA->operands()) {
2417 continue;
2418 ConstantStruct *CS = cast<ConstantStruct>(Ctor);
2419
2420 assert(cast<ConstantInt>(CS->getOperand(0))->getValue() == 65535 &&
2421 "HLSL doesn't support setting priority for global ctors.");
2422 assert(isa<ConstantPointerNull>(CS->getOperand(2)) &&
2423 "HLSL doesn't support COMDat for global ctors.");
2424 Fns.push_back(cast<Function>(CS->getOperand(1)));
2425 }
2426}
2427
2429 llvm::Module &M = CGM.getModule();
2432 gatherFunctions(CtorFns, M, true);
2433 gatherFunctions(DtorFns, M, false);
2434
2435 // Insert a call to the global constructor at the beginning of the entry block
2436 // to externally exported functions. This is a bit of a hack, but HLSL allows
2437 // global constructors, but doesn't support driver initialization of globals.
2438 for (auto &F : M.functions()) {
2439 if (!F.hasFnAttribute("hlsl.shader"))
2440 continue;
2441 auto *Token = getConvergenceToken(F.getEntryBlock());
2442 Instruction *IP = &*F.getEntryBlock().begin();
2444 if (Token) {
2445 llvm::Value *bundleArgs[] = {Token};
2446 OB.emplace_back("convergencectrl", bundleArgs);
2447 IP = Token->getNextNode();
2448 }
2449 IRBuilder<> B(IP);
2450 for (auto *Fn : CtorFns) {
2451 auto CI = B.CreateCall(FunctionCallee(Fn), {}, OB);
2452 CI->setCallingConv(Fn->getCallingConv());
2453 }
2454
2455 // Insert global dtors before the terminator of the last instruction
2456 B.SetInsertPoint(F.back().getTerminator());
2457 for (auto *Fn : DtorFns) {
2458 auto CI = B.CreateCall(FunctionCallee(Fn), {}, OB);
2459 CI->setCallingConv(Fn->getCallingConv());
2460 }
2461 }
2462
2463 // No need to keep global ctors/dtors for non-lib profile after call to
2464 // ctors/dtors added for entry.
2465 Triple T(M.getTargetTriple());
2466 if (T.getEnvironment() != Triple::EnvironmentType::Library) {
2467 if (auto *GV = M.getNamedGlobal("llvm.global_ctors"))
2468 GV->eraseFromParent();
2469 if (auto *GV = M.getNamedGlobal("llvm.global_dtors"))
2470 GV->eraseFromParent();
2471 }
2472}
2473
2474static void initializeBuffer(CodeGenModule &CGM, llvm::GlobalVariable *GV,
2475 Intrinsic::ID IntrID,
2477
2478 LLVMContext &Ctx = CGM.getLLVMContext();
2479 llvm::Function *InitResFunc =
2480 llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy, false),
2481 llvm::GlobalValue::InternalLinkage,
2482 "_init_buffer_" + GV->getName(), CGM.getModule());
2483 InitResFunc->addFnAttr(llvm::Attribute::AlwaysInline);
2484
2485 llvm::BasicBlock *EntryBB =
2486 llvm::BasicBlock::Create(Ctx, "entry", InitResFunc);
2487 CGBuilderTy Builder(CGM, Ctx);
2488 const DataLayout &DL = CGM.getModule().getDataLayout();
2489 Builder.SetInsertPoint(EntryBB);
2490
2491 // Make sure the global variable is buffer resource handle
2492 llvm::Type *HandleTy = GV->getValueType();
2493 assert(HandleTy->isTargetExtTy() && "unexpected type of the buffer global");
2494
2495 llvm::Value *CreateHandle = Builder.CreateIntrinsic(
2496 /*ReturnType=*/HandleTy, IntrID, Args, nullptr,
2497 Twine(GV->getName()).concat("_h"));
2498
2499 Builder.CreateAlignedStore(CreateHandle, GV, GV->getPointerAlignment(DL));
2500 Builder.CreateRetVoid();
2501
2502 CGM.AddCXXGlobalInit(InitResFunc);
2503}
2504
2505void CGHLSLRuntime::initializeBufferFromBinding(const HLSLBufferDecl *BufDecl,
2506 llvm::GlobalVariable *GV) {
2507 ResourceBindingAttrs Binding(BufDecl);
2508 assert(Binding.hasBinding() &&
2509 "cbuffer/tbuffer should always have resource binding attribute");
2510
2511 auto *Index = llvm::ConstantInt::get(CGM.IntTy, 0);
2512 auto *RangeSize = llvm::ConstantInt::get(CGM.IntTy, 1);
2513 auto *Space = llvm::ConstantInt::get(CGM.IntTy, Binding.getSpace());
2514 Value *Name = buildNameForResource(BufDecl->getName(), CGM);
2515
2516 // buffer with explicit binding
2517 if (Binding.isExplicit()) {
2518 llvm::Intrinsic::ID IntrinsicID =
2519 CGM.getHLSLRuntime().getCreateHandleFromBindingIntrinsic();
2520 auto *RegSlot = llvm::ConstantInt::get(CGM.IntTy, Binding.getSlot());
2521 SmallVector<Value *> Args{Space, RegSlot, RangeSize, Index, Name};
2522 initializeBuffer(CGM, GV, IntrinsicID, Args);
2523 } else {
2524 // buffer with implicit binding
2525 llvm::Intrinsic::ID IntrinsicID =
2526 CGM.getHLSLRuntime().getCreateHandleFromImplicitBindingIntrinsic();
2527 auto *OrderID =
2528 llvm::ConstantInt::get(CGM.IntTy, Binding.getImplicitOrderID());
2529 SmallVector<Value *> Args{OrderID, Space, RangeSize, Index, Name};
2530 initializeBuffer(CGM, GV, IntrinsicID, Args);
2531 }
2532}
2533
2535 llvm::GlobalVariable *GV) {
2536 if (auto Attr = VD->getAttr<HLSLVkExtBuiltinInputAttr>())
2538 GV, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, Attr->getBuiltIn());
2539 if (auto Attr = VD->getAttr<HLSLVkExtBuiltinOutputAttr>())
2541 GV, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, Attr->getBuiltIn());
2542}
2543
2544llvm::Instruction *CGHLSLRuntime::getConvergenceToken(BasicBlock &BB) {
2545 if (!CGM.shouldEmitConvergenceTokens())
2546 return nullptr;
2547
2548 auto E = BB.end();
2549 for (auto I = BB.begin(); I != E; ++I) {
2550 auto *II = dyn_cast<llvm::IntrinsicInst>(&*I);
2551 if (II && llvm::isConvergenceControlIntrinsic(II->getIntrinsicID())) {
2552 return II;
2553 }
2554 }
2555 llvm_unreachable("Convergence token should have been emitted.");
2556 return nullptr;
2557}
2558
2559class OpaqueValueVisitor : public RecursiveASTVisitor<OpaqueValueVisitor> {
2560public:
2564
2566 // These need to be bound in CodeGenFunction::EmitHLSLOutArgLValues
2567 // or CodeGenFunction::EmitHLSLOutArgExpr. If they are part of this
2568 // traversal, the temporary containing the copy out will not have
2569 // been created yet.
2570 return false;
2571 }
2572
2574 // Traverse the source expression first.
2575 if (E->getSourceExpr())
2577
2578 // Then add this OVE if we haven't seen it before.
2579 if (Visited.insert(E).second)
2580 OVEs.push_back(E);
2581
2582 return true;
2583 }
2584};
2585
2587 InitListExpr *E) {
2588
2589 typedef CodeGenFunction::OpaqueValueMappingData OpaqueValueMappingData;
2590 OpaqueValueVisitor Visitor;
2591 Visitor.TraverseStmt(E);
2592 for (auto *OVE : Visitor.OVEs) {
2593 if (CGF.isOpaqueValueEmitted(OVE))
2594 continue;
2595 if (OpaqueValueMappingData::shouldBindAsLValue(OVE)) {
2596 LValue LV = CGF.EmitLValue(OVE->getSourceExpr());
2597 OpaqueValueMappingData::bind(CGF, OVE, LV);
2598 } else {
2599 RValue RV = CGF.EmitAnyExpr(OVE->getSourceExpr());
2600 OpaqueValueMappingData::bind(CGF, OVE, RV);
2601 }
2602 }
2603}
2604
2606 const ArraySubscriptExpr *ArraySubsExpr, CodeGenFunction &CGF) {
2607 assert((ArraySubsExpr->getType()->isHLSLResourceRecord() ||
2608 ArraySubsExpr->getType()->isHLSLResourceRecordArray()) &&
2609 "expected resource array subscript expression");
2610
2611 // Let clang codegen handle local and static resource array subscripts,
2612 // or when the subscript references on opaque expression (as part of
2613 // ArrayInitLoopExpr AST node).
2614 const VarDecl *ArrayDecl = dyn_cast_or_null<VarDecl>(
2615 getArrayDecl(CGF.CGM.getContext(), ArraySubsExpr));
2616 if (!ArrayDecl || !ArrayDecl->hasGlobalStorage() ||
2617 ArrayDecl->getStorageClass() == SC_Static)
2618 return std::nullopt;
2619
2620 // get the resource array type
2621 ASTContext &AST = ArrayDecl->getASTContext();
2622 const Type *ResArrayTy = ArrayDecl->getType().getTypePtr();
2623 assert(ResArrayTy->isHLSLResourceRecordArray() &&
2624 "expected array of resource classes");
2625
2626 // Iterate through all nested array subscript expressions to calculate
2627 // the index in the flattened resource array (if this is a multi-
2628 // dimensional array). The index is calculated as a sum of all indices
2629 // multiplied by the total size of the array at that level.
2630 Value *Index = nullptr;
2631 const ArraySubscriptExpr *ASE = ArraySubsExpr;
2632 while (ASE != nullptr) {
2633 Value *SubIndex = CGF.EmitScalarExpr(ASE->getIdx());
2634 if (const auto *ArrayTy =
2635 dyn_cast<ConstantArrayType>(ASE->getType().getTypePtr())) {
2636 Value *Multiplier = llvm::ConstantInt::get(
2637 CGM.IntTy, AST.getConstantArrayElementCount(ArrayTy));
2638 SubIndex = CGF.Builder.CreateMul(SubIndex, Multiplier);
2639 }
2640 Index = Index ? CGF.Builder.CreateAdd(Index, SubIndex) : SubIndex;
2641 ASE = dyn_cast<ArraySubscriptExpr>(ASE->getBase()->IgnoreParenImpCasts());
2642 }
2643
2644 // Find binding info for the resource array. For implicit binding
2645 // an HLSLResourceBindingAttr should have been added by SemaHLSL.
2646 ResourceBindingAttrs Binding(ArrayDecl);
2647 assert(Binding.hasBinding() &&
2648 "resource array must have a binding attribute");
2649
2650 // Find the individual resource type.
2651 QualType ResultTy = ArraySubsExpr->getType();
2652 QualType ResourceTy =
2653 ResultTy->isArrayType() ? AST.getBaseElementType(ResultTy) : ResultTy;
2654
2655 // Create a temporary variable for the result, which is either going
2656 // to be a single resource instance or a local array of resources (we need to
2657 // return an LValue).
2658 RawAddress TmpVar = CGF.CreateMemTempWithoutCast(ResultTy);
2659 if (CGF.EmitLifetimeStart(TmpVar.getPointer()))
2661 NormalEHLifetimeMarker, TmpVar);
2662
2667
2668 // Calculate total array size (= range size).
2669 llvm::Value *Range = llvm::ConstantInt::getSigned(
2670 CGM.IntTy, getTotalArraySize(AST, ResArrayTy));
2671
2672 // If the result of the subscript operation is a single resource, call the
2673 // constructor.
2674 if (ResultTy == ResourceTy) {
2675 CallArgList Args;
2676 CXXMethodDecl *CreateMethod = lookupResourceInitMethodAndSetupArgs(
2677 CGF.CGM, ResourceTy->getAsCXXRecordDecl(), Range, Index,
2678 ArrayDecl->getName(), Binding, Args);
2679
2680 if (!CreateMethod) {
2681 // This can happen if someone creates an array of structs that looks like
2682 // an HLSL resource record array but it does not have the required static
2683 // create method. No binding will be generated for it.
2684 assert(!ResourceTy->getAsCXXRecordDecl()->isImplicit() &&
2685 "create method lookup should always succeed for built-in resource "
2686 "records");
2687 return std::nullopt;
2688 }
2689
2690 callResourceInitMethod(CGF, CreateMethod, Args, ValueSlot.getAddress());
2691
2692 } else {
2693 // The result of the subscript operation is a local resource array which
2694 // needs to be initialized.
2695 const ConstantArrayType *ArrayTy =
2697 std::optional<llvm::Value *> EndIndex = initializeResourceArrayFromGlobal(
2698 CGF, ResourceTy->getAsCXXRecordDecl(), ArrayTy, ValueSlot, Range, Index,
2699 ArrayDecl->getName(), Binding, {llvm::ConstantInt::get(CGM.IntTy, 0)});
2700 if (!EndIndex)
2701 return std::nullopt;
2702 }
2703 return CGF.MakeAddrLValue(TmpVar, ResultTy, AlignmentSource::Decl);
2704}
2705
2706// Initialize all resources of a global resource array into provided slot.
2707bool CGHLSLRuntime::initializeGlobalResourceArray(CodeGenFunction &CGF,
2708 const VarDecl *ArrayDecl,
2709 AggValueSlot &DestSlot) {
2710 assert(ArrayDecl->getType()->isHLSLResourceRecordArray() &&
2711 ArrayDecl->hasGlobalStorage() &&
2712 ArrayDecl->getStorageClass() != SC_Static &&
2713 "expected global non-static resource array");
2714
2715 // Find binding info for the resource array. For implicit binding
2716 // the HLSLResourceBindingAttr should have been added by SemaHLSL.
2717 ResourceBindingAttrs Binding(ArrayDecl);
2718 assert(Binding.hasBinding() &&
2719 "resource array must have a binding attribute");
2720
2721 // Find the individual resource type.
2722 ASTContext &AST = ArrayDecl->getASTContext();
2723 QualType ResTy = AST.getBaseElementType(ArrayDecl->getType());
2724 const auto *ResArrayTy =
2726
2727 // Create Value for index and total array size (= range size).
2728 int Size = getTotalArraySize(AST, ResArrayTy);
2729 llvm::Value *Zero = llvm::ConstantInt::get(CGM.IntTy, 0);
2730 llvm::Value *Range = llvm::ConstantInt::get(CGM.IntTy, Size);
2731
2732 // Initialize individual resources in the array into DestSlot.
2733 std::optional<llvm::Value *> EndIndex = initializeResourceArrayFromGlobal(
2734 CGF, ResTy->getAsCXXRecordDecl(), ResArrayTy, DestSlot, Range, Zero,
2735 ArrayDecl->getName(), Binding, {Zero});
2736 return EndIndex.has_value();
2737}
2738
2739// If the expression is a global resource array, initialize all of its resources
2740// into Dest. Returns false if no initialization has been performed and the
2741// array copy should be handled by the default codegen.
2743 AggValueSlot &DestSlot) {
2744 assert(E->getType()->isHLSLResourceRecordArray() &&
2745 "expected resource array");
2746
2747 // Find the array declaration for the expression. Fallback to the default
2748 // handling if it's not a global resource array.
2749 const VarDecl *ArrayDecl =
2750 dyn_cast_or_null<VarDecl>(getArrayDecl(CGF.CGM.getContext(), E));
2751 if (!ArrayDecl || !ArrayDecl->hasGlobalStorage() ||
2752 ArrayDecl->getStorageClass() == SC_Static)
2753 return false;
2754
2755 return initializeGlobalResourceArray(CGF, ArrayDecl, DestSlot);
2756}
2757
2758// If the expression is a global resource array, create a temporary and
2759// initialize all of its resources, and return it as an LValue. Returns nullopt
2760// if no initialization has been performed and the handling should follow the
2761// default path.
2762std::optional<LValue>
2764 const VarDecl *ArrayDecl) {
2765 assert(ArrayDecl->getType()->isHLSLResourceRecordArray() &&
2766 "expected resource array declaration");
2767
2768 if (!ArrayDecl->hasGlobalStorage() ||
2769 ArrayDecl->getStorageClass() == SC_Static)
2770 return std::nullopt;
2771
2772 AggValueSlot TmpArraySlot =
2773 CGF.CreateAggTemp(ArrayDecl->getType(), "tmpResArray");
2774 if (initializeGlobalResourceArray(CGF, ArrayDecl, TmpArraySlot))
2775 return CGF.MakeAddrLValue(TmpArraySlot.getAddress(), ArrayDecl->getType(),
2777 return std::nullopt;
2778}
2779
2781 CodeGenFunction &CGF) {
2782
2783 assert(LV.getType()->isConstantMatrixType() && "expected matrix type");
2785 "expected cbuffer matrix");
2786
2787 QualType MatQualTy = LV.getType();
2788 llvm::Type *LayoutTy = HLSLBufferLayoutBuilder(CGF.CGM).layOutType(MatQualTy);
2789 Address SrcAddr = LV.getAddress();
2790
2791 if (LayoutTy == CGF.ConvertTypeForMem(MatQualTy))
2792 return SrcAddr;
2793
2794 RawAddress DestAlloca =
2795 CGF.CreateMemTempWithoutCast(MatQualTy, "matrix.buf.copy");
2796 HLSLBufferCopyEmitter(CGF, DestAlloca, SrcAddr).emitCopy(MatQualTy);
2797 return DestAlloca;
2798}
2799
2801 const ArraySubscriptExpr *E, CodeGenFunction &CGF,
2802 llvm::function_ref<llvm::Value *(bool Promote)> EmitIdxAfterBase) {
2803 // Find the element type to index by first padding the element type per HLSL
2804 // buffer rules, and then padding out to a 16-byte register boundary if
2805 // necessary.
2806 llvm::Type *LayoutTy =
2808 uint64_t LayoutSizeInBits =
2809 CGM.getDataLayout().getTypeSizeInBits(LayoutTy).getFixedValue();
2810 CharUnits ElementSize = CharUnits::fromQuantity(LayoutSizeInBits / 8);
2811 CharUnits RowAlignedSize = ElementSize.alignTo(CharUnits::fromQuantity(16));
2812 if (RowAlignedSize > ElementSize) {
2813 llvm::Type *Padding = CGM.getTargetCodeGenInfo().getHLSLPadding(
2814 CGM, RowAlignedSize - ElementSize);
2815 assert(Padding && "No padding type for target?");
2816 LayoutTy = llvm::StructType::get(CGF.getLLVMContext(), {LayoutTy, Padding},
2817 /*isPacked=*/true);
2818 }
2819
2820 // If the layout type doesn't introduce any padding, we don't need to do
2821 // anything special.
2822 llvm::Type *OrigTy = CGF.CGM.getTypes().ConvertTypeForMem(E->getType());
2823 if (LayoutTy == OrigTy)
2824 return std::nullopt;
2825
2826 LValueBaseInfo EltBaseInfo;
2827 TBAAAccessInfo EltTBAAInfo;
2828
2829 // Index into the object as-if we have an array of the padded element type,
2830 // and then dereference the element itself to avoid reading padding that may
2831 // be past the end of the in-memory object.
2833 llvm::Value *Idx = EmitIdxAfterBase(/*Promote*/ true);
2834 Indices.push_back(Idx);
2835 Indices.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
2836
2837 if (CGF.getLangOpts().EmitLogicalPointer) {
2838 // The fact that we emit an array-to-pointer decay might be an oversight,
2839 // but for now, we simply ignore it (see #179951).
2840 const CastExpr *CE = cast<CastExpr>(E->getBase());
2841 assert(CE->getCastKind() == CastKind::CK_ArrayToPointerDecay);
2842
2843 LValue LV = CGF.EmitLValue(CE->getSubExpr());
2844 Address Addr = LV.getAddress();
2845 LayoutTy = llvm::ArrayType::get(
2846 LayoutTy,
2847 cast<llvm::ArrayType>(Addr.getElementType())->getNumElements());
2848 auto *GEP = cast<StructuredGEPInst>(CGF.Builder.CreateStructuredGEP(
2849 LayoutTy, Addr.emitRawPointer(CGF), Indices, "cbufferidx"));
2850 Addr =
2851 Address(GEP, GEP->getResultElementType(), RowAlignedSize, KnownNonNull);
2852 return CGF.MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
2853 }
2854
2855 Address Addr =
2856 CGF.EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
2857 llvm::Value *GEP = CGF.Builder.CreateGEP(LayoutTy, Addr.emitRawPointer(CGF),
2858 Indices, "cbufferidx");
2859 Addr = Address(GEP, Addr.getElementType(), RowAlignedSize, KnownNonNull);
2860 return CGF.MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
2861}
2862
2863std::optional<LValue>
2865 const MemberExpr *ME) {
2866 assert((ME->getType()->isHLSLResourceRecord() ||
2868 "expected resource member expression");
2869
2870 const VarDecl *ResourceVD =
2871 findAssociatedResourceDeclForStruct(CGF.CGM.getContext(), ME);
2872 if (!ResourceVD)
2873 return std::nullopt;
2874
2875 // Handle member of resource array type.
2876 if (ResourceVD->getType()->isHLSLResourceRecordArray())
2877 return emitGlobalResourceArrayAsLValue(CGF, ResourceVD);
2878
2879 GlobalVariable *ResGV =
2880 cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(ResourceVD));
2881 const DataLayout &DL = CGM.getDataLayout();
2882 llvm::Type *Ty = ResGV->getValueType();
2883 CharUnits Align = CharUnits::fromQuantity(DL.getABITypeAlign(Ty));
2884 Address Addr = Address(ResGV, Ty, Align);
2885 LValue LV = LValue::MakeAddr(Addr, ME->getType(), CGM.getContext(),
2887 CGM.getTBAAAccessInfo(ME->getType()));
2888 return LV;
2889}
2890
2892 const LValue &SrcLV,
2893 AggValueSlot &DestSlot) {
2895 "expected expression in HLSL constant address space");
2896 assert(!E->getType()->isHLSLResourceRecord() &&
2898 "direct accesses to resource types should be handled separately");
2899
2900 if (DestSlot.isIgnored())
2901 return false;
2902
2903 QualType Ty = E->getType();
2904 Address DstPtr = DestSlot.getAddress();
2905 Address SrcPtr = SrcLV.getAddress();
2906
2907 // If there are no intangible types, we don't need to lookup associated
2908 // resources.
2909 if (!Ty->isHLSLIntangibleType())
2910 return HLSLBufferCopyEmitter(CGF, DstPtr, SrcPtr).emitCopy(Ty);
2911
2912 // Handle structs with intangible types by setting the resource fields
2913 // of the destination struct with the resources associated with the global
2914 // struct.
2915 EmbeddedResourceNameBuilder NameBuilder;
2916 const VarDecl *VD = findStructResourceParentDeclAndBuildName(E, NameBuilder);
2917 AssociatedResourcesList AssociatedResources(VD, NameBuilder.getName());
2918
2919 // Callback to fill in the associated resource.
2920 auto EmitResFn = [&](AggValueSlot &ResSlot) {
2921 const VarDecl *ResDecl = AssociatedResources.getNextResource();
2922 assert(ResDecl && "associated resource declaration not found");
2923
2924 // Check that the resource type of dest and src matches.
2925 [[maybe_unused]] llvm::Type *DestType =
2926 ResSlot.getAddress().getElementType();
2927 [[maybe_unused]] llvm::Type *SrcConvertedType =
2928 CGM.getTypes().ConvertTypeForMem(ResDecl->getType());
2929 assert(DestType == SrcConvertedType && "resource slot type mismatch");
2930
2931 if (ResDecl->getType()->isHLSLResourceRecord())
2932 copyGlobalResource(CGF, ResDecl, ResSlot);
2933 else
2934 initializeGlobalResourceArray(CGF, ResDecl, ResSlot);
2935 };
2936
2937 auto Result =
2938 HLSLBufferCopyEmitter(CGF, DstPtr, SrcPtr).emitCopy(Ty, EmitResFn);
2939 assert(AssociatedResources.getNextResource() == nullptr &&
2940 "expected all associated resources to be processed");
2941 return Result;
2942}
2943
2945 const MemberExpr *E) {
2946 LValue Base =
2948 auto *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
2949 assert(Field && "Unexpected access into HLSL buffer");
2950
2951 const RecordDecl *Rec = Field->getParent();
2952
2953 // Work out the buffer layout type to index into.
2954 QualType RecType = CGM.getContext().getCanonicalTagType(Rec);
2955 assert(RecType->isStructureOrClassType() && "Invalid type in HLSL buffer");
2956 // Since this is a member of an object in the buffer and not the buffer's
2957 // struct/class itself, we shouldn't have any offsets on the members we need
2958 // to contend with.
2959 CGHLSLOffsetInfo EmptyOffsets;
2960 llvm::StructType *LayoutTy = HLSLBufferLayoutBuilder(CGM).layOutStruct(
2961 RecType->getAsCanonical<RecordType>(), EmptyOffsets);
2962
2963 // Get the field index for the layout struct, accounting for padding.
2964 unsigned FieldIdx =
2965 CGM.getTypes().getCGRecordLayout(Rec).getLLVMFieldNo(Field);
2966 assert(FieldIdx < LayoutTy->getNumElements() &&
2967 "Layout struct is smaller than member struct");
2968 unsigned Skipped = 0;
2969 for (unsigned I = 0; I <= FieldIdx;) {
2970 llvm::Type *ElementTy = LayoutTy->getElementType(I + Skipped);
2971 if (CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(ElementTy))
2972 ++Skipped;
2973 else
2974 ++I;
2975 }
2976 FieldIdx += Skipped;
2977 assert(FieldIdx < LayoutTy->getNumElements() && "Access out of bounds");
2978
2979 // Now index into the struct, making sure that the type we return is the
2980 // buffer layout type rather than the original type in the AST.
2981 QualType FieldType = Field->getType();
2982 llvm::Type *FieldLLVMTy = CGM.getTypes().ConvertTypeForMem(FieldType);
2984 CGF.CGM.getDataLayout().getABITypeAlign(FieldLLVMTy));
2985
2986 Value *Ptr = CGF.getLangOpts().EmitLogicalPointer
2987 ? CGF.Builder.CreateStructuredGEP(
2988 LayoutTy, Base.getPointer(CGF),
2989 llvm::ConstantInt::get(CGM.IntTy, FieldIdx))
2990 : CGF.Builder.CreateStructGEP(LayoutTy, Base.getPointer(CGF),
2991 FieldIdx, Field->getName());
2992 Address Addr(Ptr, FieldLLVMTy, Align, KnownNonNull);
2993
2994 LValue LV = LValue::MakeAddr(Addr, FieldType, CGM.getContext(),
2996 CGM.getTBAAAccessInfo(FieldType));
2997 LV.getQuals().addCVRQualifiers(Base.getVRQualifiers());
2998
2999 return LV;
3000}
Defines the clang::ASTContext interface.
static bool requiresFlatInterpolation(llvm::Type *Ty)
static llvm::dxil::ElementType getSignatureComponentType(CodeGenModule &CGM, QualType Ty)
static QualType getSemanticLeafType(const clang::DeclaratorDecl *Decl)
static void addSPIRVInterfaceDecorations(llvm::GlobalVariable *GV, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode=llvm::hlsl::InterpolationMode::Undefined)
static llvm::hlsl::SemanticSignatureElement createSemanticSignatureElement(CodeGenModule &CGM, uint32_t SigId, HLSLAppliedSemanticAttr *Semantic, std::optional< unsigned > Index, const SemanticShape &Shape)
static unsigned getSPIRVVkBuiltinID(StringRef BuiltIn)
static void gatherFunctions(SmallVectorImpl< Function * > &Fns, llvm::Module &M, bool CtorOrDtor)
static llvm::Value * createSPIRVInputLoad(IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty, const Twine &Name, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode)
static llvm::hlsl::InterpolationMode getSPIRVInterpolationMode(llvm::hlsl::InterpolationMode InterpMode, llvm::Type *Ty, llvm::Triple::EnvironmentType Stage, llvm::hlsl::IOType IO)
static void addSPIRVQuadAllExecutionModes(CodeGenModule &CGM)
static Value * buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty)
static void createSPIRVOutputStore(IRBuilder<> &B, llvm::Module &M, llvm::Value *Source, const Twine &Name, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode, bool IsSigned=false)
static void markArbitrarySignatureElements(SmallVectorImpl< llvm::hlsl::SemanticSignatureElement > &Signature, size_t FirstElement)
static void initializeBuffer(CodeGenModule &CGM, llvm::GlobalVariable *GV, Intrinsic::ID IntrID, ArrayRef< llvm::Value * > Args)
static llvm::Value * createSPIRVBuiltinDelta(IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty, const Twine &Name, unsigned BuiltInID, unsigned BaseBuiltInID, llvm::hlsl::InterpolationMode InterpMode)
static const clang::HLSLAttributedResourceType * createBufferHandleType(const HLSLBufferDecl *BufDecl)
static SemanticShape getSemanticShape(ASTContext &Ctx, QualType Ty)
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Record Record
Definition MachO.h:31
Defines AST-level helper utilities for matrix types.
llvm::dxbc::PSV::SemanticKind SemanticKind
Definition SemaHLSL.cpp:63
Defines the SourceManager interface.
Defines the clang::TargetOptions class.
C Language Family Type Representation.
bool VisitHLSLOutArgExpr(HLSLOutArgExpr *)
llvm::SmallVector< OpaqueValueExpr *, 8 > OVEs
bool VisitOpaqueValueExpr(OpaqueValueExpr *E)
llvm::SmallPtrSet< OpaqueValueExpr *, 8 > Visited
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:916
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType CharTy
CanQualType IntTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedIntTy
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
QualType withConst() const
Retrieves a version of this type with const applied.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
CharUnits getAlignment() const
Definition Address.h:194
An aggregate value slot.
Definition CGValue.h:551
Address getAddress() const
Definition CGValue.h:689
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:156
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:312
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:239
Abstract information about a function or function prototype.
Definition CGCall.h:43
All available information about a concrete callee.
Definition CGCall.h:66
CGFunctionInfo - Class to encapsulate the information about a function definition.
static const uint32_t Unspecified
static bool compareOffsets(uint32_t LHS, uint32_t RHS)
Comparison function for offsets received from operator[] suitable for use in a stable_sort.
static CGHLSLOffsetInfo fromDecl(const HLSLBufferDecl &BufDecl)
Iterates over all declarations in the HLSL buffer and based on the packoffset or register(c#) annotat...
llvm::Instruction * getConvergenceToken(llvm::BasicBlock &BB)
void setHLSLEntryAttributes(const FunctionDecl *FD, llvm::Function *Fn)
llvm::Value * handleScalarSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
llvm::StructType * getHLSLBufferLayoutType(const RecordType *LayoutStructTy)
void emitEntryFunction(const FunctionDecl *FD, llvm::Function *Fn)
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void handleScalarSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
std::optional< LValue > emitResourceMemberExpr(CodeGenFunction &CGF, const MemberExpr *E)
specific_attr_iterator< HLSLAppliedSemanticAttr > handleStructSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrBegin, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrEnd, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers)
llvm::SmallVectorImpl< llvm::hlsl::SemanticSignatureElement > SemanticSignatures
void addHLSLBufferLayoutType(const RecordType *LayoutStructTy, llvm::StructType *LayoutTy)
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
void emitSystemSemanticStore(llvm::IRBuilder<> &B, llvm::Value *Source, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, llvm::dxbc::PSV::SemanticKind SemanticKind, llvm::Triple::EnvironmentType Stage, std::optional< unsigned > Index, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
bool emitBufferCopy(CodeGenFunction &CGF, const Expr *E, const LValue &SrcLV, AggValueSlot &DestSlot)
std::optional< LValue > emitBufferArraySubscriptExpr(const ArraySubscriptExpr *E, CodeGenFunction &CGF, llvm::function_ref< llvm::Value *(bool Promote)> EmitIdxAfterBase)
std::optional< LValue > emitResourceArraySubscriptExpr(const ArraySubscriptExpr *E, CodeGenFunction &CGF)
void addRootSignature(const HLSLRootSignatureDecl *D)
LValue emitBufferMemberExpr(CodeGenFunction &CGF, const MemberExpr *E)
llvm::Value * emitSystemSemanticLoad(llvm::IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, llvm::dxbc::PSV::SemanticKind SemanticKind, llvm::Triple::EnvironmentType Stage, std::optional< unsigned > Index, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
llvm::Type * convertHLSLSpecificType(const Type *T, const CGHLSLOffsetInfo &OffsetInfo)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
specific_attr_iterator< HLSLAppliedSemanticAttr > handleSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrBegin, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrEnd, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers=llvm::hlsl::InterpolationModifier::None)
void addBuffer(const HLSLBufferDecl *D)
std::pair< llvm::Value *, specific_attr_iterator< HLSLAppliedSemanticAttr > > handleStructSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > begin, specific_attr_iterator< HLSLAppliedSemanticAttr > end, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers)
bool emitGlobalResourceArray(CodeGenFunction &CGF, const Expr *E, AggValueSlot &DestSlot)
void emitInitListOpaqueValues(CodeGenFunction &CGF, InitListExpr *E)
std::pair< llvm::Value *, specific_attr_iterator< HLSLAppliedSemanticAttr > > handleSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > begin, specific_attr_iterator< HLSLAppliedSemanticAttr > end, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers=llvm::hlsl::InterpolationModifier::None)
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:277
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
A non-RAII class containing all the information about a bound opaque value.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
const LangOptions & getLangOpts() const
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1376
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5753
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:236
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:285
llvm::Type * ConvertTypeForMem(QualType T)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1661
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1742
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1777
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
Definition CGExpr.cpp:6640
llvm::LLVMContext & getLLVMContext()
This class organizes the cross-function state that is used while generating LLVM code.
const PreprocessorOptions & getPreprocessorOpts() const
llvm::Module & getModule() const
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
DiagnosticsEngine & getDiags() const
void AddCXXGlobalInit(llvm::Function *F)
const TargetInfo & getTarget() const
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
const llvm::DataLayout & getDataLayout() const
ASTContext & getContext() const
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall, const FunctionDecl *ABIInfoFD)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition CGCall.cpp:730
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
llvm::Constant * getPointer() const
Definition Address.h:308
llvm::StructType * layOutStruct(const RecordType *StructType, const CGHLSLOffsetInfo &OffsetInfo)
Lays out a struct type following HLSL buffer rules and considering any explicit offset information.
llvm::Type * layOutType(QualType Type)
Lays out a type following HLSL buffer rules.
LValue - This represents an lvalue references.
Definition CGValue.h:183
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:454
const Qualifiers & getQuals() const
Definition CGValue.h:350
Address getAddress() const
Definition CGValue.h:373
QualType getType() const
Definition CGValue.h:303
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue get(llvm::Value *V)
Definition CGValue.h:99
An abstract representation of an aligned address.
Definition Address.h:42
llvm::Value * getPointer() const
Definition Address.h:66
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:384
virtual bool isHLSLPadding(llvm::Type *Ty) const
Return true if this is an HLSL padding type.
Definition TargetInfo.h:473
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
int64_t getSExtSize() const
Return the size sign-extended as a uint64_t.
Definition TypeBase.h:3940
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:582
bool hasAttrs() const
Definition DeclBase.h:527
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
SourceLocation getLocation() const
Definition DeclBase.h:448
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:578
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:573
AttrVec & getAttrs()
Definition DeclBase.h:533
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:3039
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5381
bool isCBuffer() const
Definition Decl.h:5425
const CXXRecordDecl * getLayoutStruct() const
Definition Decl.h:5428
bool hasValidPackoffset() const
Definition Decl.h:5427
buffer_decl_range buffer_decls() const
Definition Decl.h:5456
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition Expr.h:7483
ArrayRef< llvm::hlsl::rootsig::RootElement > getRootElements() const
Definition Decl.h:5498
llvm::dxbc::RootSignatureVersion getVersion() const
Definition Decl.h:5496
One of these records is kept for each identifier that is lexed.
Describes an C or C++ initializer list.
Definition Expr.h:5377
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
Represents a parameter to a function.
Definition Decl.h:1832
std::vector< std::pair< std::string, bool > > Macros
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void addCVRQualifiers(unsigned mask)
Definition TypeBase.h:503
Represents a struct/union/class.
Definition Decl.h:4506
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4722
field_iterator field_begin() const
Definition Decl.cpp:5386
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue=nullptr)
Encodes a location in the source.
One instance of this struct is kept for every file loaded or used.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc=SourceLocation()) const
Returns the memory buffer for the associated content.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
const ContentCache & getContentCache() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isHLSLIntangibleType() const
Definition Type.cpp:5733
bool isHLSLResourceRecord() const
Definition Type.cpp:5720
bool isStructureOrClassType() const
Definition Type.cpp:839
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isRecordType() const
Definition TypeBase.h:8942
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5724
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2574
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
Represents a GCC generic vector type.
Definition TypeBase.h:4398
void pushBaseNameHierarchy(CXXRecordDecl *DerivedRD, CXXRecordDecl *BaseRD)
IdentifierInfo * getNameAsIdentifier(ASTContext &AST) const
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
bool hasCounterHandle(const CXXRecordDecl *RD)
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool Load(InterpState &S, CodePtr OpPC)
Definition Interp.h:2189
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
Definition MatrixUtils.h:25
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
unsigned getCounterImplicitOrderID() const