LLVM 24.0.0git
DXILResourceAccess.cpp
Go to the documentation of this file.
1//===- DXILResourceAccess.cpp - Resource access via load/store ------------===//
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
10#include "DirectX.h"
11#include "llvm/ADT/SetVector.h"
15#include "llvm/IR/BasicBlock.h"
16#include "llvm/IR/Dominators.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/Instruction.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/IntrinsicsDirectX.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/User.h"
29#include <optional>
30
31#define DEBUG_TYPE "dxil-resource-access"
32
33using namespace llvm;
34
37 LLVMContext &Context = I->getContext();
38 std::string InstStr;
39 raw_string_ostream InstOS(InstStr);
40 I->print(InstOS);
41 Context.diagnose(
42 DiagnosticInfoGeneric("At resource access:" + Twine(InstStr), DS_Note));
43
44 for (auto *Handle : Handles) {
45 std::string HandleStr;
46 raw_string_ostream HandleOS(HandleStr);
47 Handle->print(HandleOS);
48 Context.diagnose(DiagnosticInfoGeneric(
49 "Uses resource handle:" + Twine(HandleStr), DS_Note));
50 }
51 Context.diagnose(DiagnosticInfoGeneric(
52 "Resource access is not guaranteed to map to a unique global resource"));
53}
54
56 Value *Ptr, uint64_t AccessSize) {
57 Value *Offset = nullptr;
58
59 while (Ptr) {
60 if (auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
61 assert((II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
62 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) &&
63 "Resource access through unexpected intrinsic");
64 return Offset ? Offset : ConstantInt::get(Builder.getInt32Ty(), 0);
65 }
66
68 assert(GEP && "Resource access through unexpected instruction");
69
70 unsigned NumIndices = GEP->getNumIndices();
71 uint64_t IndexScale = DL.getTypeAllocSize(GEP->getSourceElementType());
72 APInt ConstantOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
73 Value *GEPOffset;
74 if (GEP->accumulateConstantOffset(DL, ConstantOffset)) {
75 // We have a constant offset (in bytes).
76 GEPOffset =
77 ConstantInt::get(DL.getIndexType(GEP->getType()), ConstantOffset);
78 IndexScale = 1;
79 } else if (NumIndices == 1) {
80 // If we have a single index we're indexing into a top level array. This
81 // generally only happens with cbuffers.
82 GEPOffset = *GEP->idx_begin();
83 } else if (NumIndices == 2) {
84 // If we have two indices, this should be an access through a pointer.
85 auto *IndexIt = GEP->idx_begin();
86 assert(cast<ConstantInt>(IndexIt)->getZExtValue() == 0 &&
87 "GEP is not indexing through pointer");
88 GEPOffset = *(++IndexIt);
89 } else
90 llvm_unreachable("Unhandled GEP structure for resource access");
91
92 uint64_t ElemSize = AccessSize;
93 if (!(IndexScale % ElemSize)) {
94 // If our scale is an exact multiple of the access size, adjust the
95 // scaling to avoid an unnecessary division.
96 IndexScale /= ElemSize;
97 ElemSize = 1;
98 }
99 if (IndexScale != 1)
100 GEPOffset = Builder.CreateMul(
101 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), IndexScale));
102 if (ElemSize != 1)
103 GEPOffset = Builder.CreateUDiv(
104 GEPOffset, ConstantInt::get(Builder.getInt32Ty(), ElemSize));
105
106 Offset = Offset ? Builder.CreateAdd(Offset, GEPOffset) : GEPOffset;
107 Ptr = GEP->getPointerOperand();
108 }
109
110 llvm_unreachable("GEP of null pointer?");
111}
112
115 const DataLayout &DL = SI->getDataLayout();
116 IRBuilder<> Builder(SI);
117 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
118 Type *ScalarType = ContainedType->getScalarType();
119 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
120
121 Value *V = SI->getValueOperand();
122 if (V->getType() == ContainedType) {
123 // V is already the right type.
124 assert(SI->getPointerOperand() == II &&
125 "Store of whole element has mismatched address to store to");
126 } else if (V->getType() == ScalarType) {
127 // We're storing a scalar, so we need to load the current value and only
128 // replace the relevant part.
129 auto *Load = Builder.CreateIntrinsic(
130 LoadType, Intrinsic::dx_resource_load_typedbuffer,
131 {II->getOperand(0), II->getOperand(1)});
132 auto *Struct = Builder.CreateExtractValue(Load, {0});
133
134 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
135 Value *Offset =
136 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
137 V = Builder.CreateInsertElement(Struct, V, Offset);
138 } else {
139 llvm_unreachable("Store to typed resource has invalid type");
140 }
141
142 auto *Inst = Builder.CreateIntrinsic(
143 Builder.getVoidTy(), Intrinsic::dx_resource_store_typedbuffer,
144 {II->getOperand(0), II->getOperand(1), V});
145 SI->replaceAllUsesWith(Inst);
146}
147
148static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index,
150 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
151 // entirely into the index.
152 if (!RTI.isStruct()) {
153 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
154 if (!ConstantOffset || !ConstantOffset->isZero())
155 Index = Builder.CreateAdd(Index, Offset);
156 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
157 }
158
159 Builder.CreateIntrinsic(Builder.getVoidTy(),
160 Intrinsic::dx_resource_store_rawbuffer,
161 {Buffer, Index, Offset, V});
162}
163
166 const DataLayout &DL = SI->getDataLayout();
167 IRBuilder<> Builder(SI);
168
169 Value *V = SI->getValueOperand();
170 assert(!V->getType()->isAggregateType() &&
171 "Resource store should be scalar or vector type");
172
173 Value *Index = II->getOperand(1);
174 // The offset for the rawbuffer load and store ops is always in bytes.
175 uint64_t AccessSize = 1;
176 Value *Offset =
177 traverseGEPOffsets(DL, Builder, SI->getPointerOperand(), AccessSize);
178
179 auto *VT = dyn_cast<FixedVectorType>(V->getType());
180 if (VT && VT->getNumElements() > 4) {
181 // Split into stores of at most 4 elements.
182 Type *EltTy = VT->getElementType();
183 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
184 4 * (DL.getTypeSizeInBits(EltTy) / 8));
185
186 SmallVector<int, 4> Indices;
187 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
188 if (I > 0)
189 Offset = Builder.CreateAdd(Offset, Stride);
190
191 for (unsigned int J = I, E = std::min(N, J + 4); J < E; ++J)
192 Indices.push_back(J);
193 Value *Part = Builder.CreateShuffleVector(V, Indices);
194 emitRawStore(Builder, II->getOperand(0), Index, Offset, Part, RTI);
195
196 Indices.clear();
197 }
198 } else
199 emitRawStore(Builder, II->getOperand(0), Index, Offset, V, RTI);
200}
201
233
234static std::optional<dxil::AtomicBinOpCode>
274
277 std::optional<dxil::AtomicBinOpCode> BinOpCode =
279 if (!BinOpCode) {
280 reportFatalUsageError("DXIL resource atomicrmw operation not implemented");
281 return;
282 }
283
284 const DataLayout &DL = AI->getDataLayout();
285 IRBuilder<> Builder(AI);
286 Value *Index = II->getOperand(1);
287
288 // The offset for the rawbuffer load/store/atomic ops is always in bytes.
289 uint64_t AccessSize = 1;
290 Value *Offset =
291 traverseGEPOffsets(DL, Builder, AI->getPointerOperand(), AccessSize);
292
293 // For non-struct buffers (RawBuffer or TypedBuffer), fold the byte offset
294 // into the index and mark the coord1 arg as poison — only StructuredBuffer
295 // atomics use both a struct index and a byte offset.
296 if (!RTI.isStruct()) {
297 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
298 if (!ConstantOffset || !ConstantOffset->isZero())
299 Index = Builder.CreateAdd(Index, Offset);
300 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
301 }
302
303 Value *BinOp = Builder.getInt32(static_cast<uint32_t>(*BinOpCode));
304
305 // Emit the target-independent intrinsic; DXILOpLowering lowers it to the
306 // DXIL `AtomicBinOp` op and handles the target-ext-typed handle cast via
307 // its `createTmpHandleCast` bookkeeping.
308 Value *Result = Builder.CreateIntrinsic(
309 AI->getType(), Intrinsic::dx_resource_atomic_binop,
310 {II->getOperand(0), BinOp, Index, Offset, AI->getValOperand()});
311
312 AI->replaceAllUsesWith(Result);
313}
314
349
352 const DataLayout &DL = LI->getDataLayout();
353 IRBuilder<> Builder(LI);
354 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
355 Type *LoadType = StructType::get(ContainedType, Builder.getInt1Ty());
356
357 Value *V =
358 Builder.CreateIntrinsic(LoadType, Intrinsic::dx_resource_load_typedbuffer,
359 {II->getOperand(0), II->getOperand(1)});
360 V = Builder.CreateExtractValue(V, {0});
361
362 Type *ScalarType = ContainedType->getScalarType();
363 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
364 Value *Offset =
365 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
366 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
367 if (!ConstantOffset || !ConstantOffset->isZero())
368 V = Builder.CreateExtractElement(V, Offset);
369
370 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
371 // shufflevector), then make sure we're maintaining the resulting type.
372 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
373 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
374 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
375 Builder.getInt32(0));
376
377 LI->replaceAllUsesWith(V);
378}
379
382 const DataLayout &DL = LI->getDataLayout();
383 IRBuilder<> Builder(LI);
384 Type *ContainedType = RTI.getHandleTy()->getTypeParameter(0);
385
386 Value *Handle = II->getOperand(0);
387 Value *Coords = II->getOperand(1);
388
389 // For operator[], mip level is 0.
390 Value *MipLevel = Builder.getInt32(0);
391
392 // For operator[], offsets are zero.
393 Type *CoordTy = Coords->getType();
394 Type *OffsetTy;
395 if (auto *VecTy = dyn_cast<FixedVectorType>(CoordTy))
396 OffsetTy =
397 FixedVectorType::get(Builder.getInt32Ty(), VecTy->getNumElements());
398 else
399 OffsetTy = Builder.getInt32Ty();
400 Value *Offsets = Constant::getNullValue(OffsetTy);
401
402 Value *V =
403 Builder.CreateIntrinsic(ContainedType, Intrinsic::dx_resource_load_level,
404 {Handle, Coords, MipLevel, Offsets});
405
406 Type *ScalarType = ContainedType->getScalarType();
407 uint64_t AccessSize = DL.getTypeSizeInBits(ScalarType) / 8;
408 Value *Offset =
409 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
410 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
411 if (!ConstantOffset || !ConstantOffset->isZero())
412 V = Builder.CreateExtractElement(V, Offset);
413
414 // If we loaded a <1 x ...> instead of a scalar (presumably to feed a
415 // shufflevector), then make sure we're maintaining the resulting type.
416 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType()))
417 if (VT->getNumElements() == 1 && !isa<FixedVectorType>(V->getType()))
418 V = Builder.CreateInsertElement(PoisonValue::get(VT), V,
419 Builder.getInt32(0));
420
421 LI->replaceAllUsesWith(V);
422}
423
424static Value *emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer,
425 Value *Index, Value *Offset,
427 // For raw buffer (ie, HLSL's ByteAddressBuffer), we need to fold the access
428 // entirely into the index.
429 if (!RTI.isStruct()) {
430 auto *ConstantOffset = dyn_cast<ConstantInt>(Offset);
431 if (!ConstantOffset || !ConstantOffset->isZero())
432 Index = Builder.CreateAdd(Index, Offset);
433 Offset = llvm::PoisonValue::get(Builder.getInt32Ty());
434 }
435
436 // The load intrinsic includes the bit for CheckAccessFullyMapped, so we need
437 // to add that to the return type.
438 Type *TypeWithCheck = StructType::get(Ty, Builder.getInt1Ty());
439 Value *V = Builder.CreateIntrinsic(TypeWithCheck,
440 Intrinsic::dx_resource_load_rawbuffer,
441 {Buffer, Index, Offset});
442 return Builder.CreateExtractValue(V, {0});
443}
444
447 const DataLayout &DL = LI->getDataLayout();
448 IRBuilder<> Builder(LI);
449
450 Value *Index = II->getOperand(1);
451 // The offset for the rawbuffer load and store ops is always in bytes.
452 uint64_t AccessSize = 1;
453 Value *Offset =
454 traverseGEPOffsets(DL, Builder, LI->getPointerOperand(), AccessSize);
455
456 // TODO: We could make this handle aggregates by walking the structure and
457 // handling each field individually, but we don't ever generate code that
458 // would hit that so it seems superfluous.
459 assert(!LI->getType()->isAggregateType() &&
460 "Resource load should be scalar or vector type");
461
462 Value *V;
463 if (auto *VT = dyn_cast<FixedVectorType>(LI->getType())) {
464 // Split into loads of at most 4 elements.
465 Type *EltTy = VT->getElementType();
466 Value *Stride = ConstantInt::get(Builder.getInt32Ty(),
467 4 * (DL.getTypeSizeInBits(EltTy) / 8));
468
470 for (unsigned int I = 0, N = VT->getNumElements(); I < N; I += 4) {
471 Type *Ty = FixedVectorType::get(EltTy, N - I < 4 ? N - I : 4);
472 if (I > 0)
473 Offset = Builder.CreateAdd(Offset, Stride);
474 Parts.push_back(
475 emitRawLoad(Builder, Ty, II->getOperand(0), Index, Offset, RTI));
476 }
477
478 V = Parts.size() > 1 ? concatenateVectors(Builder, Parts) : Parts[0];
479 } else
480 V = emitRawLoad(Builder, LI->getType(), II->getOperand(0), Index, Offset,
481 RTI);
482
483 LI->replaceAllUsesWith(V);
484}
485
486namespace {
487/// Helper for building a `load.cbufferrow` intrinsic given a simple type.
488struct CBufferRowIntrin {
489 Intrinsic::ID IID;
490 Type *RetTy;
491 unsigned int EltSize;
492 unsigned int NumElts;
493
494 CBufferRowIntrin(const DataLayout &DL, Type *Ty) {
495 assert(Ty == Ty->getScalarType() && "Expected scalar type");
496
497 switch (DL.getTypeSizeInBits(Ty)) {
498 case 16:
499 IID = Intrinsic::dx_resource_load_cbufferrow_8;
500 RetTy = StructType::get(Ty, Ty, Ty, Ty, Ty, Ty, Ty, Ty);
501 EltSize = 2;
502 NumElts = 8;
503 break;
504 case 32:
505 IID = Intrinsic::dx_resource_load_cbufferrow_4;
506 RetTy = StructType::get(Ty, Ty, Ty, Ty);
507 EltSize = 4;
508 NumElts = 4;
509 break;
510 case 64:
511 IID = Intrinsic::dx_resource_load_cbufferrow_2;
512 RetTy = StructType::get(Ty, Ty);
513 EltSize = 8;
514 NumElts = 2;
515 break;
516 default:
517 llvm_unreachable("Only 16, 32, and 64 bit types supported");
518 }
519 }
520};
521} // namespace
522
525 const DataLayout &DL = LI->getDataLayout();
526
527 Type *Ty = LI->getType();
528 assert(!isa<StructType>(Ty) && "Structs not handled yet");
529 CBufferRowIntrin Intrin(DL, Ty->getScalarType());
530
531 StringRef Name = LI->getName();
532 Value *Handle = II->getOperand(0);
533
534 IRBuilder<> Builder(LI);
535
536 ConstantInt *GlobalOffset =
537 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer
538 ? ConstantInt::get(Builder.getInt32Ty(), 0)
539 : dyn_cast<ConstantInt>(II->getOperand(1));
540 assert(GlobalOffset && "CBuffer getpointer index must be constant");
541
542 uint64_t GlobalOffsetVal = GlobalOffset->getZExtValue();
543 Value *CurrentRow = ConstantInt::get(
544 Builder.getInt32Ty(), GlobalOffsetVal / hlsl::CBufferRowSizeInBytes);
545 unsigned int CurrentIndex =
546 (GlobalOffsetVal % hlsl::CBufferRowSizeInBytes) / Intrin.EltSize;
547
548 // Every object in a cbuffer either fits in a row or is aligned to a row. This
549 // means that only the very last pointer access can point into a row.
550 auto *LastGEP = dyn_cast<GEPOperator>(LI->getPointerOperand());
551 if (!LastGEP) {
552 // If we don't have a GEP at all we're just accessing the resource through
553 // the result of getpointer directly.
554 assert(LI->getPointerOperand() == II &&
555 "Unexpected indirect access to resource without GEP");
556 } else {
557 Value *GEPOffset = traverseGEPOffsets(
558 DL, Builder, LastGEP->getPointerOperand(), hlsl::CBufferRowSizeInBytes);
559 CurrentRow = Builder.CreateAdd(GEPOffset, CurrentRow);
560
561 APInt ConstantOffset(DL.getIndexTypeSizeInBits(LastGEP->getType()), 0);
562 if (LastGEP->accumulateConstantOffset(DL, ConstantOffset)) {
563 APInt Remainder(DL.getIndexTypeSizeInBits(LastGEP->getType()),
565 APInt::udivrem(ConstantOffset, Remainder, ConstantOffset, Remainder);
566 CurrentRow = Builder.CreateAdd(
567 CurrentRow, ConstantInt::get(Builder.getInt32Ty(), ConstantOffset));
568 CurrentIndex += Remainder.udiv(Intrin.EltSize).getZExtValue();
569 } else {
570 assert(LastGEP->getNumIndices() == 1 &&
571 "Last GEP of cbuffer access is not array or struct access");
572 // We assume a non-constant access will be row-aligned. This is safe
573 // because arrays and structs are always row aligned, and accesses to
574 // vector elements will show up as a load of the vector followed by an
575 // extractelement.
576 CurrentRow = cast<ConstantInt>(CurrentRow)->isZero()
577 ? *LastGEP->idx_begin()
578 : Builder.CreateAdd(CurrentRow, *LastGEP->idx_begin());
579 CurrentIndex = 0;
580 }
581 }
582
583 auto *CBufLoad = Builder.CreateIntrinsic(
584 Intrin.RetTy, Intrin.IID, {Handle, CurrentRow}, nullptr, Name + ".load");
585 auto *Elt =
586 Builder.CreateExtractValue(CBufLoad, {CurrentIndex++}, Name + ".extract");
587
588 // At this point we've loaded the first scalar of our result, but our original
589 // type may have been a vector.
590 unsigned int Remaining =
591 ((DL.getTypeSizeInBits(Ty) / 8) / Intrin.EltSize) - 1;
592 if (Remaining == 0) {
593 // We only have a single element, so we're done.
594 Value *Result = Elt;
595
596 // However, if we loaded a <1 x T>, then we need to adjust the type.
597 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
598 assert(VT->getNumElements() == 1 && "Can't have multiple elements here");
599 Result = Builder.CreateInsertElement(PoisonValue::get(VT), Result,
600 Builder.getInt32(0), Name);
601 }
602 LI->replaceAllUsesWith(Result);
603 return;
604 }
605
606 // Walk each element and extract it, wrapping to new rows as needed.
607 SmallVector<Value *> Extracts{Elt};
608 while (Remaining--) {
609 CurrentIndex %= Intrin.NumElts;
610
611 if (CurrentIndex == 0) {
612 CurrentRow = Builder.CreateAdd(CurrentRow,
613 ConstantInt::get(Builder.getInt32Ty(), 1));
614 CBufLoad = Builder.CreateIntrinsic(Intrin.RetTy, Intrin.IID,
615 {Handle, CurrentRow}, nullptr,
616 Name + ".load");
617 }
618
619 Extracts.push_back(Builder.CreateExtractValue(CBufLoad, {CurrentIndex++},
620 Name + ".extract"));
621 }
622
623 // Finally, we build up the original loaded value.
624 Value *Result = PoisonValue::get(Ty);
625 for (int I = 0, E = Extracts.size(); I < E; ++I)
626 Result = Builder.CreateInsertElement(
627 Result, Extracts[I], Builder.getInt32(I), Name + formatv(".upto{}", I));
628 LI->replaceAllUsesWith(Result);
629}
630
664
666 if (auto *LI = dyn_cast<LoadInst>(AI))
667 return dyn_cast<Instruction>(LI->getPointerOperand());
668 if (auto *SI = dyn_cast<StoreInst>(AI))
669 return dyn_cast<Instruction>(SI->getPointerOperand());
670 if (auto *RMWI = dyn_cast<AtomicRMWInst>(AI))
671 return dyn_cast<Instruction>(RMWI->getPointerOperand());
672
673 return nullptr;
674}
675
676static const std::array<Intrinsic::ID, 2> HandleIntrins = {
677 Intrinsic::dx_resource_handlefrombinding,
678 Intrinsic::dx_resource_handlefromimplicitbinding,
679};
680
682 SmallVector<Value *> Worklist = {Ptr};
684
685 while (!Worklist.empty()) {
686 Value *X = Worklist.pop_back_val();
687
688 if (!X->getType()->isPointerTy() && !X->getType()->isTargetExtTy())
689 return {}; // Early exit on store/load into non-resource
690
691 if (auto *Phi = dyn_cast<PHINode>(X))
692 for (Use &V : Phi->incoming_values())
693 Worklist.push_back(V.get());
694 else if (auto *Select = dyn_cast<SelectInst>(X))
695 for (Value *V : {Select->getTrueValue(), Select->getFalseValue()})
696 Worklist.push_back(V);
697 else if (auto *II = dyn_cast<IntrinsicInst>(X)) {
698 Intrinsic::ID IID = II->getIntrinsicID();
699
700 if (IID == Intrinsic::dx_resource_getpointer)
701 Worklist.push_back(II->getArgOperand(/*Handle=*/0));
702
704 Handles.push_back(II);
705 }
706 }
707
708 return Handles;
709}
710
712 DXILResourceTypeMap &DRTM) {
714 "Only expects a Handle as determined from collectUsedHandles.");
715
716 auto *HandleTy = cast<TargetExtType>(Handle->getType());
717 dxil::ResourceClass Class = DRTM[HandleTy].getResourceClass();
718 uint32_t Space = cast<ConstantInt>(Handle->getArgOperand(0))->getZExtValue();
719 uint32_t LowerBound =
720 cast<ConstantInt>(Handle->getArgOperand(1))->getZExtValue();
721 uint32_t Size = cast<ConstantInt>(Handle->getArgOperand(2))->getZExtValue();
722 uint32_t UpperBound = Size == UINT32_MAX ? UINT32_MAX : LowerBound + Size - 1;
723
724 return hlsl::Binding(Class, Space, LowerBound, UpperBound, nullptr);
725}
726
727namespace {
728/// Helper for propagating the current handle and ptr indices.
729struct AccessIndices {
730 Value *GetPtrIdx;
731 Value *HandleIdx;
732
733 bool hasGetPtrIdx() { return GetPtrIdx != nullptr; }
734 bool hasHandleIdx() { return HandleIdx != nullptr; }
735};
736} // namespace
737
738// getAccessIndices traverses up the control flow that a ptr came from and
739// propagates back the indicies used to access the resource (AccessIndices):
740//
741// - GetPtrIdx is the index of dx.resource.getpointer
742// - HandleIdx is the index of dx.resource.handlefrom.*
743static AccessIndices
745 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
746 if (llvm::is_contained(HandleIntrins, II->getIntrinsicID())) {
747 DeadInsts.insert(II);
748 return {nullptr, II->getArgOperand(/*Index=*/3)};
749 }
750
751 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer) {
752 auto *V = dyn_cast<Instruction>(II->getArgOperand(/*Handle=*/0));
753 auto AccessIdx = getAccessIndices(V, DeadInsts);
754 assert(!AccessIdx.hasGetPtrIdx() &&
755 "Encountered multiple dx.resource.getpointers in ptr chain?");
756 AccessIdx.GetPtrIdx = II->getArgOperand(1);
757
758 DeadInsts.insert(II);
759 return AccessIdx;
760 }
761 }
762
763 if (auto *Phi = dyn_cast<PHINode>(I)) {
764 unsigned NumEdges = Phi->getNumIncomingValues();
765 assert(NumEdges != 0 && "Malformed Phi Node");
766
767 IRBuilder<> Builder(Phi);
768 PHINode *GetPtrPhi = PHINode::Create(Builder.getInt32Ty(), NumEdges);
769 PHINode *HandlePhi = PHINode::Create(Builder.getInt32Ty(), NumEdges);
770
771 bool HasGetPtr = true;
772 for (unsigned Idx = 0; Idx < NumEdges; Idx++) {
773 auto *BB = Phi->getIncomingBlock(Idx);
774 auto *V = dyn_cast<Instruction>(Phi->getIncomingValue(Idx));
775 auto AccessIdx = getAccessIndices(V, DeadInsts);
776 HasGetPtr &= AccessIdx.hasGetPtrIdx();
777 if (HasGetPtr)
778 GetPtrPhi->addIncoming(AccessIdx.GetPtrIdx, BB);
779 HandlePhi->addIncoming(AccessIdx.HandleIdx, BB);
780 }
781
782 if (HasGetPtr)
783 Builder.Insert(GetPtrPhi);
784 else
785 GetPtrPhi = nullptr;
786
787 Builder.Insert(HandlePhi);
788
789 DeadInsts.insert(Phi);
790 return {GetPtrPhi, HandlePhi};
791 }
792
793 if (auto *Select = dyn_cast<SelectInst>(I)) {
794 auto *TrueV = dyn_cast<Instruction>(Select->getTrueValue());
795 auto TrueAccessIdx = getAccessIndices(TrueV, DeadInsts);
796
797 auto *FalseV = dyn_cast<Instruction>(Select->getFalseValue());
798 auto FalseAccessIdx = getAccessIndices(FalseV, DeadInsts);
799
800 IRBuilder<> Builder(Select);
801 Value *GetPtrSelect = nullptr;
802
803 if (TrueAccessIdx.hasGetPtrIdx() && FalseAccessIdx.hasGetPtrIdx())
804 GetPtrSelect =
805 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.GetPtrIdx,
806 FalseAccessIdx.GetPtrIdx);
807
808 auto *HandleSelect =
809 Builder.CreateSelect(Select->getCondition(), TrueAccessIdx.HandleIdx,
810 FalseAccessIdx.HandleIdx);
811 DeadInsts.insert(Select);
812 return {GetPtrSelect, HandleSelect};
813 }
814
815 llvm_unreachable("collectUsedHandles should assure this does not occur");
816}
817
818static void
821 auto AccessIdx = getAccessIndices(Ptr, DeadInsts);
822 assert(AccessIdx.hasGetPtrIdx() && AccessIdx.hasHandleIdx() &&
823 "Couldn't retrieve indices. This is guaranteed by getAccessIndices");
824
825 IRBuilder<> Builder(Ptr);
826 IntrinsicInst *Handle = cast<IntrinsicInst>(OldHandle->clone());
827 Handle->setArgOperand(/*Index=*/3, AccessIdx.HandleIdx);
828 Builder.Insert(Handle);
829
830 auto *GetPtr =
831 Builder.CreateIntrinsic(Ptr->getType(), Intrinsic::dx_resource_getpointer,
832 {Handle, AccessIdx.GetPtrIdx});
833
834 Ptr->replaceAllUsesWith(GetPtr);
835 DeadInsts.insert(Ptr);
836}
837
838// Try to legalize dx.resource.handlefrom.*.binding and dx.resource.getpointer
839// calls with their respective index values and propagate the index values to
840// be used at resource access.
841//
842// If it can't be transformed to be legal then:
843//
844// Reports an error if a resource access is not guaranteed into a unique global
845// resource.
846//
847// Returns true if any changes are made.
850 for (BasicBlock &BB : make_early_inc_range(F)) {
851 for (Instruction &I : BB) {
852 if (auto *PtrOp = getStoreLoadPointerOperand(&I)) {
854 unsigned NumHandles = Handles.size();
855 if (NumHandles <= 1)
856 continue; // Legal, no-replacement required
857
858 bool SameGlobalBinding = true;
859 hlsl::Binding B = getHandleIntrinsicBinding(Handles[0], DRTM);
860 for (unsigned Idx = 1; Idx < NumHandles; Idx++)
861 SameGlobalBinding &=
862 (B == getHandleIntrinsicBinding(Handles[Idx], DRTM));
863
864 if (!SameGlobalBinding) {
866 continue;
867 }
868
869 replaceHandleWithIndices(PtrOp, Handles[0], DeadInsts);
870 }
871 }
872 }
873
874 bool MadeChanges = false;
875
876 for (auto *I : llvm::reverse(DeadInsts))
877 if (I->hasNUses(0)) { // Handle can still be used outside of replaced path
878 I->eraseFromParent();
879 MadeChanges = true;
880 }
881
882 return MadeChanges;
883}
884
886 SmallVector<User *> Worklist;
887 for (User *U : II->users())
888 Worklist.push_back(U);
889
891 while (!Worklist.empty()) {
892 User *U = Worklist.back();
893 Worklist.pop_back();
894
895 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
896 for (User *U : GEP->users())
897 Worklist.push_back(U);
898 DeadInsts.push_back(GEP);
899
900 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
901 assert(SI->getValueOperand() != II && "Pointer escaped!");
903 DeadInsts.push_back(SI);
904
905 } else if (auto *LI = dyn_cast<LoadInst>(U)) {
906 createLoadIntrinsic(II, LI, RTI);
907 DeadInsts.push_back(LI);
908 } else if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
910 DeadInsts.push_back(AI);
911 } else
912 llvm_unreachable("Unhandled instruction - pointer escaped?");
913 }
914
915 // Traverse the now-dead instructions in RPO and remove them.
916 for (Instruction *Dead : llvm::reverse(DeadInsts))
917 Dead->eraseFromParent();
918 II->eraseFromParent();
919}
920
924 for (Instruction &I : BB)
925 if (auto *II = dyn_cast<IntrinsicInst>(&I))
926 if (II->getIntrinsicID() == Intrinsic::dx_resource_getpointer ||
927 II->getIntrinsicID() == Intrinsic::dx_resource_getbasepointer) {
928 auto *HandleTy = cast<TargetExtType>(II->getArgOperand(0)->getType());
929 assert(
930 (DRTM[HandleTy].isCBuffer() ||
931 II->getIntrinsicID() != Intrinsic::dx_resource_getbasepointer) &&
932 "dx_resource_getbasepointer should only be used by cbuffers");
933 Resources.emplace_back(II, DRTM[HandleTy]);
934 }
935
936 for (auto &[II, RI] : Resources)
937 replaceAccess(II, RI);
938
939 return !Resources.empty();
940}
941
944 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
945 DXILResourceTypeMap *DRTM =
946 MAMProxy.getCachedResult<DXILResourceTypeAnalysis>(*F.getParent());
947 assert(DRTM && "DXILResourceTypeAnalysis must be available");
948
949 bool MadeHandleChanges = legalizeResourceHandles(F, *DRTM);
950 bool MadeResourceChanges = transformResourcePointers(F, *DRTM);
951 if (!(MadeHandleChanges || MadeResourceChanges))
952 return PreservedAnalyses::all();
953
957 return PA;
958}
959
960namespace {
961class DXILResourceAccessLegacy : public FunctionPass {
962public:
963 bool runOnFunction(Function &F) override {
964 DXILResourceTypeMap &DRTM =
965 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
966 bool MadeHandleChanges = legalizeResourceHandles(F, DRTM);
967 bool MadeResourceChanges = transformResourcePointers(F, DRTM);
968 return MadeHandleChanges || MadeResourceChanges;
969 }
970 StringRef getPassName() const override { return "DXIL Resource Access"; }
971 DXILResourceAccessLegacy() : FunctionPass(ID) {}
972
973 static char ID; // Pass identification.
974 void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
975 AU.addRequired<DXILResourceTypeWrapperPass>();
976 AU.addPreserved<DominatorTreeWrapperPass>();
977 }
978};
979char DXILResourceAccessLegacy::ID = 0;
980} // end anonymous namespace
981
982INITIALIZE_PASS_BEGIN(DXILResourceAccessLegacy, DEBUG_TYPE,
983 "DXIL Resource Access", false, false)
985INITIALIZE_PASS_END(DXILResourceAccessLegacy, DEBUG_TYPE,
986 "DXIL Resource Access", false, false)
987
989 return new DXILResourceAccessLegacy();
990}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Remove Unused Resources
static void diagnoseNonUniqueResourceAccess(Instruction *I, ArrayRef< IntrinsicInst * > Handles)
static std::optional< dxil::AtomicBinOpCode > getAtomicBinOpCode(AtomicRMWInst::BinOp BinOp)
static void createLoadIntrinsic(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static Value * emitRawLoad(IRBuilder<> &Builder, Type *Ty, Value *Buffer, Value *Index, Value *Offset, dxil::ResourceTypeInfo &RTI)
static bool legalizeResourceHandles(Function &F, DXILResourceTypeMap &DRTM)
static AccessIndices getAccessIndices(Instruction *I, SmallSetVector< Instruction *, 16 > &DeadInsts)
static void createTypedBufferLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createTypedBufferStore(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static SmallVector< IntrinsicInst * > collectUsedHandles(Value *Ptr)
static const std::array< Intrinsic::ID, 2 > HandleIntrins
static bool transformResourcePointers(Function &F, DXILResourceTypeMap &DRTM)
static void createTextureLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void replaceHandleWithIndices(Instruction *Ptr, IntrinsicInst *OldHandle, SmallSetVector< Instruction *, 16 > &DeadInsts)
static void emitRawStore(IRBuilder<> &Builder, Value *Buffer, Value *Index, Value *Offset, Value *V, dxil::ResourceTypeInfo &RTI)
static Value * traverseGEPOffsets(const DataLayout &DL, IRBuilder<> &Builder, Value *Ptr, uint64_t AccessSize)
static hlsl::Binding getHandleIntrinsicBinding(IntrinsicInst *Handle, DXILResourceTypeMap &DRTM)
static void createStoreIntrinsic(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static void createCBufferLoad(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createRawStores(IntrinsicInst *II, StoreInst *SI, dxil::ResourceTypeInfo &RTI)
static void createRawLoads(IntrinsicInst *II, LoadInst *LI, dxil::ResourceTypeInfo &RTI)
static void createAtomicBinOp(IntrinsicInst *II, AtomicRMWInst *AI, dxil::ResourceTypeInfo &RTI)
static Instruction * getStoreLoadPointerOperand(Instruction *AI)
static void createAtomicBinOpIntrinsic(IntrinsicInst *II, AtomicRMWInst *AI, dxil::ResourceTypeInfo &RTI)
static void replaceAccess(IntrinsicInst *II, dxil::ResourceTypeInfo &RTI)
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file implements a set that has insertion order iteration characteristics.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1793
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
Value * getPointerOperand()
BinOp getOperation() const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
Type * getTypeParameter(unsigned i) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:319
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
TargetExtType * getHandleTy() const
LLVM_ABI bool isStruct() const
dxil::ResourceKind getResourceKind() const
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
const unsigned CBufferRowSizeInBytes
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
@ Dead
Unused definition.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
FunctionPass * createDXILResourceAccessLegacyPass()
Pass to update resource accesses to use load/store directly.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N