Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilCounters.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilCounters.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilCounters.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilOperations.h"
using namespace llvm;
using namespace hlsl;
using namespace hlsl::DXIL;
namespace hlsl {
namespace {
struct PointerInfo {
enum class MemType : unsigned {
Unknown = 0,
Global_Static,
Global_TGSM,
Alloca
};
MemType memType : 2;
bool isArray : 1;
PointerInfo() : memType(MemType::Unknown), isArray(false) {}
};
typedef DenseMap<Value *, PointerInfo> PointerInfoMap;
PointerInfo GetPointerInfo(Value *V, PointerInfoMap &ptrInfoMap) {
auto it = ptrInfoMap.find(V);
if (it != ptrInfoMap.end())
return it->second;
Type *Ty = V->getType()->getPointerElementType();
ptrInfoMap[V].isArray = Ty->isArrayTy();
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
if (GV->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
ptrInfoMap[V].memType = PointerInfo::MemType::Global_TGSM;
else if (!GV->isConstant() &&
GV->getLinkage() ==
GlobalVariable::LinkageTypes::InternalLinkage &&
GV->getType()->getPointerAddressSpace() == DXIL::kDefaultAddrSpace)
ptrInfoMap[V].memType = PointerInfo::MemType::Global_Static;
} else if (isa<AllocaInst>(V)) {
ptrInfoMap[V].memType = PointerInfo::MemType::Alloca;
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
ptrInfoMap[V] = GetPointerInfo(GEP->getPointerOperand(), ptrInfoMap);
} else if (BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
ptrInfoMap[V] = GetPointerInfo(BC->getOperand(0), ptrInfoMap);
} else if (AddrSpaceCastInst *AC = dyn_cast<AddrSpaceCastInst>(V)) {
ptrInfoMap[V] = GetPointerInfo(AC->getOperand(0), ptrInfoMap);
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
if (CE->getOpcode() == LLVMAddrSpaceCast)
llvm_unreachable("address space cast is illegal in DxilCounters.");
//} else if (PHINode *PN = dyn_cast<PHINode>(V)) {
// for (auto it = PN->value_op_begin(), e = PN->value_op_end(); it != e;
// ++it) {
// PI = GetPointerInfo(*it, ptrInfoMap);
// if (PI.memType != PointerInfo::MemType::Unknown)
// break;
// }
}
return ptrInfoMap[V];
}
struct ValueInfo {
bool isCbuffer : 1;
bool isConstant : 1;
ValueInfo() : isCbuffer(false), isConstant(false) {}
ValueInfo Combine(const ValueInfo &other) const {
ValueInfo R;
R.isCbuffer = isCbuffer && other.isCbuffer;
R.isConstant = isConstant && other.isConstant;
return R;
}
};
/*<py>
def tab_lines(text):
return [' ' + line for line in text.splitlines()]
def gen_count_dxil_op(counter):
return (['bool CountDxilOp_%s(unsigned op) {' % counter] +
tab_lines(
hctdb_instrhelp.get_instrs_pred("op",
hctdb_instrhelp.counter_pred(counter, True))) +
['}'])
def gen_count_llvm_op(counter):
return (['bool CountLlvmOp_%s(unsigned op) {' % counter] +
tab_lines(
hctdb_instrhelp.get_instrs_pred("op",
hctdb_instrhelp.counter_pred(counter, False), 'llvm_id')) +
['}'])
def gen_counter_functions():
lines = ['// Counter functions for Dxil ops:']
for counter in hctdb_instrhelp.get_dxil_op_counters():
lines += gen_count_dxil_op(counter)
lines.append('// Counter functions for llvm ops:')
for counter in hctdb_instrhelp.get_llvm_op_counters():
lines += gen_count_llvm_op(counter)
return lines
</py>*/
// <py::lines('OPCODE-COUNTERS')>gen_counter_functions()</py>
// OPCODE-COUNTERS:BEGIN
// Counter functions for Dxil ops:
bool CountDxilOp_atomic(unsigned op) {
// Instructions: BufferUpdateCounter=70, AtomicBinOp=78,
// AtomicCompareExchange=79
return op == 70 || (78 <= op && op <= 79);
}
bool CountDxilOp_barrier(unsigned op) {
// Instructions: Barrier=80
return op == 80;
}
bool CountDxilOp_floats(unsigned op) {
// Instructions: FAbs=6, Saturate=7, IsNaN=8, IsInf=9, IsFinite=10,
// IsNormal=11, Cos=12, Sin=13, Tan=14, Acos=15, Asin=16, Atan=17, Hcos=18,
// Hsin=19, Htan=20, Exp=21, Frc=22, Log=23, Sqrt=24, Rsqrt=25, Round_ne=26,
// Round_ni=27, Round_pi=28, Round_z=29, FMax=35, FMin=36, Fma=47, Dot2=54,
// Dot3=55, Dot4=56, Dot2AddHalf=162
return (6 <= op && op <= 29) || (35 <= op && op <= 36) || op == 47 ||
(54 <= op && op <= 56) || op == 162;
}
bool CountDxilOp_gs_cut(unsigned op) {
// Instructions: CutStream=98, EmitThenCutStream=99
return (98 <= op && op <= 99);
}
bool CountDxilOp_gs_emit(unsigned op) {
// Instructions: EmitStream=97, EmitThenCutStream=99
return op == 97 || op == 99;
}
bool CountDxilOp_ints(unsigned op) {
// Instructions: IMax=37, IMin=38, IMul=41, IMad=48, Ibfe=51,
// Dot4AddI8Packed=163
return (37 <= op && op <= 38) || op == 41 || op == 48 || op == 51 ||
op == 163;
}
bool CountDxilOp_sig_ld(unsigned op) {
// Instructions: LoadInput=4, LoadOutputControlPoint=103,
// LoadPatchConstant=104
return op == 4 || (103 <= op && op <= 104);
}
bool CountDxilOp_sig_st(unsigned op) {
// Instructions: StoreOutput=5, StorePatchConstant=106, StoreVertexOutput=171,
// StorePrimitiveOutput=172
return op == 5 || op == 106 || (171 <= op && op <= 172);
}
bool CountDxilOp_tex_bias(unsigned op) {
// Instructions: SampleBias=61
return op == 61;
}
bool CountDxilOp_tex_cmp(unsigned op) {
// Instructions: SampleCmp=64, SampleCmpLevelZero=65, TextureGatherCmp=74,
// SampleCmpLevel=224
return (64 <= op && op <= 65) || op == 74 || op == 224;
}
bool CountDxilOp_tex_grad(unsigned op) {
// Instructions: SampleGrad=63
return op == 63;
}
bool CountDxilOp_tex_load(unsigned op) {
// Instructions: TextureLoad=66, BufferLoad=68, RawBufferLoad=139
return op == 66 || op == 68 || op == 139;
}
bool CountDxilOp_tex_norm(unsigned op) {
// Instructions: Sample=60, SampleLevel=62, TextureGather=73,
// TextureGatherRaw=223
return op == 60 || op == 62 || op == 73 || op == 223;
}
bool CountDxilOp_tex_store(unsigned op) {
// Instructions: TextureStore=67, BufferStore=69, RawBufferStore=140,
// WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175,
// WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177,
// TextureStoreSample=225
return op == 67 || op == 69 || op == 140 || (174 <= op && op <= 177) ||
op == 225;
}
bool CountDxilOp_uints(unsigned op) {
// Instructions: Bfrev=30, Countbits=31, FirstbitLo=32, FirstbitHi=33,
// FirstbitSHi=34, UMax=39, UMin=40, UMul=42, UDiv=43, UAddc=44, USubb=45,
// UMad=49, Msad=50, Ubfe=52, Bfi=53, Dot4AddU8Packed=164
return (30 <= op && op <= 34) || (39 <= op && op <= 40) ||
(42 <= op && op <= 45) || (49 <= op && op <= 50) ||
(52 <= op && op <= 53) || op == 164;
}
// Counter functions for llvm ops:
bool CountLlvmOp_atomic(unsigned op) {
// Instructions: AtomicCmpXchg=31, AtomicRMW=32
return (31 <= op && op <= 32);
}
bool CountLlvmOp_fence(unsigned op) {
// Instructions: Fence=30
return op == 30;
}
bool CountLlvmOp_floats(unsigned op) {
// Instructions: FAdd=9, FSub=11, FMul=13, FDiv=16, FRem=19, FPToUI=36,
// FPToSI=37, UIToFP=38, SIToFP=39, FPTrunc=40, FPExt=41, FCmp=47
return op == 9 || op == 11 || op == 13 || op == 16 || op == 19 ||
(36 <= op && op <= 41) || op == 47;
}
bool CountLlvmOp_ints(unsigned op) {
// Instructions: Add=8, Sub=10, Mul=12, SDiv=15, SRem=18, AShr=22, Trunc=33,
// SExt=35, ICmp=46
return op == 8 || op == 10 || op == 12 || op == 15 || op == 18 || op == 22 ||
op == 33 || op == 35 || op == 46;
}
bool CountLlvmOp_uints(unsigned op) {
// Instructions: UDiv=14, URem=17, Shl=20, LShr=21, And=23, Or=24, Xor=25,
// ZExt=34
return op == 14 || op == 17 || (20 <= op && op <= 21) ||
(23 <= op && op <= 25) || op == 34;
}
// OPCODE-COUNTERS:END
void CountDxilOp(unsigned op, DxilCounters &counters) {
// clang-format off
// Python lines need to be not formatted.
// <py::lines('COUNT-DXIL-OPS')>['if (CountDxilOp_%s(op)) ++counters.%s;' % (c,c) for c in hctdb_instrhelp.get_dxil_op_counters()]</py>
// clang-format on
// COUNT-DXIL-OPS:BEGIN
if (CountDxilOp_atomic(op))
++counters.atomic;
if (CountDxilOp_barrier(op))
++counters.barrier;
if (CountDxilOp_floats(op))
++counters.floats;
if (CountDxilOp_gs_cut(op))
++counters.gs_cut;
if (CountDxilOp_gs_emit(op))
++counters.gs_emit;
if (CountDxilOp_ints(op))
++counters.ints;
if (CountDxilOp_sig_ld(op))
++counters.sig_ld;
if (CountDxilOp_sig_st(op))
++counters.sig_st;
if (CountDxilOp_tex_bias(op))
++counters.tex_bias;
if (CountDxilOp_tex_cmp(op))
++counters.tex_cmp;
if (CountDxilOp_tex_grad(op))
++counters.tex_grad;
if (CountDxilOp_tex_load(op))
++counters.tex_load;
if (CountDxilOp_tex_norm(op))
++counters.tex_norm;
if (CountDxilOp_tex_store(op))
++counters.tex_store;
if (CountDxilOp_uints(op))
++counters.uints;
// COUNT-DXIL-OPS:END
}
void CountLlvmOp(unsigned op, DxilCounters &counters) {
// clang-format off
// Python lines need to be not formatted.
// <py::lines('COUNT-LLVM-OPS')>['if (CountLlvmOp_%s(op)) ++counters.%s;' % (c,c) for c in hctdb_instrhelp.get_llvm_op_counters()]</py>
// clang-format on
// COUNT-LLVM-OPS:BEGIN
if (CountLlvmOp_atomic(op))
++counters.atomic;
if (CountLlvmOp_fence(op))
++counters.fence;
if (CountLlvmOp_floats(op))
++counters.floats;
if (CountLlvmOp_ints(op))
++counters.ints;
if (CountLlvmOp_uints(op))
++counters.uints;
// COUNT-LLVM-OPS:END
}
} // namespace
void CountInstructions(llvm::Module &M, DxilCounters &counters) {
const DataLayout &DL = M.getDataLayout();
PointerInfoMap ptrInfoMap;
for (auto &GV : M.globals()) {
PointerInfo PI = GetPointerInfo(&GV, ptrInfoMap);
if (PI.isArray) {
// Count number of bytes used in global arrays.
Type *pTy = GV.getType()->getPointerElementType();
uint32_t size = DL.getTypeAllocSize(pTy);
switch (PI.memType) {
case PointerInfo::MemType::Global_Static:
counters.array_static_bytes += size;
break;
case PointerInfo::MemType::Global_TGSM:
counters.array_tgsm_bytes += size;
break;
default:
break;
}
}
}
for (auto &F : M.functions()) {
if (F.isDeclaration())
continue;
for (auto itBlock = F.begin(), endBlock = F.end(); itBlock != endBlock;
++itBlock) {
for (auto itInst = itBlock->begin(), endInst = itBlock->end();
itInst != endInst; ++itInst) {
Instruction *I = itInst;
++counters.insts;
if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Type *pTy = AI->getType()->getPointerElementType();
// Count number of bytes used in alloca arrays.
if (pTy->isArrayTy()) {
counters.array_local_bytes += DL.getTypeAllocSize(pTy);
}
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (hlsl::OP::IsDxilOpFuncCallInst(CI)) {
unsigned opcode = static_cast<unsigned>(hlsl::OP::getOpCode(CI));
CountDxilOp(opcode, counters);
}
} else if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
LoadInst *LI = dyn_cast<LoadInst>(I);
StoreInst *SI = dyn_cast<StoreInst>(I);
Value *PtrOp = LI ? LI->getPointerOperand() : SI->getPointerOperand();
PointerInfo PI = GetPointerInfo(PtrOp, ptrInfoMap);
// Count load/store on array elements.
if (PI.isArray) {
switch (PI.memType) {
case PointerInfo::MemType::Alloca:
++counters.array_local_ldst;
break;
case PointerInfo::MemType::Global_Static:
++counters.array_static_ldst;
break;
case PointerInfo::MemType::Global_TGSM:
++counters.array_tgsm_ldst;
break;
default:
break;
}
}
} else if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
if (BI->getNumSuccessors() > 1) {
// TODO: More sophisticated analysis to separate dynamic from static
// branching?
++counters.branches;
}
} else {
// Count llvm ops:
CountLlvmOp(I->getOpcode(), counters);
}
}
}
}
}
struct CounterOffsetByName {
StringRef name;
uint32_t DxilCounters::*ptr;
};
// Must be sorted case-sensitive:
static const CounterOffsetByName CountersByName[] = {
// clang-format off
// Python lines need to be not formatted.
// <py::lines('COUNTER-MEMBER-PTRS')>['{ "%s", &DxilCounters::%s },' % (c,c) for c in hctdb_instrhelp.get_counters()]</py>
// clang-format on
// COUNTER-MEMBER-PTRS:BEGIN
{"array_local_bytes", &DxilCounters::array_local_bytes},
{"array_local_ldst", &DxilCounters::array_local_ldst},
{"array_static_bytes", &DxilCounters::array_static_bytes},
{"array_static_ldst", &DxilCounters::array_static_ldst},
{"array_tgsm_bytes", &DxilCounters::array_tgsm_bytes},
{"array_tgsm_ldst", &DxilCounters::array_tgsm_ldst},
{"atomic", &DxilCounters::atomic},
{"barrier", &DxilCounters::barrier},
{"branches", &DxilCounters::branches},
{"fence", &DxilCounters::fence},
{"floats", &DxilCounters::floats},
{"gs_cut", &DxilCounters::gs_cut},
{"gs_emit", &DxilCounters::gs_emit},
{"insts", &DxilCounters::insts},
{"ints", &DxilCounters::ints},
{"sig_ld", &DxilCounters::sig_ld},
{"sig_st", &DxilCounters::sig_st},
{"tex_bias", &DxilCounters::tex_bias},
{"tex_cmp", &DxilCounters::tex_cmp},
{"tex_grad", &DxilCounters::tex_grad},
{"tex_load", &DxilCounters::tex_load},
{"tex_norm", &DxilCounters::tex_norm},
{"tex_store", &DxilCounters::tex_store},
{"uints", &DxilCounters::uints},
// COUNTER-MEMBER-PTRS:END
};
static int CounterOffsetByNameLess(const CounterOffsetByName &a,
const CounterOffsetByName &b) {
return a.name < b.name;
}
uint32_t *LookupByName(llvm::StringRef name, DxilCounters &counters) {
CounterOffsetByName key = {name, nullptr};
static const CounterOffsetByName *CounterEnd =
CountersByName + _countof(CountersByName);
auto result = std::lower_bound(CountersByName, CounterEnd, key,
CounterOffsetByNameLess);
if (result != CounterEnd && result->name == key.name)
return &(counters.*(result->ptr));
return nullptr;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/CMakeLists.txt | # Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License.
# See LICENSE.TXT for details.
add_hlsl_hctgen(DxilOperations OUTPUT DxilOperations.cpp CODE_TAG)
add_hlsl_hctgen(DxilShaderModel OUTPUT DxilShaderModel.cpp CODE_TAG)
add_hlsl_hctgen(DxilMetadata OUTPUT DxilMetadataHelper.cpp CODE_TAG)
add_llvm_library(LLVMDXIL
DxilCBuffer.cpp
DxilCompType.cpp
DxilCounters.cpp
DxilInterpolationMode.cpp
DxilMetadataHelper.cpp
DxilModule.cpp
DxilModuleHelper.cpp
DxilNodeProps.cpp
DxilOperations.cpp
DxilResource.cpp
DxilResourceBase.cpp
DxilResourceBinding.cpp
DxilResourceProperties.cpp
DxilSampler.cpp
DxilSemantic.cpp
DxilShaderFlags.cpp
DxilShaderModel.cpp
DxilSignature.cpp
DxilSignatureElement.cpp
DxilSubobject.cpp
DxilTypeSystem.cpp
DxilUtil.cpp
DxilUtilDbgInfoAndMisc.cpp
DxilPDB.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
add_dependencies(LLVMDXIL intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilNodeProps.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilNodeProps.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilNodeProps.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// NodeFlags methods
//
NodeFlags::NodeFlags() : m_Flags(DXIL::NodeIOFlags::None) {}
NodeFlags::NodeFlags(DXIL::NodeIOFlags flags) : m_Flags(flags) {}
NodeFlags::NodeFlags(DXIL::NodeIOKind kind)
: m_Flags((DXIL::NodeIOFlags)kind) {}
NodeFlags::NodeFlags(uint32_t F) : NodeFlags((DXIL::NodeIOFlags)F) {}
bool NodeFlags::operator==(const hlsl::NodeFlags &o) const {
return m_Flags == o.m_Flags;
}
NodeFlags::operator uint32_t() const { return (uint32_t)m_Flags; }
DXIL::NodeIOKind NodeFlags::GetNodeIOKind() const {
return (DXIL::NodeIOKind)((uint32_t)m_Flags &
(uint32_t)DXIL::NodeIOFlags::NodeIOKindMask);
}
DXIL::NodeIOFlags NodeFlags::GetNodeIOFlags() const { return m_Flags; }
bool NodeFlags::IsInputRecord() const {
return ((uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::Input) != 0;
}
bool NodeFlags::IsOutput() const {
return ((uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::Output) != 0;
}
bool NodeFlags::IsRecord() const {
return ((uint32_t)m_Flags &
(uint32_t)DXIL::NodeIOFlags::RecordGranularityMask) != 0;
}
bool NodeFlags::IsOutputNode() const { return IsOutput() && !IsRecord(); }
bool NodeFlags::IsOutputRecord() const { return IsOutput() && IsRecord(); }
bool NodeFlags::IsReadWrite() const {
return ((uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::ReadWrite) != 0;
}
bool NodeFlags::IsEmpty() const {
return ((uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::EmptyRecord) != 0;
}
bool NodeFlags::IsEmptyInput() const { return IsEmpty() && IsInputRecord(); }
bool NodeFlags::IsValidNodeKind() const {
return GetNodeIOKind() != DXIL::NodeIOKind::Invalid;
}
bool NodeFlags::RecordTypeMatchesLaunchType(
DXIL::NodeLaunchType launchType) const {
DXIL::NodeIOFlags recordLaunchType = (DXIL::NodeIOFlags)(
(uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::RecordGranularityMask);
return (launchType == DXIL::NodeLaunchType::Broadcasting &&
recordLaunchType == DXIL::NodeIOFlags::DispatchRecord) ||
(launchType == DXIL::NodeLaunchType::Coalescing &&
recordLaunchType == DXIL::NodeIOFlags::GroupRecord) ||
(launchType == DXIL::NodeLaunchType::Thread &&
recordLaunchType == DXIL::NodeIOFlags::ThreadRecord);
}
void NodeFlags::SetTrackRWInputSharing() {
m_Flags = (DXIL::NodeIOFlags)(
(uint32_t)m_Flags | (uint32_t)DXIL::NodeIOFlags::TrackRWInputSharing);
}
bool NodeFlags::GetTrackRWInputSharing() const {
return ((uint32_t)m_Flags &
(uint32_t)DXIL::NodeIOFlags::TrackRWInputSharing) != 0;
}
void NodeFlags::SetGloballyCoherent() {
m_Flags = (DXIL::NodeIOFlags)((uint32_t)m_Flags |
(uint32_t)DXIL::NodeIOFlags::GloballyCoherent);
}
bool NodeFlags::GetGloballyCoherent() const {
return ((uint32_t)m_Flags & (uint32_t)DXIL::NodeIOFlags::GloballyCoherent) !=
0;
}
//------------------------------------------------------------------------------
//
// NodeIOProperties methods.
//
NodeInfo NodeIOProperties::GetNodeInfo() const {
return NodeInfo(Flags.GetNodeIOFlags(), RecordType.size);
}
NodeRecordInfo NodeIOProperties::GetNodeRecordInfo() const {
return NodeInfo(Flags.GetNodeIOFlags(), RecordType.size);
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilModule.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilModule.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilCounters.h"
#include "dxc/DXIL/DxilEntryProps.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilSignatureElement.h"
#include "dxc/DXIL/DxilSubobject.h"
#include "dxc/Support/Global.h"
#include "dxc/WinAdapter.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/raw_ostream.h"
#include <unordered_set>
using std::make_unique;
using namespace llvm;
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
class DxilErrorDiagnosticInfo : public DiagnosticInfo {
private:
const char *m_message;
public:
DxilErrorDiagnosticInfo(const char *str)
: DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
m_message(str) {}
void print(DiagnosticPrinter &DP) const override { DP << m_message; }
};
} // namespace
namespace hlsl {
namespace DXIL {
// Define constant variables exposed in DxilConstants.h
// TODO: revisit data layout descriptions for the following:
// - x64 pointers?
// - Keep elf manging(m:e)?
// For legacy data layout, everything less than 32 align to 32.
const char *kLegacyLayoutString = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:"
"64-f16:32-f32:32-f64:64-n8:16:32:64";
// New data layout with native low precision types
const char *kNewLayoutString = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-"
"f16:16-f32:32-f64:64-n8:16:32:64";
// Function Attributes
// TODO: consider generating attributes from hctdb
const char *kFP32DenormKindString = "fp32-denorm-mode";
const char *kFP32DenormValueAnyString = "any";
const char *kFP32DenormValuePreserveString = "preserve";
const char *kFP32DenormValueFtzString = "ftz";
const char *kDxBreakFuncName = "dx.break";
const char *kDxBreakCondName = "dx.break.cond";
const char *kDxBreakMDName = "dx.break.br";
const char *kDxIsHelperGlobalName = "dx.ishelper";
const char *kHostLayoutTypePrefix = "hostlayout.";
const char *kWaveOpsIncludeHelperLanesString = "waveops-include-helper-lanes";
} // namespace DXIL
void SetDxilHook(Module &M);
void ClearDxilHook(Module &M);
//------------------------------------------------------------------------------
//
// DxilModule methods.
//
DxilModule::DxilModule(Module *pModule)
: m_Ctx(pModule->getContext()), m_pModule(pModule),
m_pMDHelper(make_unique<DxilMDHelper>(
pModule, make_unique<DxilExtraPropertyHelper>(pModule))),
m_pOP(make_unique<OP>(pModule->getContext(), pModule)),
m_pTypeSystem(make_unique<DxilTypeSystem>(pModule)) {
DXASSERT_NOMSG(m_pModule != nullptr);
SetDxilHook(*m_pModule);
}
DxilModule::~DxilModule() { ClearDxilHook(*m_pModule); }
LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
Module *DxilModule::GetModule() const { return m_pModule; }
OP *DxilModule::GetOP() const { return m_pOP.get(); }
void DxilModule::SetShaderModel(const ShaderModel *pSM, bool bUseMinPrecision) {
DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM),
"shader model must not change for the module");
DXASSERT(pSM != nullptr && pSM->IsValidForDxil(),
"shader model must be valid");
m_pSM = pSM;
m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
m_pMDHelper->SetShaderModel(m_pSM);
m_bUseMinPrecision = bUseMinPrecision;
m_pOP->InitWithMinPrecision(m_bUseMinPrecision);
m_pTypeSystem->SetMinPrecision(m_bUseMinPrecision);
if (!m_pSM->IsLib()) {
// Always have valid entry props for non-lib case from this point on.
DxilFunctionProps props;
props.shaderKind = m_pSM->GetKind();
m_DxilEntryPropsMap[nullptr] =
make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
}
m_SerializedRootSignature.clear();
}
const ShaderModel *DxilModule::GetShaderModel() const { return m_pSM; }
void DxilModule::GetDxilVersion(unsigned &DxilMajor,
unsigned &DxilMinor) const {
DxilMajor = m_DxilMajor;
DxilMinor = m_DxilMinor;
}
void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
m_ValMajor = ValMajor;
m_ValMinor = ValMinor;
}
void DxilModule::SetForceZeroStoreLifetimes(bool ForceZeroStoreLifetimes) {
m_ForceZeroStoreLifetimes = ForceZeroStoreLifetimes;
}
bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
// Don't upgrade if validation was disabled.
if (m_ValMajor == 0 && m_ValMinor == 0) {
return false;
}
if (ValMajor > m_ValMajor ||
(ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
// Module requires higher validator version than previously set
SetValidatorVersion(ValMajor, ValMinor);
return true;
}
return false;
}
void DxilModule::GetValidatorVersion(unsigned &ValMajor,
unsigned &ValMinor) const {
ValMajor = m_ValMajor;
ValMinor = m_ValMinor;
}
bool DxilModule::GetForceZeroStoreLifetimes() const {
return m_ForceZeroStoreLifetimes;
}
bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor,
unsigned &ValMinor) const {
if (!m_pSM)
return false;
m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) < 0 &&
m_ShaderFlags.GetRaytracingTier1_1())
ValMinor = 5;
else if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 4) < 0 &&
GetSubobjects() && !GetSubobjects()->GetSubobjects().empty())
ValMinor = 4;
else if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 1) < 0 &&
(m_ShaderFlags.GetFeatureInfo() &
hlsl::DXIL::ShaderFeatureInfo_ViewID))
ValMinor = 1;
return true;
}
bool DxilModule::UpgradeToMinValidatorVersion() {
unsigned ValMajor = 1, ValMinor = 0;
if (GetMinValidatorVersion(ValMajor, ValMinor)) {
return UpgradeValidatorVersion(ValMajor, ValMinor);
}
return false;
}
Function *DxilModule::GetEntryFunction() { return m_pEntryFunc; }
const Function *DxilModule::GetEntryFunction() const { return m_pEntryFunc; }
llvm::SmallVector<llvm::Function *, 64> DxilModule::GetExportedFunctions() {
llvm::SmallVector<llvm::Function *, 64> ret;
for (auto const &fn : m_DxilEntryPropsMap) {
if (fn.first != nullptr) {
ret.push_back(const_cast<llvm::Function *>(fn.first));
}
}
if (ret.empty()) {
auto *entryFunction = m_pEntryFunc;
if (entryFunction == nullptr) {
entryFunction = GetPatchConstantFunction();
}
ret.push_back(entryFunction);
}
return ret;
}
void DxilModule::SetEntryFunction(Function *pEntryFunc) {
if (m_pSM->IsLib()) {
DXASSERT(pEntryFunc == nullptr,
"Otherwise, trying to set an entry function on library");
m_pEntryFunc = nullptr;
return;
}
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
m_pEntryFunc = pEntryFunc;
// Move entry props to new function in order to preserve them.
std::unique_ptr<DxilEntryProps> Props =
std::move(m_DxilEntryPropsMap.begin()->second);
m_DxilEntryPropsMap.clear();
m_DxilEntryPropsMap[m_pEntryFunc] = std::move(Props);
}
const string &DxilModule::GetEntryFunctionName() const { return m_EntryName; }
void DxilModule::SetEntryFunctionName(const string &name) {
m_EntryName = name;
}
llvm::Function *DxilModule::GetPatchConstantFunction() {
if (!m_pSM->IsHS())
return nullptr;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.patchConstantFunc;
}
const llvm::Function *DxilModule::GetPatchConstantFunction() const {
if (!m_pSM->IsHS())
return nullptr;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.patchConstantFunc;
}
void DxilModule::SetPatchConstantFunction(llvm::Function *patchConstantFunc) {
if (!m_pSM->IsHS())
return;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
auto &HS = props.ShaderProps.HS;
if (HS.patchConstantFunc != patchConstantFunc) {
if (HS.patchConstantFunc)
m_PatchConstantFunctions.erase(HS.patchConstantFunc);
HS.patchConstantFunc = patchConstantFunc;
if (patchConstantFunc)
m_PatchConstantFunctions.insert(patchConstantFunc);
}
}
bool DxilModule::IsEntryOrPatchConstantFunction(
const llvm::Function *pFunc) const {
return pFunc == GetEntryFunction() || pFunc == GetPatchConstantFunction();
}
unsigned DxilModule::GetGlobalFlags() const {
unsigned Flags = m_ShaderFlags.GetGlobalFlags();
return Flags;
}
void DxilModule::CollectShaderFlagsForModule(ShaderFlags &Flags) {
ComputeShaderCompatInfo();
for (auto &itInfo : m_FuncToShaderCompat)
Flags.CombineShaderFlags(itInfo.second.shaderFlags);
const ShaderModel *SM = GetShaderModel();
// Set DerivativesInMeshAndAmpShaders if necessary for MS/AS.
if (Flags.GetUsesDerivatives()) {
if (SM->IsMS() || SM->IsAS())
Flags.SetDerivativesInMeshAndAmpShaders(true);
}
// Clear function-local flags not intended for the module.
Flags.ClearLocalFlags();
unsigned NumUAVs = 0;
const unsigned kSmallUAVCount = 8;
bool hasRawAndStructuredBuffer = false;
for (auto &UAV : m_UAVs) {
unsigned uavSize = UAV->GetRangeSize();
NumUAVs += uavSize > 8U ? 9U : uavSize; // avoid overflow
if (UAV->IsROV())
Flags.SetROVs(true);
switch (UAV->GetKind()) {
case DXIL::ResourceKind::RawBuffer:
case DXIL::ResourceKind::StructuredBuffer:
hasRawAndStructuredBuffer = true;
break;
default:
// Not raw/structured.
break;
}
}
// Maintain earlier erroneous counting of UAVs for compatibility
if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 6) < 0)
Flags.Set64UAVs(m_UAVs.size() > kSmallUAVCount);
else
Flags.Set64UAVs(NumUAVs > kSmallUAVCount);
if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 8) < 0) {
// For 1.7 compatibility, set UAVsAtEveryStage if there are UAVs
// and the shader model is not CS or PS.
if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
Flags.SetUAVsAtEveryStage(true);
} else {
// Starting with 1.8, UAVsAtEveryStage is only set when the shader model is
// a graphics stage where it mattered. It was unnecessary to set it for
// library profiles, or MS/AS profiles.
if (NumUAVs && (SM->IsVS() || SM->IsHS() || SM->IsDS() || SM->IsGS()))
Flags.SetUAVsAtEveryStage(true);
}
for (auto &SRV : m_SRVs) {
switch (SRV->GetKind()) {
case DXIL::ResourceKind::RawBuffer:
case DXIL::ResourceKind::StructuredBuffer:
hasRawAndStructuredBuffer = true;
break;
default:
// Not raw/structured.
break;
}
}
Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
bool hasCSRawAndStructuredViaShader4X =
hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
}
void DxilModule::CollectShaderFlagsForModule() {
CollectShaderFlagsForModule(m_ShaderFlags);
// This is also where we record the size of the mesh payload for amplification
// shader output
for (Function &F : GetModule()->functions()) {
if (HasDxilEntryProps(&F)) {
DxilFunctionProps &props = GetDxilFunctionProps(&F);
if (props.shaderKind == DXIL::ShaderKind::Amplification) {
if (props.ShaderProps.AS.payloadSizeInBytes != 0)
continue;
for (const BasicBlock &BB : F.getBasicBlockList()) {
for (const Instruction &I : BB.getInstList()) {
const DxilInst_DispatchMesh dispatch(const_cast<Instruction *>(&I));
if (dispatch) {
Type *payloadTy =
dispatch.get_payload()->getType()->getPointerElementType();
const DataLayout &DL = m_pModule->getDataLayout();
props.ShaderProps.AS.payloadSizeInBytes =
DL.getTypeAllocSize(payloadTy);
}
}
}
}
}
}
}
void DxilModule::SetNumThreads(unsigned x, unsigned y, unsigned z) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 &&
(m_pSM->IsCS() || m_pSM->IsMS() || m_pSM->IsAS()),
"only works for CS/MS/AS profiles");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT_NOMSG(m_pSM->GetKind() == props.shaderKind);
props.numThreads[0] = x;
props.numThreads[1] = y;
props.numThreads[2] = z;
}
unsigned DxilModule::GetNumThreads(unsigned idx) const {
DXASSERT(m_DxilEntryPropsMap.size() == 1 &&
(m_pSM->IsCS() || m_pSM->IsMS() || m_pSM->IsAS()),
"only works for CS/MS/AS profiles");
DXASSERT(idx < 3, "Thread dimension index must be 0-2");
assert(idx < 3);
if (!(m_pSM->IsCS() || m_pSM->IsMS() || m_pSM->IsAS()))
return 0;
const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT_NOMSG(m_pSM->GetKind() == props.shaderKind);
return props.numThreads[idx];
}
DxilWaveSize &DxilModule::GetWaveSize() {
return const_cast<DxilWaveSize &>(
static_cast<const DxilModule *>(this)->GetWaveSize());
}
const DxilWaveSize &DxilModule::GetWaveSize() const {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsCS(),
"only works for CS profile");
const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT_NOMSG(m_pSM->GetKind() == props.shaderKind);
return props.WaveSize;
}
DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
if (!m_pSM->IsGS())
return DXIL::InputPrimitive::Undefined;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
return props.ShaderProps.GS.inputPrimitive;
}
void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
"only works for GS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
auto &GS = props.ShaderProps.GS;
DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP &&
IP < DXIL::InputPrimitive::LastEntry);
GS.inputPrimitive = IP;
}
unsigned DxilModule::GetMaxVertexCount() const {
if (!m_pSM->IsGS())
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
auto &GS = props.ShaderProps.GS;
DXASSERT_NOMSG(GS.maxVertexCount != 0);
return GS.maxVertexCount;
}
void DxilModule::SetMaxVertexCount(unsigned Count) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
"only works for GS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
auto &GS = props.ShaderProps.GS;
GS.maxVertexCount = Count;
}
DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
return m_StreamPrimitiveTopology;
}
void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
m_StreamPrimitiveTopology = Topology;
SetActiveStreamMask(m_ActiveStreamMask); // Update props
}
bool DxilModule::HasMultipleOutputStreams() const {
if (!m_pSM->IsGS()) {
return false;
} else {
unsigned NumStreams =
(m_ActiveStreamMask & 0x1) + ((m_ActiveStreamMask & 0x2) >> 1) +
((m_ActiveStreamMask & 0x4) >> 2) + ((m_ActiveStreamMask & 0x8) >> 3);
DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
return NumStreams > 1;
}
}
unsigned DxilModule::GetOutputStream() const {
if (!m_pSM->IsGS()) {
return 0;
} else {
DXASSERT_NOMSG(!HasMultipleOutputStreams());
switch (m_ActiveStreamMask) {
case 0x1:
return 0;
case 0x2:
return 1;
case 0x4:
return 2;
case 0x8:
return 3;
default:
DXASSERT_NOMSG(false);
}
return (unsigned)(-1);
}
}
unsigned DxilModule::GetGSInstanceCount() const {
if (!m_pSM->IsGS())
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
return props.ShaderProps.GS.instanceCount;
}
void DxilModule::SetGSInstanceCount(unsigned Count) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
"only works for GS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
props.ShaderProps.GS.instanceCount = Count;
}
bool DxilModule::IsStreamActive(unsigned Stream) const {
return (m_ActiveStreamMask & (1 << Stream)) != 0;
}
void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
if (bActive) {
m_ActiveStreamMask |= (1 << Stream);
} else {
m_ActiveStreamMask &= ~(1 << Stream);
}
SetActiveStreamMask(m_ActiveStreamMask);
}
void DxilModule::SetActiveStreamMask(unsigned Mask) {
m_ActiveStreamMask = Mask;
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
"only works for GS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsGS(), "Must be GS profile");
for (unsigned i = 0; i < 4; i++) {
if (IsStreamActive(i))
props.ShaderProps.GS.streamPrimitiveTopologies[i] =
m_StreamPrimitiveTopology;
else
props.ShaderProps.GS.streamPrimitiveTopologies[i] =
DXIL::PrimitiveTopology::Undefined;
}
}
unsigned DxilModule::GetActiveStreamMask() const { return m_ActiveStreamMask; }
bool DxilModule::GetUseMinPrecision() const { return m_bUseMinPrecision; }
void DxilModule::SetDisableOptimization(bool DisableOptimization) {
m_bDisableOptimizations = DisableOptimization;
}
bool DxilModule::GetDisableOptimization() const {
return m_bDisableOptimizations;
}
void DxilModule::SetAllResourcesBound(bool ResourcesBound) {
m_bAllResourcesBound = ResourcesBound;
}
bool DxilModule::GetAllResourcesBound() const { return m_bAllResourcesBound; }
void DxilModule::SetResMayAlias(bool resMayAlias) {
m_bResMayAlias = resMayAlias;
}
bool DxilModule::GetResMayAlias() const { return m_bResMayAlias; }
void DxilModule::SetLegacyResourceReservation(bool legacyResourceReservation) {
m_IntermediateFlags &= ~LegacyResourceReservation;
if (legacyResourceReservation)
m_IntermediateFlags |= LegacyResourceReservation;
}
bool DxilModule::GetLegacyResourceReservation() const {
return (m_IntermediateFlags & LegacyResourceReservation) != 0;
}
void DxilModule::ClearIntermediateOptions() { m_IntermediateFlags = 0; }
unsigned DxilModule::GetInputControlPointCount() const {
if (!(m_pSM->IsHS() || m_pSM->IsDS()))
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
if (props.IsHS())
return props.ShaderProps.HS.inputControlPoints;
else
return props.ShaderProps.DS.inputControlPoints;
}
void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && (m_pSM->IsHS() || m_pSM->IsDS()),
"only works for non-lib profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
if (props.IsHS())
props.ShaderProps.HS.inputControlPoints = NumICPs;
else
props.ShaderProps.DS.inputControlPoints = NumICPs;
}
DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
if (!(m_pSM->IsHS() || m_pSM->IsDS()))
return DXIL::TessellatorDomain::Undefined;
DXASSERT_NOMSG(m_DxilEntryPropsMap.size() == 1);
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
if (props.IsHS())
return props.ShaderProps.HS.domain;
else
return props.ShaderProps.DS.domain;
}
void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && (m_pSM->IsHS() || m_pSM->IsDS()),
"only works for HS or DS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
if (props.IsHS())
props.ShaderProps.HS.domain = TessDomain;
else
props.ShaderProps.DS.domain = TessDomain;
}
unsigned DxilModule::GetOutputControlPointCount() const {
if (!m_pSM->IsHS())
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.outputControlPoints;
}
void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
"only works for HS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
props.ShaderProps.HS.outputControlPoints = NumOCPs;
}
DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
if (!m_pSM->IsHS())
return DXIL::TessellatorPartitioning::Undefined;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.partition;
}
void DxilModule::SetTessellatorPartitioning(
DXIL::TessellatorPartitioning TessPartitioning) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
"only works for HS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
props.ShaderProps.HS.partition = TessPartitioning;
}
DXIL::TessellatorOutputPrimitive
DxilModule::GetTessellatorOutputPrimitive() const {
if (!m_pSM->IsHS())
return DXIL::TessellatorOutputPrimitive::Undefined;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.outputPrimitive;
}
void DxilModule::SetTessellatorOutputPrimitive(
DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
"only works for HS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
props.ShaderProps.HS.outputPrimitive = TessOutputPrimitive;
}
float DxilModule::GetMaxTessellationFactor() const {
if (!m_pSM->IsHS())
return 0.0F;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
return props.ShaderProps.HS.maxTessFactor;
}
void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
"only works for HS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsHS(), "Must be HS profile");
props.ShaderProps.HS.maxTessFactor = MaxTessellationFactor;
}
unsigned DxilModule::GetMaxOutputVertices() const {
if (!m_pSM->IsMS())
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
return props.ShaderProps.MS.maxVertexCount;
}
void DxilModule::SetMaxOutputVertices(unsigned NumOVs) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
"only works for MS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
props.ShaderProps.MS.maxVertexCount = NumOVs;
}
unsigned DxilModule::GetMaxOutputPrimitives() const {
if (!m_pSM->IsMS())
return 0;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
return props.ShaderProps.MS.maxPrimitiveCount;
}
void DxilModule::SetMaxOutputPrimitives(unsigned NumOPs) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
"only works for MS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
props.ShaderProps.MS.maxPrimitiveCount = NumOPs;
}
DXIL::MeshOutputTopology DxilModule::GetMeshOutputTopology() const {
if (!m_pSM->IsMS())
return DXIL::MeshOutputTopology::Undefined;
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
return props.ShaderProps.MS.outputTopology;
}
void DxilModule::SetMeshOutputTopology(
DXIL::MeshOutputTopology MeshOutputTopology) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsMS(),
"only works for MS profile");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
props.ShaderProps.MS.outputTopology = MeshOutputTopology;
}
unsigned DxilModule::GetPayloadSizeInBytes() const {
if (m_pSM->IsMS()) {
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
return props.ShaderProps.MS.payloadSizeInBytes;
} else if (m_pSM->IsAS()) {
DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsAS(), "Must be AS profile");
return props.ShaderProps.AS.payloadSizeInBytes;
} else {
return 0;
}
}
void DxilModule::SetPayloadSizeInBytes(unsigned Size) {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && (m_pSM->IsMS() || m_pSM->IsAS()),
"only works for MS or AS profile");
if (m_pSM->IsMS()) {
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsMS(), "Must be MS profile");
props.ShaderProps.MS.payloadSizeInBytes = Size;
} else if (m_pSM->IsAS()) {
DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
DXASSERT(props.IsAS(), "Must be AS profile");
props.ShaderProps.AS.payloadSizeInBytes = Size;
}
}
void DxilModule::SetAutoBindingSpace(uint32_t Space) {
m_AutoBindingSpace = Space;
}
uint32_t DxilModule::GetAutoBindingSpace() const { return m_AutoBindingSpace; }
void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
if (!props)
return;
DxilFunctionProps &ourProps = GetDxilFunctionProps(GetEntryFunction());
if (props != &ourProps) {
ourProps.shaderKind = props->shaderKind;
ourProps.ShaderProps = props->ShaderProps;
}
switch (props->shaderKind) {
case DXIL::ShaderKind::Pixel: {
auto &PS = props->ShaderProps.PS;
m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
} break;
case DXIL::ShaderKind::Compute:
case DXIL::ShaderKind::Domain:
case DXIL::ShaderKind::Hull:
case DXIL::ShaderKind::Vertex:
case DXIL::ShaderKind::Mesh:
case DXIL::ShaderKind::Amplification:
break;
default: {
DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
"else invalid shader kind");
auto &GS = props->ShaderProps.GS;
m_ActiveStreamMask = 0;
for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
if (GS.streamPrimitiveTopologies[i] !=
DXIL::PrimitiveTopology::Undefined) {
m_ActiveStreamMask |= (1 << i);
DXASSERT_NOMSG(
m_StreamPrimitiveTopology == DXIL::PrimitiveTopology::Undefined ||
m_StreamPrimitiveTopology == GS.streamPrimitiveTopologies[i]);
m_StreamPrimitiveTopology = GS.streamPrimitiveTopologies[i];
}
}
// Refresh props:
SetActiveStreamMask(m_ActiveStreamMask);
} break;
}
}
template <typename T>
unsigned DxilModule::AddResource(vector<unique_ptr<T>> &Vec,
unique_ptr<T> pRes) {
DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
unsigned Id = (unsigned)Vec.size();
Vec.emplace_back(std::move(pRes));
return Id;
}
unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
}
DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) { return *m_CBuffers[idx]; }
const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
return *m_CBuffers[idx];
}
const vector<unique_ptr<DxilCBuffer>> &DxilModule::GetCBuffers() const {
return m_CBuffers;
}
unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
}
DxilSampler &DxilModule::GetSampler(unsigned idx) { return *m_Samplers[idx]; }
const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
return *m_Samplers[idx];
}
const vector<unique_ptr<DxilSampler>> &DxilModule::GetSamplers() const {
return m_Samplers;
}
unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
}
DxilResource &DxilModule::GetSRV(unsigned idx) { return *m_SRVs[idx]; }
const DxilResource &DxilModule::GetSRV(unsigned idx) const {
return *m_SRVs[idx];
}
const vector<unique_ptr<DxilResource>> &DxilModule::GetSRVs() const {
return m_SRVs;
}
unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
}
DxilResource &DxilModule::GetUAV(unsigned idx) { return *m_UAVs[idx]; }
const DxilResource &DxilModule::GetUAV(unsigned idx) const {
return *m_UAVs[idx];
}
const vector<unique_ptr<DxilResource>> &DxilModule::GetUAVs() const {
return m_UAVs;
}
template <typename TResource>
static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
std::unordered_set<unsigned> &immResID) {
for (auto p = vec.begin(); p != vec.end();) {
auto c = p++;
if (immResID.count((*c)->GetID()) == 0) {
p = vec.erase(c);
}
}
}
static void CollectUsedResource(Value *resID,
std::unordered_set<Value *> &usedResID) {
if (usedResID.count(resID) > 0)
return;
usedResID.insert(resID);
if (dyn_cast<ConstantInt>(resID)) {
// Do nothing
} else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
if (ZEI->getSrcTy()->isIntegerTy()) {
IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
if (ITy->getBitWidth() == 1) {
usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
}
}
} else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
CollectUsedResource(SI->getTrueValue(), usedResID);
CollectUsedResource(SI->getFalseValue(), usedResID);
} else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
for (Use &U : Phi->incoming_values()) {
CollectUsedResource(U.get(), usedResID);
}
}
// TODO: resID could be other types of instructions depending on the compiler
// optimization.
}
static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
std::unordered_set<Value *> &usedResID) {
for (Value *V : usedResID) {
if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
immResID.insert(cResID->getLimitedValue());
}
}
}
void DxilModule::RemoveFunction(llvm::Function *F) {
DXASSERT_NOMSG(F != nullptr);
m_DxilEntryPropsMap.erase(F);
if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
m_pTypeSystem.get()->EraseFunctionAnnotation(F);
m_pOP->RemoveFunction(F);
}
void DxilModule::RemoveUnusedResources() {
DXASSERT(!m_pSM->IsLib(), "this function does not work on libraries");
hlsl::OP *hlslOP = GetOP();
Function *createHandleFunc =
hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
if (createHandleFunc->user_empty()) {
m_CBuffers.clear();
m_UAVs.clear();
m_SRVs.clear();
m_Samplers.clear();
createHandleFunc->eraseFromParent();
return;
}
std::unordered_set<Value *> usedUAVID;
std::unordered_set<Value *> usedSRVID;
std::unordered_set<Value *> usedSamplerID;
std::unordered_set<Value *> usedCBufID;
// Collect used ID.
for (User *U : createHandleFunc->users()) {
CallInst *CI = cast<CallInst>(U);
Value *vResClass =
CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
ConstantInt *cResClass = cast<ConstantInt>(vResClass);
DXIL::ResourceClass resClass =
static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
// Skip unused resource handle.
if (CI->user_empty())
continue;
Value *resID =
CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
switch (resClass) {
case DXIL::ResourceClass::CBuffer:
CollectUsedResource(resID, usedCBufID);
break;
case DXIL::ResourceClass::Sampler:
CollectUsedResource(resID, usedSamplerID);
break;
case DXIL::ResourceClass::SRV:
CollectUsedResource(resID, usedSRVID);
break;
case DXIL::ResourceClass::UAV:
CollectUsedResource(resID, usedUAVID);
break;
default:
DXASSERT(0, "invalid res class");
break;
}
}
std::unordered_set<unsigned> immUAVID;
std::unordered_set<unsigned> immSRVID;
std::unordered_set<unsigned> immSamplerID;
std::unordered_set<unsigned> immCBufID;
ConvertUsedResource(immUAVID, usedUAVID);
ConvertUsedResource(immSRVID, usedSRVID);
ConvertUsedResource(immSamplerID, usedSamplerID);
ConvertUsedResource(immCBufID, usedCBufID);
RemoveResources(m_UAVs, immUAVID);
RemoveResources(m_SRVs, immSRVID);
RemoveResources(m_Samplers, immSamplerID);
RemoveResources(m_CBuffers, immCBufID);
}
namespace {
template <typename TResource>
static void RemoveResourcesWithUnusedSymbolsHelper(
std::vector<std::unique_ptr<TResource>> &vec) {
unsigned resID = 0;
std::unordered_set<GlobalVariable *>
eraseList; // Need in case of duplicate defs of lib resources
for (auto p = vec.begin(); p != vec.end();) {
auto c = p++;
Constant *symbol = (*c)->GetGlobalSymbol();
symbol->removeDeadConstantUsers();
if (symbol->user_empty()) {
p = vec.erase(c);
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(symbol))
eraseList.insert(GV);
continue;
}
if ((*c)->GetID() != resID) {
(*c)->SetID(resID);
}
resID++;
}
for (auto gv : eraseList) {
gv->eraseFromParent();
}
}
} // namespace
void DxilModule::RemoveResourcesWithUnusedSymbols() {
RemoveResourcesWithUnusedSymbolsHelper(m_SRVs);
RemoveResourcesWithUnusedSymbolsHelper(m_UAVs);
RemoveResourcesWithUnusedSymbolsHelper(m_CBuffers);
RemoveResourcesWithUnusedSymbolsHelper(m_Samplers);
}
namespace {
template <typename TResource>
static bool RenameResources(std::vector<std::unique_ptr<TResource>> &vec,
const std::string &prefix) {
bool bChanged = false;
for (auto &res : vec) {
res->SetGlobalName(prefix + res->GetGlobalName());
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(res->GetGlobalSymbol())) {
GV->setName(prefix + GV->getName());
}
bChanged = true;
}
return bChanged;
}
} // namespace
bool DxilModule::RenameResourcesWithPrefix(const std::string &prefix) {
bool bChanged = false;
bChanged |= RenameResources(m_SRVs, prefix);
bChanged |= RenameResources(m_UAVs, prefix);
bChanged |= RenameResources(m_CBuffers, prefix);
bChanged |= RenameResources(m_Samplers, prefix);
return bChanged;
}
namespace {
template <typename TResource>
static bool
RenameGlobalsWithBinding(std::vector<std::unique_ptr<TResource>> &vec,
llvm::StringRef prefix, bool bKeepName) {
bool bChanged = false;
for (auto &res : vec) {
if (res->IsAllocated()) {
std::string newName;
if (bKeepName)
newName = (Twine(res->GetGlobalName()) + "." + Twine(prefix) +
Twine(res->GetLowerBound()) + "." + Twine(res->GetSpaceID()))
.str();
else
newName = (Twine(prefix) + Twine(res->GetLowerBound()) + "." +
Twine(res->GetSpaceID()))
.str();
res->SetGlobalName(newName);
if (GlobalVariable *GV =
dyn_cast<GlobalVariable>(res->GetGlobalSymbol())) {
GV->setName(newName);
}
bChanged = true;
}
}
return bChanged;
}
} // namespace
bool DxilModule::RenameResourceGlobalsWithBinding(bool bKeepName) {
bool bChanged = false;
bChanged |= RenameGlobalsWithBinding(m_SRVs, "t", bKeepName);
bChanged |= RenameGlobalsWithBinding(m_UAVs, "u", bKeepName);
bChanged |= RenameGlobalsWithBinding(m_CBuffers, "b", bKeepName);
bChanged |= RenameGlobalsWithBinding(m_Samplers, "s", bKeepName);
return bChanged;
}
DxilSignature &DxilModule::GetInputSignature() {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
}
const DxilSignature &DxilModule::GetInputSignature() const {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
}
DxilSignature &DxilModule::GetOutputSignature() {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
}
const DxilSignature &DxilModule::GetOutputSignature() const {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
}
DxilSignature &DxilModule::GetPatchConstOrPrimSignature() {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.PatchConstOrPrimSignature;
}
const DxilSignature &DxilModule::GetPatchConstOrPrimSignature() const {
DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
"only works for non-lib profile");
return m_DxilEntryPropsMap.begin()->second->sig.PatchConstOrPrimSignature;
}
const std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() const {
return m_SerializedRootSignature;
}
std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() {
return m_SerializedRootSignature;
}
// Entry props.
bool DxilModule::HasDxilEntrySignature(const llvm::Function *F) const {
return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
}
DxilEntrySignature &DxilModule::GetDxilEntrySignature(const llvm::Function *F) {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
return m_DxilEntryPropsMap[F].get()->sig;
}
void DxilModule::ReplaceDxilEntryProps(llvm::Function *F,
llvm::Function *NewF) {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap[F]);
m_DxilEntryPropsMap.erase(F);
m_DxilEntryPropsMap[NewF] = std::move(Props);
}
void DxilModule::CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF) {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
std::unique_ptr<DxilEntryProps> Props =
make_unique<DxilEntryProps>(*m_DxilEntryPropsMap[F]);
m_DxilEntryPropsMap[NewF] = std::move(Props);
}
bool DxilModule::HasDxilEntryProps(const llvm::Function *F) const {
return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
}
DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
return *m_DxilEntryPropsMap.find(F)->second.get();
}
const DxilEntryProps &
DxilModule::GetDxilEntryProps(const llvm::Function *F) const {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
return *m_DxilEntryPropsMap.find(F)->second.get();
}
bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
}
DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
return const_cast<DxilFunctionProps &>(
static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
}
const DxilFunctionProps &
DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
return m_DxilEntryPropsMap.find(F)->second.get()->props;
}
void DxilModule::SetPatchConstantFunctionForHS(
llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
auto propIter = m_DxilEntryPropsMap.find(hullShaderFunc);
DXASSERT(propIter != m_DxilEntryPropsMap.end(),
"Hull shader must already have function props!");
DxilFunctionProps &props = propIter->second->props;
DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
auto &HS = props.ShaderProps.HS;
if (HS.patchConstantFunc != patchConstantFunc) {
if (HS.patchConstantFunc)
m_PatchConstantFunctions.erase(HS.patchConstantFunc);
HS.patchConstantFunc = patchConstantFunc;
if (patchConstantFunc)
m_PatchConstantFunctions.insert(patchConstantFunc);
}
}
bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
}
bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
return m_PatchConstantFunctions.count(F) != 0;
}
bool DxilModule::IsComputeShader(const llvm::Function *F) const {
return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
}
bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
auto propIter = m_DxilEntryPropsMap.find(F);
if (propIter != m_DxilEntryPropsMap.end()) {
DxilFunctionProps &props = propIter->second->props;
return props.IsGraphics() || props.IsCS() || props.IsNode();
}
// Otherwise, return true if patch constant function
return IsPatchConstantShader(F);
}
bool DxilModule::IsEntry(const llvm::Function *F) const {
auto propIter = m_DxilEntryPropsMap.find(F);
if (propIter != m_DxilEntryPropsMap.end()) {
DXASSERT(propIter->second->props.shaderKind != DXIL::ShaderKind::Invalid,
"invalid entry props");
return true;
}
// Otherwise, return true if patch constant function
return IsPatchConstantShader(F);
}
bool DxilModule::StripRootSignatureFromMetadata() {
NamedMDNode *pRootSignatureNamedMD =
GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
if (pRootSignatureNamedMD) {
GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
return true;
}
return false;
}
DxilSubobjects *DxilModule::GetSubobjects() { return m_pSubobjects.get(); }
const DxilSubobjects *DxilModule::GetSubobjects() const {
return m_pSubobjects.get();
}
DxilSubobjects *DxilModule::ReleaseSubobjects() {
return m_pSubobjects.release();
}
void DxilModule::ResetSubobjects(DxilSubobjects *subobjects) {
m_pSubobjects.reset(subobjects);
}
bool DxilModule::StripSubobjectsFromMetadata() {
NamedMDNode *pSubobjectsNamedMD =
GetModule()->getNamedMetadata(DxilMDHelper::kDxilSubobjectsMDName);
if (pSubobjectsNamedMD) {
GetModule()->eraseNamedMetadata(pSubobjectsNamedMD);
return true;
}
return false;
}
void DxilModule::UpdateValidatorVersionMetadata() {
m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
}
void DxilModule::ResetSerializedRootSignature(std::vector<uint8_t> &Value) {
m_SerializedRootSignature.assign(Value.begin(), Value.end());
}
DxilTypeSystem &DxilModule::GetTypeSystem() { return *m_pTypeSystem; }
const DxilTypeSystem &DxilModule::GetTypeSystem() const {
return *m_pTypeSystem;
}
std::vector<unsigned> &DxilModule::GetSerializedViewIdState() {
return m_SerializedState;
}
const std::vector<unsigned> &DxilModule::GetSerializedViewIdState() const {
return m_SerializedState;
}
void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
m_pTypeSystem.reset(pValue);
}
void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
void DxilModule::ResetEntryPropsMap(DxilEntryPropsMap &&PropMap) {
m_DxilEntryPropsMap.clear();
std::move(PropMap.begin(), PropMap.end(),
inserter(m_DxilEntryPropsMap, m_DxilEntryPropsMap.begin()));
}
static const StringRef llvmUsedName = "llvm.used";
void DxilModule::EmitLLVMUsed() {
if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
oldGV->eraseFromParent();
}
if (m_LLVMUsed.empty())
return;
vector<llvm::Constant *> GVs;
Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
GVs.resize(m_LLVMUsed.size());
for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
// Cast pointer to addrspace 0, as LLVMUsed elements must have the same
// type.
GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
} else {
GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
}
}
ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
GlobalVariable *pGV =
new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
ConstantArray::get(pATy, GVs), llvmUsedName);
pGV->setSection("llvm.metadata");
}
void DxilModule::ClearLLVMUsed() {
if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
oldGV->eraseFromParent();
}
if (m_LLVMUsed.empty())
return;
for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
pConst->removeDeadConstantUsers();
}
m_LLVMUsed.clear();
}
vector<GlobalVariable *> &DxilModule::GetLLVMUsed() { return m_LLVMUsed; }
// DXIL metadata serialization/deserialization.
void DxilModule::ClearDxilMetadata(Module &M) {
// Delete: DXIL version, validator version, DXIL shader model,
// entry point tuples (shader properties, signatures, resources)
// type system, view ID state, LLVM used, entry point tuples,
// root signature, function properties.
// Other cases for libs pending.
// LLVM used is a global variable - handle separately.
SmallVector<NamedMDNode *, 8> nodes;
for (NamedMDNode &b : M.named_metadata()) {
StringRef name = b.getName();
if (name == DxilMDHelper::kDxilVersionMDName ||
name == DxilMDHelper::kDxilValidatorVersionMDName ||
name == DxilMDHelper::kDxilShaderModelMDName ||
name == DxilMDHelper::kDxilEntryPointsMDName ||
name == DxilMDHelper::kDxilRootSignatureMDName ||
name == DxilMDHelper::kDxilIntermediateOptionsMDName ||
name == DxilMDHelper::kDxilResourcesMDName ||
name == DxilMDHelper::kDxilTypeSystemMDName ||
name == DxilMDHelper::kDxilViewIdStateMDName ||
name == DxilMDHelper::kDxilSubobjectsMDName ||
name == DxilMDHelper::kDxilCountersMDName ||
name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
nodes.push_back(&b);
}
}
for (size_t i = 0; i < nodes.size(); ++i) {
M.eraseNamedMetadata(nodes[i]);
}
}
void DxilModule::EmitDxilMetadata() {
m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
m_pMDHelper->EmitDxilShaderModel(m_pSM);
m_pMDHelper->EmitDxilIntermediateOptions(m_IntermediateFlags);
MDTuple *pMDProperties = nullptr;
uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
if (m_pSM->IsLib()) {
DxilFunctionProps props;
props.shaderKind = DXIL::ShaderKind::Library;
pMDProperties = m_pMDHelper->EmitDxilEntryProperties(flag, props,
GetAutoBindingSpace());
} else {
pMDProperties = m_pMDHelper->EmitDxilEntryProperties(
flag, m_DxilEntryPropsMap.begin()->second->props,
GetAutoBindingSpace());
}
MDTuple *pMDSignatures = nullptr;
if (!m_pSM->IsLib()) {
pMDSignatures = m_pMDHelper->EmitDxilSignatures(
m_DxilEntryPropsMap.begin()->second->sig);
}
MDTuple *pMDResources = EmitDxilResources();
if (pMDResources)
m_pMDHelper->EmitDxilResources(pMDResources);
m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
((m_ValMajor == 0 && m_ValMinor == 0) ||
(m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
m_pMDHelper->EmitDxilViewIdState(m_SerializedState);
}
// Emit the DXR Payload Annotations only for library Dxil 1.6 and above.
if (m_pSM->IsLib()) {
if (DXIL::CompareVersions(m_DxilMajor, m_DxilMinor, 1, 6) >= 0) {
m_pMDHelper->EmitDxrPayloadAnnotations(GetTypeSystem());
}
}
EmitLLVMUsed();
MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(
GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources,
pMDProperties);
vector<MDNode *> Entries;
Entries.emplace_back(pEntry);
if (m_pSM->IsLib()) {
// Sort functions by name to keep metadata deterministic
vector<const Function *> funcOrder;
funcOrder.reserve(m_DxilEntryPropsMap.size());
std::transform(m_DxilEntryPropsMap.begin(), m_DxilEntryPropsMap.end(),
std::back_inserter(funcOrder),
[](const std::pair<const llvm::Function *const,
std::unique_ptr<DxilEntryProps>> &p)
-> const Function * { return p.first; });
std::sort(funcOrder.begin(), funcOrder.end(),
[](const Function *F1, const Function *F2) {
return F1->getName() < F2->getName();
});
for (auto F : funcOrder) {
auto &entryProps = m_DxilEntryPropsMap[F];
MDTuple *pProps =
m_pMDHelper->EmitDxilEntryProperties(0, entryProps->props, 0);
MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(entryProps->sig);
MDTuple *pSubEntry = m_pMDHelper->EmitDxilEntryPointTuple(
const_cast<Function *>(F), F->getName().str(), pSig, nullptr, pProps);
Entries.emplace_back(pSubEntry);
}
funcOrder.clear();
// Save Subobjects
if (GetSubobjects()) {
m_pMDHelper->EmitSubobjects(*GetSubobjects());
}
}
m_pMDHelper->EmitDxilEntryPoints(Entries);
if (!m_SerializedRootSignature.empty()) {
m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
}
}
bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
return DxilMDHelper::IsKnownNamedMetaData(Node);
}
bool DxilModule::HasMetadataErrors() { return m_bMetadataErrors; }
void DxilModule::LoadDxilMetadata() {
m_bMetadataErrors = false;
m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
const ShaderModel *loadedSM;
m_pMDHelper->LoadDxilShaderModel(loadedSM);
m_pMDHelper->LoadDxilIntermediateOptions(m_IntermediateFlags);
// This must be set before LoadDxilEntryProperties
m_pMDHelper->SetShaderModel(loadedSM);
// Setting module shader model requires UseMinPrecision flag,
// which requires loading m_ShaderFlags,
// which requires global entry properties,
// so load entry properties first, then set the shader model
const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
if (!loadedSM->IsLib()) {
IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
}
Function *pEntryFunc;
string EntryName;
const llvm::MDOperand *pEntrySignatures, *pEntryResources, *pEntryProperties;
m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName,
pEntrySignatures, pEntryResources,
pEntryProperties);
uint64_t rawShaderFlags = 0;
DxilFunctionProps entryFuncProps;
entryFuncProps.shaderKind = loadedSM->GetKind();
m_pMDHelper->LoadDxilEntryProperties(*pEntryProperties, rawShaderFlags,
entryFuncProps, m_AutoBindingSpace);
m_bUseMinPrecision = true;
if (rawShaderFlags) {
m_ShaderFlags.SetShaderFlagsRaw(rawShaderFlags);
m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
m_bResMayAlias = !m_ShaderFlags.GetResMayNotAlias();
}
// Now that we have the UseMinPrecision flag, set shader model:
SetShaderModel(loadedSM, m_bUseMinPrecision);
// SetShaderModel will initialize m_DxilMajor/m_DxilMinor to min for SM,
// so, load here after shader model so it matches the metadata.
m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
if (loadedSM->IsLib()) {
for (unsigned i = 1; i < pEntries->getNumOperands(); i++) {
Function *pFunc;
string Name;
const llvm::MDOperand *pSignatures, *pResources, *pProperties;
m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(i), pFunc, Name,
pSignatures, pResources, pProperties);
DxilFunctionProps props;
uint64_t rawShaderFlags = 0;
unsigned autoBindingSpace = 0;
m_pMDHelper->LoadDxilEntryProperties(*pProperties, rawShaderFlags, props,
autoBindingSpace);
if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
// Add patch constant function to m_PatchConstantFunctions
m_PatchConstantFunctions.insert(props.ShaderProps.HS.patchConstantFunc);
}
std::unique_ptr<DxilEntryProps> pEntryProps =
make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
m_pMDHelper->LoadDxilSignatures(*pSignatures, pEntryProps->sig);
m_DxilEntryPropsMap[pFunc] = std::move(pEntryProps);
}
// Load Subobjects
std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
m_pMDHelper->LoadSubobjects(*pSubobjects);
if (pSubobjects->GetSubobjects().size()) {
ResetSubobjects(pSubobjects.release());
}
} else {
std::unique_ptr<DxilEntryProps> pEntryProps =
make_unique<DxilEntryProps>(entryFuncProps, m_bUseMinPrecision);
DxilFunctionProps *pFuncProps = &pEntryProps->props;
m_pMDHelper->LoadDxilSignatures(*pEntrySignatures, pEntryProps->sig);
m_DxilEntryPropsMap.clear();
m_DxilEntryPropsMap[pEntryFunc] = std::move(pEntryProps);
SetEntryFunction(pEntryFunc);
SetEntryFunctionName(EntryName);
SetShaderProperties(pFuncProps);
}
LoadDxilResources(*pEntryResources);
// Type system is not required for consumption of dxil.
try {
m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
} catch (hlsl::Exception &) {
m_bMetadataErrors = true;
#ifndef NDEBUG
throw;
#endif
m_pTypeSystem->GetStructAnnotationMap().clear();
m_pTypeSystem->GetFunctionAnnotationMap().clear();
}
// Payload annotations not required for consumption of dxil.
try {
m_pMDHelper->LoadDxrPayloadAnnotations(*m_pTypeSystem.get());
} catch (hlsl::Exception &) {
m_bMetadataErrors = true;
#ifndef NDEBUG
throw;
#endif
m_pTypeSystem->GetPayloadAnnotationMap().clear();
}
m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
m_pMDHelper->LoadDxilViewIdState(m_SerializedState);
m_bMetadataErrors |= m_pMDHelper->HasExtraMetadata();
}
MDTuple *DxilModule::EmitDxilResources() {
// Emit SRV records.
MDTuple *pTupleSRVs = nullptr;
if (!m_SRVs.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_SRVs.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
}
pTupleSRVs = MDNode::get(m_Ctx, MDVals);
}
// Emit UAV records.
MDTuple *pTupleUAVs = nullptr;
if (!m_UAVs.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_UAVs.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
}
pTupleUAVs = MDNode::get(m_Ctx, MDVals);
}
// Emit CBuffer records.
MDTuple *pTupleCBuffers = nullptr;
if (!m_CBuffers.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_CBuffers.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
}
pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
}
// Emit Sampler records.
MDTuple *pTupleSamplers = nullptr;
if (!m_Samplers.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_Samplers.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
}
pTupleSamplers = MDNode::get(m_Ctx, MDVals);
}
if (pTupleSRVs != nullptr || pTupleUAVs != nullptr ||
pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs,
pTupleCBuffers, pTupleSamplers);
} else {
return nullptr;
}
}
void DxilModule::ReEmitDxilResources() {
ClearDxilMetadata(*m_pModule);
EmitDxilMetadata();
}
void DxilModule::EmitDxilCounters() {
DxilCounters counters = {};
hlsl::CountInstructions(*m_pModule, counters);
m_pMDHelper->EmitDxilCounters(counters);
}
void DxilModule::LoadDxilCounters(DxilCounters &counters) const {
m_pMDHelper->LoadDxilCounters(counters);
}
template <typename TResource>
static bool
StripResourcesReflection(std::vector<std::unique_ptr<TResource>> &vec) {
bool bChanged = false;
for (auto &p : vec) {
p->SetGlobalName("");
// Cannot remove global symbol which used by validation.
bChanged = true;
}
return bChanged;
}
bool isSequentialType(Type *Ty) {
return isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<PointerType>(Ty);
}
// Return true if any members or components of struct <Ty> contain
// scalars of less than 32 bits or are matrices, in which case translation is
// required
typedef llvm::SmallSetVector<const StructType *, 4> SmallStructSetVector;
static bool
ResourceTypeRequiresTranslation(const StructType *Ty,
SmallStructSetVector &containedStructs) {
if (Ty->getName().startswith("class.matrix."))
return true;
bool bResult = false;
containedStructs.insert(Ty);
for (auto eTy : Ty->elements()) {
// Skip past all levels of sequential types to test their elements
while ((isSequentialType(eTy))) {
eTy = eTy->getContainedType(0);
}
// Recursively call this function again to process internal structs
if (StructType *structTy = dyn_cast<StructType>(eTy)) {
if (ResourceTypeRequiresTranslation(structTy, containedStructs))
bResult = true;
} else if (eTy->getScalarSizeInBits() < 32) { // test scalar sizes
bResult = true;
}
}
return bResult;
}
bool DxilModule::StripReflection() {
bool bChanged = false;
bool bIsLib = GetShaderModel()->IsLib();
// Remove names.
for (Function &F : m_pModule->functions()) {
for (BasicBlock &BB : F) {
if (BB.hasName()) {
BB.setName("");
bChanged = true;
}
for (Instruction &I : BB) {
if (I.hasName()) {
I.setName("");
bChanged = true;
}
}
}
}
if (bIsLib && GetUseMinPrecision()) {
// We must preserve struct annotations for resources containing
// min-precision types, since they have not yet been converted for legacy
// layout. Keep all structs contained in any we must keep.
SmallStructSetVector structsToKeep;
SmallStructSetVector containedStructs;
for (auto &CBuf : GetCBuffers())
if (StructType *ST = dyn_cast<StructType>(CBuf->GetHLSLType()))
if (ResourceTypeRequiresTranslation(ST, containedStructs))
structsToKeep.insert(containedStructs.begin(),
containedStructs.end());
for (auto &UAV : GetUAVs()) {
if (DXIL::IsStructuredBuffer(UAV->GetKind()))
if (StructType *ST = dyn_cast<StructType>(UAV->GetHLSLType()))
if (ResourceTypeRequiresTranslation(ST, containedStructs))
structsToKeep.insert(containedStructs.begin(),
containedStructs.end());
}
for (auto &SRV : GetSRVs()) {
if (SRV->IsStructuredBuffer() || SRV->IsTBuffer())
if (StructType *ST = dyn_cast<StructType>(SRV->GetHLSLType()))
if (ResourceTypeRequiresTranslation(ST, containedStructs))
structsToKeep.insert(containedStructs.begin(),
containedStructs.end());
}
m_pTypeSystem->GetStructAnnotationMap().remove_if(
[structsToKeep](
const std::pair<const StructType *,
std::unique_ptr<DxilStructAnnotation>> &I) {
return !structsToKeep.count(I.first);
});
} else {
// Remove struct annotations.
if (!m_pTypeSystem->GetStructAnnotationMap().empty()) {
m_pTypeSystem->GetStructAnnotationMap().clear();
bChanged = true;
}
if (DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) >= 0) {
// Remove function annotations.
if (!m_pTypeSystem->GetFunctionAnnotationMap().empty()) {
m_pTypeSystem->GetFunctionAnnotationMap().clear();
bChanged = true;
}
}
}
// Resource
if (!bIsLib) {
bChanged |= StripResourcesReflection(m_CBuffers);
bChanged |= StripResourcesReflection(m_UAVs);
bChanged |= StripResourcesReflection(m_SRVs);
bChanged |= StripResourcesReflection(m_Samplers);
}
// Unused global.
SmallVector<GlobalVariable *, 2> UnusedGlobals;
for (GlobalVariable &GV : m_pModule->globals()) {
if (GV.use_empty()) {
// Need to preserve this global, otherwise we drop constructors
// for static globals.
if (!bIsLib || GV.getName().compare("llvm.global_ctors") != 0)
UnusedGlobals.emplace_back(&GV);
}
}
bChanged |= !UnusedGlobals.empty();
for (GlobalVariable *GV : UnusedGlobals) {
GV->eraseFromParent();
}
// ReEmit meta.
if (bChanged)
ReEmitDxilResources();
return bChanged;
}
static void RemoveTypesFromSet(Type *Ty,
SetVector<const StructType *> &typeSet) {
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
while (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
if (StructType *ST = dyn_cast<StructType>(Ty)) {
if (typeSet.count(ST)) {
typeSet.remove(ST);
for (unsigned i = 0; i < ST->getNumElements(); i++) {
RemoveTypesFromSet(ST->getElementType(i), typeSet);
}
}
}
}
template <typename TResource>
static void RemoveUsedTypesFromSet(std::vector<std::unique_ptr<TResource>> &vec,
SetVector<const StructType *> &typeSet) {
for (auto &p : vec) {
RemoveTypesFromSet(p->GetHLSLType(), typeSet);
}
}
void DxilModule::RemoveUnusedTypeAnnotations() {
// Collect annotated types
const DxilTypeSystem::StructAnnotationMap &SAMap =
m_pTypeSystem->GetStructAnnotationMap();
SetVector<const StructType *> types;
for (const auto &it : SAMap)
types.insert(it.first);
// Iterate resource types and remove any HLSL types from set
RemoveUsedTypesFromSet(m_CBuffers, types);
RemoveUsedTypesFromSet(m_UAVs, types);
RemoveUsedTypesFromSet(m_SRVs, types);
// Iterate Function parameters and return types, removing any HLSL types found
// from set
for (Function &F : m_pModule->functions()) {
FunctionType *FT = F.getFunctionType();
RemoveTypesFromSet(FT->getReturnType(), types);
for (Type *PTy : FT->params())
RemoveTypesFromSet(PTy, types);
}
// Remove remaining set of types
for (const StructType *ST : types)
m_pTypeSystem->EraseStructAnnotation(ST);
}
template <typename _T>
static void CopyResourceInfo(_T &TargetRes, const _T &SourceRes,
DxilTypeSystem &TargetTypeSys,
const DxilTypeSystem &SourceTypeSys) {
if (TargetRes.GetKind() != SourceRes.GetKind() ||
TargetRes.GetLowerBound() != SourceRes.GetLowerBound() ||
TargetRes.GetRangeSize() != SourceRes.GetRangeSize() ||
TargetRes.GetSpaceID() != SourceRes.GetSpaceID()) {
DXASSERT(false, "otherwise, resource details don't match");
return;
}
if (TargetRes.GetGlobalName().empty() && !SourceRes.GetGlobalName().empty()) {
TargetRes.SetGlobalName(SourceRes.GetGlobalName());
}
if (TargetRes.GetGlobalSymbol() && SourceRes.GetGlobalSymbol() &&
SourceRes.GetGlobalSymbol()->hasName()) {
TargetRes.GetGlobalSymbol()->setName(
SourceRes.GetGlobalSymbol()->getName());
}
Type *Ty = SourceRes.GetHLSLType();
TargetRes.SetHLSLType(Ty);
TargetTypeSys.CopyTypeAnnotation(Ty, SourceTypeSys);
}
void DxilModule::RestoreResourceReflection(const DxilModule &SourceDM) {
DxilTypeSystem &TargetTypeSys = GetTypeSystem();
const DxilTypeSystem &SourceTypeSys = SourceDM.GetTypeSystem();
if (GetCBuffers().size() != SourceDM.GetCBuffers().size() ||
GetSRVs().size() != SourceDM.GetSRVs().size() ||
GetUAVs().size() != SourceDM.GetUAVs().size() ||
GetSamplers().size() != SourceDM.GetSamplers().size()) {
DXASSERT(false, "otherwise, resource lists don't match");
return;
}
for (unsigned i = 0; i < GetCBuffers().size(); ++i) {
CopyResourceInfo(GetCBuffer(i), SourceDM.GetCBuffer(i), TargetTypeSys,
SourceTypeSys);
}
for (unsigned i = 0; i < GetSRVs().size(); ++i) {
CopyResourceInfo(GetSRV(i), SourceDM.GetSRV(i), TargetTypeSys,
SourceTypeSys);
}
for (unsigned i = 0; i < GetUAVs().size(); ++i) {
CopyResourceInfo(GetUAV(i), SourceDM.GetUAV(i), TargetTypeSys,
SourceTypeSys);
}
for (unsigned i = 0; i < GetSamplers().size(); ++i) {
CopyResourceInfo(GetSampler(i), SourceDM.GetSampler(i), TargetTypeSys,
SourceTypeSys);
}
}
void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
if (MDO.get() == nullptr)
return;
const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
// Load SRV records.
if (pSRVs != nullptr) {
for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
unique_ptr<DxilResource> pSRV(new DxilResource);
m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
AddSRV(std::move(pSRV));
}
}
// Load UAV records.
if (pUAVs != nullptr) {
for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
unique_ptr<DxilResource> pUAV(new DxilResource);
m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
AddUAV(std::move(pUAV));
}
}
// Load CBuffer records.
if (pCBuffers != nullptr) {
for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
AddCBuffer(std::move(pCB));
}
}
// Load Sampler records.
if (pSamplers != nullptr) {
for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
unique_ptr<DxilSampler> pSampler(new DxilSampler);
m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
AddSampler(std::move(pSampler));
}
}
}
void DxilModule::StripShaderSourcesAndCompileOptions(
bool bReplaceWithDummyData) {
// Remove dx.source metadata.
if (NamedMDNode *contents = m_pModule->getNamedMetadata(
DxilMDHelper::kDxilSourceContentsMDName)) {
contents->eraseFromParent();
if (bReplaceWithDummyData) {
// Insert an empty source and content
llvm::LLVMContext &context = m_pModule->getContext();
llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(
DxilMDHelper::kDxilSourceContentsMDName);
llvm::Metadata *operands[2] = {llvm::MDString::get(context, ""),
llvm::MDString::get(context, "")};
newNamedMD->addOperand(llvm::MDTuple::get(context, operands));
}
}
if (NamedMDNode *defines =
m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName)) {
defines->eraseFromParent();
if (bReplaceWithDummyData) {
llvm::LLVMContext &context = m_pModule->getContext();
llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(
DxilMDHelper::kDxilSourceDefinesMDName);
newNamedMD->addOperand(
llvm::MDTuple::get(context, llvm::ArrayRef<llvm::Metadata *>()));
}
}
if (NamedMDNode *mainFileName = m_pModule->getNamedMetadata(
DxilMDHelper::kDxilSourceMainFileNameMDName)) {
mainFileName->eraseFromParent();
if (bReplaceWithDummyData) {
// Insert an empty file name
llvm::LLVMContext &context = m_pModule->getContext();
llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(
DxilMDHelper::kDxilSourceMainFileNameMDName);
llvm::Metadata *operands[1] = {llvm::MDString::get(context, "")};
newNamedMD->addOperand(llvm::MDTuple::get(context, operands));
}
}
if (NamedMDNode *arguments =
m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName)) {
arguments->eraseFromParent();
if (bReplaceWithDummyData) {
llvm::LLVMContext &context = m_pModule->getContext();
llvm::NamedMDNode *newNamedMD = m_pModule->getOrInsertNamedMetadata(
DxilMDHelper::kDxilSourceArgsMDName);
newNamedMD->addOperand(
llvm::MDTuple::get(context, llvm::ArrayRef<llvm::Metadata *>()));
}
}
if (NamedMDNode *binding = m_pModule->getNamedMetadata(
DxilMDHelper::kDxilDxcBindingTableMDName)) {
binding->eraseFromParent();
}
}
void DxilModule::StripDebugRelatedCode() {
StripShaderSourcesAndCompileOptions();
if (NamedMDNode *flags = m_pModule->getModuleFlagsMetadata()) {
SmallVector<llvm::Module::ModuleFlagEntry, 4> flagEntries;
m_pModule->getModuleFlagsMetadata(flagEntries);
flags->eraseFromParent();
for (unsigned i = 0; i < flagEntries.size(); i++) {
llvm::Module::ModuleFlagEntry &entry = flagEntries[i];
if (entry.Key->getString() == "Dwarf Version" ||
entry.Key->getString() == "Debug Info Version") {
continue;
}
m_pModule->addModuleFlag(entry.Behavior, entry.Key->getString(),
cast<ConstantAsMetadata>(entry.Val)->getValue());
}
}
}
DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
if (m_pDebugInfoFinder == nullptr) {
m_pDebugInfoFinder = make_unique<llvm::DebugInfoFinder>();
m_pDebugInfoFinder->processModule(*m_pModule);
}
return *m_pDebugInfoFinder;
}
// Check if the instruction has fast math flags configured to indicate
// the instruction is precise.
// Precise fast math flags means none of the fast math flags are set.
bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
}
// Set fast math flags configured to indicate the instruction is precise.
void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
assert(isa<FPMathOperator>(inst));
inst->copyFastMathFlags(FastMathFlags());
}
// True if fast math flags are preserved across serialization/deserialization
// of the dxil module.
//
// We need to check for this when querying fast math flags for preciseness
// otherwise we will be overly conservative by reporting instructions precise
// because their fast math flags were not preserved.
//
// Currently we restrict it to the instruction types that have fast math
// preserved in the bitcode. We can expand this by converting fast math
// flags to dx.precise metadata during serialization and back to fast
// math flags during deserialization.
bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
return isa<FPMathOperator>(inst) &&
(isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
}
bool DxilModule::IsPrecise(const Instruction *inst) const {
if (m_ShaderFlags.GetDisableMathRefactoring())
return true;
else if (DxilMDHelper::IsMarkedPrecise(inst))
return true;
else if (PreservesFastMathFlags(inst))
return HasPreciseFastMathFlags(inst);
else
return false;
}
bool DxilModule::ShaderCompatInfo::Merge(ShaderCompatInfo &other) {
bool changed = DXIL::UpdateToMaxOfVersions(minMajor, minMinor, other.minMajor,
other.minMinor);
if ((mask & other.mask) != mask) {
mask &= other.mask;
changed = true;
}
uint64_t rawBefore = shaderFlags.GetShaderFlagsRaw();
shaderFlags.CombineShaderFlags(other.shaderFlags);
if (rawBefore != shaderFlags.GetShaderFlagsRaw())
changed = true;
return changed;
}
// Use the function properties `props` to determine the minimum shader model and
// flag requirements based on shader stage and feature usage.
// Compare that minimum required version to the values passed in with
// `minMajor` and `minMinor` and pass the maximum of those back through those
// same variables.
// Adjusts `ShaderFlags` argument according to `props` set.
static void AdjustMinimumShaderModelAndFlags(const DxilFunctionProps *props,
ShaderFlags &flags,
unsigned &minMajor,
unsigned &minMinor) {
// Adjust flags based on DxilFunctionProps and compute minimum shader model.
// Library functions use flags to capture properties that may or may not be
// used in the final shader, depending on that final shader's shader model.
// These flags will be combined up a call graph until we hit an entry,
// function, at which point, these flags and minimum shader model need to be
// adjusted.
// For instance: derivatives are allowed in CS/MS/AS in 6.6+, and for MS/AS,
// a feature bit is required. Libary functions will capture any derivative
// use into the UsesDerivatives feature bit, which is used to calculate the
// final requirements once we reach an entry function.
// Adjust things based on known shader entry point once we have one.
// This must be done after combining flags from called functions.
if (props) {
// This flag doesn't impact min shader model until we know what kind of
// entry point we have. Then, we may need to clear the flag, when it doesn't
// apply.
if (flags.GetUsesDerivatives()) {
if (props->IsCS()) {
// Always supported if SM 6.6+.
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 6);
} else if (props->IsMS() || props->IsAS()) {
// Requires flag for support on SM 6.6+.
flags.SetDerivativesInMeshAndAmpShaders(true);
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 6);
}
}
// If function has WaveSize, this also constrains the minimum shader model.
if (props->WaveSize.IsDefined()) {
if (props->WaveSize.IsRange())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 8);
else
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 6);
}
// Adjust minimum shader model based on shader stage.
if (props->IsMS() || props->IsAS())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 5);
else if (props->IsRay())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 3);
else if (props->IsNode())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 8);
}
// Adjust minimum shader model based on flags.
if (flags.GetSampleCmpGradientOrBias() || flags.GetExtendedCommandInfo())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 8);
else if (flags.GetAdvancedTextureOps() || flags.GetWriteableMSAATextures())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 7);
else if (flags.GetAtomicInt64OnTypedResource() ||
flags.GetAtomicInt64OnGroupShared() ||
flags.GetAtomicInt64OnHeapResource() ||
flags.GetResourceDescriptorHeapIndexing() ||
flags.GetSamplerDescriptorHeapIndexing())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 6);
else if (flags.GetRaytracingTier1_1() || flags.GetSamplerFeedback())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 5);
else if (flags.GetShadingRate())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 4);
else if (flags.GetLowPrecisionPresent() && flags.GetUseNativeLowPrecision())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 2);
else if (flags.GetViewID() || flags.GetBarycentrics())
DXIL::UpdateToMaxOfVersions(minMajor, minMinor, 6, 1);
}
static bool RequiresRaytracingTier1_1(const DxilSubobjects *pSubobjects) {
if (!pSubobjects)
return false;
for (const auto &it : pSubobjects->GetSubobjects()) {
switch (it.second->GetKind()) {
case DXIL::SubobjectKind::RaytracingPipelineConfig1:
return true;
case DXIL::SubobjectKind::StateObjectConfig: {
uint32_t configFlags;
if (it.second->GetStateObjectConfig(configFlags) &&
((configFlags &
(unsigned)DXIL::StateObjectFlags::AllowStateObjectAdditions) != 0))
return true;
} break;
default:
break;
}
}
return false;
}
void DxilModule::ComputeShaderCompatInfo() {
m_FuncToShaderCompat.clear();
bool dxil15Plus = DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 5) >= 0;
bool dxil18Plus = DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 8) >= 0;
bool dxil19Plus = DXIL::CompareVersions(m_ValMajor, m_ValMinor, 1, 9) >= 0;
// Prior to validator version 1.8, DXR 1.1 flag was set on every function
// if subobjects contained any DXR 1.1 subobjects.
bool setDXR11OnAllFunctions =
dxil15Plus && !dxil18Plus && RequiresRaytracingTier1_1(GetSubobjects());
// Initialize worklist with functions that have callers
SmallSetVector<llvm::Function *, 8> worklist;
for (auto &function : GetModule()->getFunctionList()) {
if (!function.isDeclaration()) {
// Initialize worklist with functions with callers.
// only used for validator version 1.8+
if (dxil18Plus && !function.user_empty())
worklist.insert(&function);
// Collect shader flags for function.
// Insert or lookup info
ShaderCompatInfo &info = m_FuncToShaderCompat[&function];
info.shaderFlags = ShaderFlags::CollectShaderFlags(&function, this);
if (setDXR11OnAllFunctions)
info.shaderFlags.SetRaytracingTier1_1(true);
} else if (!function.isIntrinsic() &&
function.getLinkage() ==
llvm::GlobalValue::LinkageTypes::ExternalLinkage &&
OP::IsDxilOpFunc(&function)) {
// update min shader model and shader stage mask per function
UpdateFunctionToShaderCompat(&function);
}
}
// Propagate ShaderCompatInfo to callers, limit to 1.8+ for compatibility
if (dxil18Plus) {
while (!worklist.empty()) {
llvm::Function *F = worklist.pop_back_val();
ShaderCompatInfo &calleeInfo = m_FuncToShaderCompat[F];
// Update callers
for (auto U : F->users()) {
if (CallInst *CI = dyn_cast<CallInst>(U)) {
llvm::Function *caller = CI->getParent()->getParent();
// Merge info, if changed and called, add to worklist so we update
// any callers of caller as well.
// Insert or lookup info
if (m_FuncToShaderCompat[caller].Merge(calleeInfo) &&
!caller->user_empty())
worklist.insert(caller);
}
}
}
}
// We must select the appropriate shader mask for the validator version,
// so we don't set any bits the validator doesn't recognize.
unsigned ValidShaderMask =
(1 << ((unsigned)DXIL::ShaderKind::LastValid + 1)) - 1;
if (!dxil15Plus) {
ValidShaderMask = (1 << ((unsigned)DXIL::ShaderKind::Last_1_4 + 1)) - 1;
} else if (!dxil18Plus) {
ValidShaderMask = (1 << ((unsigned)DXIL::ShaderKind::Last_1_7 + 1)) - 1;
} else if (!dxil19Plus) {
ValidShaderMask = (1 << ((unsigned)DXIL::ShaderKind::Last_1_8 + 1)) - 1;
}
for (auto &function : GetModule()->getFunctionList()) {
if (function.isDeclaration())
continue;
DXASSERT(m_FuncToShaderCompat.count(&function) != 0,
"otherwise, function missed earlier somehow!");
ShaderCompatInfo &info = m_FuncToShaderCompat[&function];
DXIL::ShaderKind shaderKind = DXIL::ShaderKind::Library;
const DxilFunctionProps *props = nullptr;
if (HasDxilFunctionProps(&function)) {
props = &GetDxilFunctionProps(&function);
shaderKind = props->shaderKind;
}
if (shaderKind == DXIL::ShaderKind::Library)
info.mask &= ValidShaderMask;
else
info.mask &= (1U << static_cast<unsigned>(shaderKind));
// Increase min target based on features used:
ShaderFlags &flags = info.shaderFlags;
if (dxil18Plus) {
// This handles WaveSize requirement as well.
AdjustMinimumShaderModelAndFlags(props, flags, info.minMajor,
info.minMinor);
} else {
// Match prior versions that were missing some feature detection.
if (flags.GetUseNativeLowPrecision() && flags.GetLowPrecisionPresent())
DXIL::UpdateToMaxOfVersions(info.minMajor, info.minMinor, 6, 2);
else if (flags.GetBarycentrics() || flags.GetViewID())
DXIL::UpdateToMaxOfVersions(info.minMajor, info.minMinor, 6, 1);
}
}
}
void DxilModule::UpdateFunctionToShaderCompat(const llvm::Function *dxilFunc) {
const bool bWithTranslation = GetShaderModel()->IsLib();
#define SFLAG(stage) ((unsigned)1 << (unsigned)DXIL::ShaderKind::stage)
for (const llvm::User *user : dxilFunc->users()) {
if (const llvm::CallInst *CI = dyn_cast<const llvm::CallInst>(user)) {
// Find calling function
const llvm::Function *F =
cast<const llvm::Function>(CI->getParent()->getParent());
// Insert or lookup info
ShaderCompatInfo &info = m_FuncToShaderCompat[F];
unsigned major, minor, mask;
OP::GetMinShaderModelAndMask(CI, bWithTranslation, m_ValMajor, m_ValMinor,
major, minor, mask);
DXIL::UpdateToMaxOfVersions(info.minMajor, info.minMinor, major, minor);
info.mask &= mask;
} else if (const llvm::LoadInst *LI = dyn_cast<LoadInst>(user)) {
// If loading a groupshared variable, limit to CS/AS/MS/Node
if (LI->getPointerAddressSpace() == DXIL::kTGSMAddrSpace) {
const llvm::Function *F =
cast<const llvm::Function>(LI->getParent()->getParent());
// Insert or lookup info
ShaderCompatInfo &info = m_FuncToShaderCompat[F];
info.mask &=
(SFLAG(Compute) | SFLAG(Mesh) | SFLAG(Amplification) | SFLAG(Node));
}
} else if (const llvm::StoreInst *SI = dyn_cast<StoreInst>(user)) {
// If storing to a groupshared variable, limit to CS/AS/MS/Node
if (SI->getPointerAddressSpace() == DXIL::kTGSMAddrSpace) {
const llvm::Function *F =
cast<const llvm::Function>(SI->getParent()->getParent());
// Insert or lookup info
ShaderCompatInfo &info = m_FuncToShaderCompat[F];
info.mask &=
(SFLAG(Compute) | SFLAG(Mesh) | SFLAG(Amplification) | SFLAG(Node));
}
}
}
#undef SFLAG
}
const DxilModule::ShaderCompatInfo *
DxilModule::GetCompatInfoForFunction(const llvm::Function *F) const {
auto it = m_FuncToShaderCompat.find(F);
if (it != m_FuncToShaderCompat.end())
return &it->second;
return nullptr;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/LLVMBuild.txt | ; Copyright (C) Microsoft Corporation. All rights reserved.
; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DXIL
parent = Libraries
required_libraries = BitReader Core DxcSupport Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilShaderModel.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilShaderModel.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <limits.h>
#include "dxc/DXIL/DxilSemantic.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
namespace hlsl {
ShaderModel::ShaderModel(Kind Kind, unsigned Major, unsigned Minor,
const char *pszName, unsigned NumInputRegs,
unsigned NumOutputRegs, bool bUAVs, bool bTypedUavs,
unsigned NumUAVRegs)
: m_Kind(Kind), m_Major(Major), m_Minor(Minor), m_pszName(pszName),
m_NumInputRegs(NumInputRegs), m_NumOutputRegs(NumOutputRegs),
m_bTypedUavs(bTypedUavs), m_NumUAVRegs(NumUAVRegs) {}
bool ShaderModel::operator==(const ShaderModel &other) const {
return m_Kind == other.m_Kind && m_Major == other.m_Major &&
m_Minor == other.m_Minor && strcmp(m_pszName, other.m_pszName) == 0 &&
m_NumInputRegs == other.m_NumInputRegs &&
m_NumOutputRegs == other.m_NumOutputRegs &&
m_bTypedUavs == other.m_bTypedUavs &&
m_NumUAVRegs == other.m_NumUAVRegs;
}
bool ShaderModel::IsValid() const {
DXASSERT(IsPS() || IsVS() || IsGS() || IsHS() || IsDS() || IsCS() ||
IsLib() || IsMS() || IsAS() || m_Kind == Kind::Invalid,
"invalid shader model");
return m_Kind != Kind::Invalid;
}
bool ShaderModel::IsValidForDxil() const {
if (!IsValid())
return false;
switch (m_Major) {
case 6: {
switch (m_Minor) {
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_is_valid_for_dxil()</py>*/
// clang-format on
// VALRULE-TEXT:BEGIN
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
// VALRULE-TEXT:END
return true;
case kOfflineMinor:
return m_Kind == Kind::Library;
}
} break;
}
return false;
}
const ShaderModel *ShaderModel::Get(Kind Kind, unsigned Major, unsigned Minor) {
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_shader_model_get()</py>*/
// VALRULE-TEXT:BEGIN
const static std::pair<unsigned, unsigned> hashToIdxMap[] = {
{1024, 0}, // ps_4_0
{1025, 1}, // ps_4_1
{1280, 2}, // ps_5_0
{1281, 3}, // ps_5_1
{1536, 4}, // ps_6_0
{1537, 5}, // ps_6_1
{1538, 6}, // ps_6_2
{1539, 7}, // ps_6_3
{1540, 8}, // ps_6_4
{1541, 9}, // ps_6_5
{1542, 10}, // ps_6_6
{1543, 11}, // ps_6_7
{1544, 12}, // ps_6_8
{66560, 13}, // vs_4_0
{66561, 14}, // vs_4_1
{66816, 15}, // vs_5_0
{66817, 16}, // vs_5_1
{67072, 17}, // vs_6_0
{67073, 18}, // vs_6_1
{67074, 19}, // vs_6_2
{67075, 20}, // vs_6_3
{67076, 21}, // vs_6_4
{67077, 22}, // vs_6_5
{67078, 23}, // vs_6_6
{67079, 24}, // vs_6_7
{67080, 25}, // vs_6_8
{132096, 26}, // gs_4_0
{132097, 27}, // gs_4_1
{132352, 28}, // gs_5_0
{132353, 29}, // gs_5_1
{132608, 30}, // gs_6_0
{132609, 31}, // gs_6_1
{132610, 32}, // gs_6_2
{132611, 33}, // gs_6_3
{132612, 34}, // gs_6_4
{132613, 35}, // gs_6_5
{132614, 36}, // gs_6_6
{132615, 37}, // gs_6_7
{132616, 38}, // gs_6_8
{197888, 39}, // hs_5_0
{197889, 40}, // hs_5_1
{198144, 41}, // hs_6_0
{198145, 42}, // hs_6_1
{198146, 43}, // hs_6_2
{198147, 44}, // hs_6_3
{198148, 45}, // hs_6_4
{198149, 46}, // hs_6_5
{198150, 47}, // hs_6_6
{198151, 48}, // hs_6_7
{198152, 49}, // hs_6_8
{263424, 50}, // ds_5_0
{263425, 51}, // ds_5_1
{263680, 52}, // ds_6_0
{263681, 53}, // ds_6_1
{263682, 54}, // ds_6_2
{263683, 55}, // ds_6_3
{263684, 56}, // ds_6_4
{263685, 57}, // ds_6_5
{263686, 58}, // ds_6_6
{263687, 59}, // ds_6_7
{263688, 60}, // ds_6_8
{328704, 61}, // cs_4_0
{328705, 62}, // cs_4_1
{328960, 63}, // cs_5_0
{328961, 64}, // cs_5_1
{329216, 65}, // cs_6_0
{329217, 66}, // cs_6_1
{329218, 67}, // cs_6_2
{329219, 68}, // cs_6_3
{329220, 69}, // cs_6_4
{329221, 70}, // cs_6_5
{329222, 71}, // cs_6_6
{329223, 72}, // cs_6_7
{329224, 73}, // cs_6_8
{394753, 74}, // lib_6_1
{394754, 75}, // lib_6_2
{394755, 76}, // lib_6_3
{394756, 77}, // lib_6_4
{394757, 78}, // lib_6_5
{394758, 79}, // lib_6_6
{394759, 80}, // lib_6_7
{394760, 81}, // lib_6_8
// lib_6_x is for offline linking only, and relaxes restrictions
{394767, 82}, // lib_6_x
{853509, 83}, // ms_6_5
{853510, 84}, // ms_6_6
{853511, 85}, // ms_6_7
{853512, 86}, // ms_6_8
{919045, 87}, // as_6_5
{919046, 88}, // as_6_6
{919047, 89}, // as_6_7
{919048, 90}, // as_6_8
};
unsigned hash = (unsigned)Kind << 16 | Major << 8 | Minor;
auto pred = [](const std::pair<unsigned, unsigned> &elem, unsigned val) {
return elem.first < val;
};
auto it = std::lower_bound(std::begin(hashToIdxMap), std::end(hashToIdxMap),
hash, pred);
if (it == std::end(hashToIdxMap) || it->first != hash)
return GetInvalid();
return &ms_ShaderModels[it->second];
// VALRULE-TEXT:END
}
const ShaderModel *ShaderModel::GetByName(llvm::StringRef Name) {
// [ps|vs|gs|hs|ds|cs|ms|as]_[major]_[minor]
Kind kind;
if (Name.empty()) {
return GetInvalid();
}
switch (Name[0]) {
case 'p':
kind = Kind::Pixel;
break;
case 'v':
kind = Kind::Vertex;
break;
case 'g':
kind = Kind::Geometry;
break;
case 'h':
kind = Kind::Hull;
break;
case 'd':
kind = Kind::Domain;
break;
case 'c':
kind = Kind::Compute;
break;
case 'l':
kind = Kind::Library;
break;
case 'm':
kind = Kind::Mesh;
break;
case 'a':
kind = Kind::Amplification;
break;
default:
return GetInvalid();
}
unsigned Idx = 3;
if (kind != Kind::Library) {
if (Name[1] != 's' || Name[2] != '_')
return GetInvalid();
} else {
if (Name[1] != 'i' || Name[2] != 'b' || Name[3] != '_')
return GetInvalid();
Idx = 4;
}
unsigned Major;
switch (Name[Idx++]) {
case '4':
Major = 4;
break;
case '5':
Major = 5;
break;
case '6':
Major = 6;
break;
default:
return GetInvalid();
}
if (Name[Idx++] != '_')
return GetInvalid();
unsigned Minor;
switch (Name[Idx++]) {
case '0':
Minor = 0;
break;
case '1':
Minor = 1;
break;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_shader_model_by_name()</py>*/
// clang-format on
// VALRULE-TEXT:BEGIN
case '2':
if (Major == 6) {
Minor = 2;
break;
} else
return GetInvalid();
case '3':
if (Major == 6) {
Minor = 3;
break;
} else
return GetInvalid();
case '4':
if (Major == 6) {
Minor = 4;
break;
} else
return GetInvalid();
case '5':
if (Major == 6) {
Minor = 5;
break;
} else
return GetInvalid();
case '6':
if (Major == 6) {
Minor = 6;
break;
} else
return GetInvalid();
case '7':
if (Major == 6) {
Minor = 7;
break;
} else
return GetInvalid();
case '8':
if (Major == 6) {
Minor = 8;
break;
} else
return GetInvalid();
// VALRULE-TEXT:END
case 'x':
if (kind == Kind::Library && Major == 6) {
Minor = kOfflineMinor;
break;
} else
return GetInvalid();
default:
return GetInvalid();
}
// make sure there isn't anything after the minor
if (Name.size() > Idx)
return GetInvalid();
return Get(kind, Major, Minor);
}
void ShaderModel::GetDxilVersion(unsigned &DxilMajor,
unsigned &DxilMinor) const {
DXASSERT(IsValidForDxil(), "invalid shader model");
DxilMajor = 1;
switch (m_Minor) {
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_dxil_version()</py>*/
// VALRULE-TEXT:BEGIN
case 0:
DxilMinor = 0;
break;
case 1:
DxilMinor = 1;
break;
case 2:
DxilMinor = 2;
break;
case 3:
DxilMinor = 3;
break;
case 4:
DxilMinor = 4;
break;
case 5:
DxilMinor = 5;
break;
case 6:
DxilMinor = 6;
break;
case 7:
DxilMinor = 7;
break;
case 8:
DxilMinor = 8;
break;
case kOfflineMinor: // Always update this to highest dxil version
DxilMinor = 8;
break;
// VALRULE-TEXT:END
default:
DXASSERT(0, "IsValidForDxil() should have caught this.");
break;
}
}
void ShaderModel::GetMinValidatorVersion(unsigned &ValMajor,
unsigned &ValMinor) const {
DXASSERT(IsValidForDxil(), "invalid shader model");
ValMajor = 1;
switch (m_Minor) {
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_min_validator_version()</py>*/
// clang-format on
// VALRULE-TEXT:BEGIN
case 0:
ValMinor = 0;
break;
case 1:
ValMinor = 1;
break;
case 2:
ValMinor = 2;
break;
case 3:
ValMinor = 3;
break;
case 4:
ValMinor = 4;
break;
case 5:
ValMinor = 5;
break;
case 6:
ValMinor = 6;
break;
case 7:
ValMinor = 7;
break;
case 8:
ValMinor = 8;
break;
// VALRULE-TEXT:END
case kOfflineMinor:
ValMajor = 0;
ValMinor = 0;
break;
default:
DXASSERT(0, "IsValidForDxil() should have caught this.");
break;
}
}
static const char *ShaderModelKindNames[] = {
"ps", "vs", "gs", "hs",
"ds", "cs", "lib", "raygeneration",
"intersection", "anyhit", "closesthit", "miss",
"callable", "ms", "as", "node",
"invalid",
};
const char *ShaderModel::GetKindName() const { return GetKindName(m_Kind); }
const char *ShaderModel::GetKindName(Kind kind) {
static_assert(static_cast<unsigned>(Kind::Invalid) ==
_countof(ShaderModelKindNames) - 1,
"Invalid kinds or names");
return ShaderModelKindNames[static_cast<unsigned int>(kind)];
}
const ShaderModel *ShaderModel::GetInvalid() {
return &ms_ShaderModels[kNumShaderModels - 1];
}
DXIL::ShaderKind ShaderModel::KindFromFullName(llvm::StringRef Name) {
return llvm::StringSwitch<DXIL::ShaderKind>(Name)
.Case("pixel", DXIL::ShaderKind::Pixel)
.Case("vertex", DXIL::ShaderKind::Vertex)
.Case("geometry", DXIL::ShaderKind::Geometry)
.Case("hull", DXIL::ShaderKind::Hull)
.Case("domain", DXIL::ShaderKind::Domain)
.Case("compute", DXIL::ShaderKind::Compute)
.Case("raygeneration", DXIL::ShaderKind::RayGeneration)
.Case("intersection", DXIL::ShaderKind::Intersection)
.Case("anyhit", DXIL::ShaderKind::AnyHit)
.Case("closesthit", DXIL::ShaderKind::ClosestHit)
.Case("miss", DXIL::ShaderKind::Miss)
.Case("callable", DXIL::ShaderKind::Callable)
.Case("mesh", DXIL::ShaderKind::Mesh)
.Case("amplification", DXIL::ShaderKind::Amplification)
.Case("node", DXIL::ShaderKind::Node)
.Default(DXIL::ShaderKind::Invalid);
}
const llvm::StringRef ShaderModel::FullNameFromKind(DXIL::ShaderKind sk) {
switch (sk) {
case DXIL::ShaderKind::Pixel:
return "pixel";
case DXIL::ShaderKind::Vertex:
return "vertex";
case DXIL::ShaderKind::Geometry:
return "geometry";
case DXIL::ShaderKind::Hull:
return "hull";
case DXIL::ShaderKind::Domain:
return "domain";
case DXIL::ShaderKind::Compute:
return "compute";
// Library has no full name for use with shader attribute.
case DXIL::ShaderKind::Library:
case DXIL::ShaderKind::Invalid:
return llvm::StringRef();
case DXIL::ShaderKind::RayGeneration:
return "raygeneration";
case DXIL::ShaderKind::Intersection:
return "intersection";
case DXIL::ShaderKind::AnyHit:
return "anyhit";
case DXIL::ShaderKind::ClosestHit:
return "closesthit";
case DXIL::ShaderKind::Miss:
return "miss";
case DXIL::ShaderKind::Callable:
return "callable";
case DXIL::ShaderKind::Mesh:
return "mesh";
case DXIL::ShaderKind::Amplification:
return "amplification";
case DXIL::ShaderKind::Node:
return "node";
default:
llvm_unreachable("unknown ShaderKind");
}
}
bool ShaderModel::AllowDerivatives(DXIL::ShaderKind sk) const {
switch (sk) {
case DXIL::ShaderKind::Pixel:
case DXIL::ShaderKind::Library:
case DXIL::ShaderKind::Node:
return true;
case DXIL::ShaderKind::Compute:
case DXIL::ShaderKind::Amplification:
case DXIL::ShaderKind::Mesh:
return IsSM66Plus();
case DXIL::ShaderKind::Vertex:
case DXIL::ShaderKind::Geometry:
case DXIL::ShaderKind::Hull:
case DXIL::ShaderKind::Domain:
case DXIL::ShaderKind::RayGeneration:
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Miss:
case DXIL::ShaderKind::Callable:
case DXIL::ShaderKind::Invalid:
return false;
}
static_assert(DXIL::ShaderKind::LastValid == DXIL::ShaderKind::Node,
"otherwise, switch needs to be updated.");
llvm_unreachable("unknown ShaderKind");
}
typedef ShaderModel SM;
typedef Semantic SE;
const ShaderModel ShaderModel::ms_ShaderModels[kNumShaderModels] = {
// IR OR UAV? TyUAV? UAV base
/* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_shader_models()</py>*/
// VALRULE-TEXT:BEGIN
SM(Kind::Pixel, 4, 0, "ps_4_0", 32, 8, false, false, 0),
SM(Kind::Pixel, 4, 1, "ps_4_1", 32, 8, false, false, 0),
SM(Kind::Pixel, 5, 0, "ps_5_0", 32, 8, true, true, 64),
SM(Kind::Pixel, 5, 1, "ps_5_1", 32, 8, true, true, 64),
SM(Kind::Pixel, 6, 0, "ps_6_0", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 1, "ps_6_1", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 2, "ps_6_2", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 3, "ps_6_3", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 4, "ps_6_4", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 5, "ps_6_5", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 6, "ps_6_6", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 7, "ps_6_7", 32, 8, true, true, UINT_MAX),
SM(Kind::Pixel, 6, 8, "ps_6_8", 32, 8, true, true, UINT_MAX),
SM(Kind::Vertex, 4, 0, "vs_4_0", 16, 16, false, false, 0),
SM(Kind::Vertex, 4, 1, "vs_4_1", 32, 32, false, false, 0),
SM(Kind::Vertex, 5, 0, "vs_5_0", 32, 32, true, true, 64),
SM(Kind::Vertex, 5, 1, "vs_5_1", 32, 32, true, true, 64),
SM(Kind::Vertex, 6, 0, "vs_6_0", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 1, "vs_6_1", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 2, "vs_6_2", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 3, "vs_6_3", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 4, "vs_6_4", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 5, "vs_6_5", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 6, "vs_6_6", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 7, "vs_6_7", 32, 32, true, true, UINT_MAX),
SM(Kind::Vertex, 6, 8, "vs_6_8", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 4, 0, "gs_4_0", 16, 32, false, false, 0),
SM(Kind::Geometry, 4, 1, "gs_4_1", 32, 32, false, false, 0),
SM(Kind::Geometry, 5, 0, "gs_5_0", 32, 32, true, true, 64),
SM(Kind::Geometry, 5, 1, "gs_5_1", 32, 32, true, true, 64),
SM(Kind::Geometry, 6, 0, "gs_6_0", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 1, "gs_6_1", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 2, "gs_6_2", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 3, "gs_6_3", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 4, "gs_6_4", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 5, "gs_6_5", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 6, "gs_6_6", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 7, "gs_6_7", 32, 32, true, true, UINT_MAX),
SM(Kind::Geometry, 6, 8, "gs_6_8", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 5, 0, "hs_5_0", 32, 32, true, true, 64),
SM(Kind::Hull, 5, 1, "hs_5_1", 32, 32, true, true, 64),
SM(Kind::Hull, 6, 0, "hs_6_0", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 1, "hs_6_1", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 2, "hs_6_2", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 3, "hs_6_3", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 4, "hs_6_4", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 5, "hs_6_5", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 6, "hs_6_6", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 7, "hs_6_7", 32, 32, true, true, UINT_MAX),
SM(Kind::Hull, 6, 8, "hs_6_8", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 5, 0, "ds_5_0", 32, 32, true, true, 64),
SM(Kind::Domain, 5, 1, "ds_5_1", 32, 32, true, true, 64),
SM(Kind::Domain, 6, 0, "ds_6_0", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 1, "ds_6_1", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 2, "ds_6_2", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 3, "ds_6_3", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 4, "ds_6_4", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 5, "ds_6_5", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 6, "ds_6_6", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 7, "ds_6_7", 32, 32, true, true, UINT_MAX),
SM(Kind::Domain, 6, 8, "ds_6_8", 32, 32, true, true, UINT_MAX),
SM(Kind::Compute, 4, 0, "cs_4_0", 0, 0, false, false, 0),
SM(Kind::Compute, 4, 1, "cs_4_1", 0, 0, false, false, 0),
SM(Kind::Compute, 5, 0, "cs_5_0", 0, 0, true, true, 64),
SM(Kind::Compute, 5, 1, "cs_5_1", 0, 0, true, true, 64),
SM(Kind::Compute, 6, 0, "cs_6_0", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 1, "cs_6_1", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 2, "cs_6_2", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 3, "cs_6_3", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 4, "cs_6_4", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 5, "cs_6_5", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 6, "cs_6_6", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 7, "cs_6_7", 0, 0, true, true, UINT_MAX),
SM(Kind::Compute, 6, 8, "cs_6_8", 0, 0, true, true, UINT_MAX),
SM(Kind::Library, 6, 1, "lib_6_1", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 2, "lib_6_2", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 3, "lib_6_3", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 4, "lib_6_4", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 5, "lib_6_5", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 6, "lib_6_6", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 7, "lib_6_7", 32, 32, true, true, UINT_MAX),
SM(Kind::Library, 6, 8, "lib_6_8", 32, 32, true, true, UINT_MAX),
// lib_6_x is for offline linking only, and relaxes restrictions
SM(Kind::Library, 6, kOfflineMinor, "lib_6_x", 32, 32, true, true,
UINT_MAX),
SM(Kind::Mesh, 6, 5, "ms_6_5", 0, 0, true, true, UINT_MAX),
SM(Kind::Mesh, 6, 6, "ms_6_6", 0, 0, true, true, UINT_MAX),
SM(Kind::Mesh, 6, 7, "ms_6_7", 0, 0, true, true, UINT_MAX),
SM(Kind::Mesh, 6, 8, "ms_6_8", 0, 0, true, true, UINT_MAX),
SM(Kind::Amplification, 6, 5, "as_6_5", 0, 0, true, true, UINT_MAX),
SM(Kind::Amplification, 6, 6, "as_6_6", 0, 0, true, true, UINT_MAX),
SM(Kind::Amplification, 6, 7, "as_6_7", 0, 0, true, true, UINT_MAX),
SM(Kind::Amplification, 6, 8, "as_6_8", 0, 0, true, true, UINT_MAX),
// Values before Invalid must remain sorted by Kind, then Major, then Minor.
SM(Kind::Invalid, 0, 0, "invalid", 0, 0, false, false, 0),
// VALRULE-TEXT:END
};
static const char *NodeLaunchTypeNames[] = {"invalid", "broadcasting",
"coalescing", "thread"};
const char *ShaderModel::GetNodeLaunchTypeName(DXIL::NodeLaunchType launchTy) {
static_assert(static_cast<unsigned>(DXIL::NodeLaunchType::Thread) ==
_countof(NodeLaunchTypeNames) - 1,
"Invalid launch type or names");
return NodeLaunchTypeNames[static_cast<unsigned int>(launchTy)];
}
DXIL::NodeLaunchType ShaderModel::NodeLaunchTypeFromName(llvm::StringRef name) {
return llvm::StringSwitch<DXIL::NodeLaunchType>(name.lower())
.Case("broadcasting", DXIL::NodeLaunchType::Broadcasting)
.Case("coalescing", DXIL::NodeLaunchType::Coalescing)
.Case("thread", DXIL::NodeLaunchType::Thread)
.Default(DXIL::NodeLaunchType::Invalid);
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilTypeSystem.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilTypeSystem.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/WinFunctions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using std::map;
using std::string;
using std::unique_ptr;
using std::vector;
namespace hlsl {
//------------------------------------------------------------------------------
//
// DxilMatrixAnnotation class methods.
//
DxilMatrixAnnotation::DxilMatrixAnnotation()
: Rows(0), Cols(0), Orientation(MatrixOrientation::Undefined) {}
//------------------------------------------------------------------------------
//
// DxilFieldAnnotation class methods.
//
DxilFieldAnnotation::DxilFieldAnnotation()
: m_bPrecise(false), m_CBufferOffset(UINT_MAX), m_bCBufferVarUsed(false),
m_BitFieldWidth(0), m_VectorSize(0) {}
bool DxilFieldAnnotation::IsPrecise() const { return m_bPrecise; }
void DxilFieldAnnotation::SetPrecise(bool b) { m_bPrecise = b; }
bool DxilFieldAnnotation::HasMatrixAnnotation() const {
return m_Matrix.Cols != 0;
}
const DxilMatrixAnnotation &DxilFieldAnnotation::GetMatrixAnnotation() const {
return m_Matrix;
}
void DxilFieldAnnotation::SetMatrixAnnotation(const DxilMatrixAnnotation &MA) {
m_Matrix = MA;
}
unsigned DxilFieldAnnotation::GetVectorSize() const { return m_VectorSize; }
void DxilFieldAnnotation::SetVectorSize(unsigned size) { m_VectorSize = size; }
bool DxilFieldAnnotation::HasResourceProperties() const {
return m_ResourceProps.isValid();
}
const DxilResourceProperties &
DxilFieldAnnotation::GetResourceProperties() const {
return m_ResourceProps;
}
void DxilFieldAnnotation::SetResourceProperties(
const DxilResourceProperties &RP) {
m_ResourceProps = RP;
}
bool DxilFieldAnnotation::HasCBufferOffset() const {
return m_CBufferOffset != UINT_MAX;
}
unsigned DxilFieldAnnotation::GetCBufferOffset() const {
return m_CBufferOffset;
}
void DxilFieldAnnotation::SetCBufferOffset(unsigned Offset) {
m_CBufferOffset = Offset;
}
bool DxilFieldAnnotation::HasCompType() const {
return m_CompType.GetKind() != CompType::Kind::Invalid;
}
const CompType &DxilFieldAnnotation::GetCompType() const { return m_CompType; }
void DxilFieldAnnotation::SetCompType(CompType::Kind kind) {
m_CompType = CompType(kind);
}
bool DxilFieldAnnotation::HasSemanticString() const {
return !m_Semantic.empty();
}
const std::string &DxilFieldAnnotation::GetSemanticString() const {
return m_Semantic;
}
llvm::StringRef DxilFieldAnnotation::GetSemanticStringRef() const {
return llvm::StringRef(m_Semantic);
}
void DxilFieldAnnotation::SetSemanticString(const std::string &SemString) {
m_Semantic = SemString;
}
bool DxilFieldAnnotation::HasInterpolationMode() const {
return !m_InterpMode.IsUndefined();
}
const InterpolationMode &DxilFieldAnnotation::GetInterpolationMode() const {
return m_InterpMode;
}
void DxilFieldAnnotation::SetInterpolationMode(const InterpolationMode &IM) {
m_InterpMode = IM;
}
bool DxilFieldAnnotation::HasFieldName() const { return !m_FieldName.empty(); }
const std::string &DxilFieldAnnotation::GetFieldName() const {
return m_FieldName;
}
void DxilFieldAnnotation::SetFieldName(const std::string &FieldName) {
m_FieldName = FieldName;
}
bool DxilFieldAnnotation::IsCBVarUsed() const { return m_bCBufferVarUsed; }
void DxilFieldAnnotation::SetCBVarUsed(bool used) { m_bCBufferVarUsed = used; }
bool DxilFieldAnnotation::HasBitFields() const { return !m_BitFields.empty(); }
const std::vector<DxilFieldAnnotation> &
DxilFieldAnnotation::GetBitFields() const {
return m_BitFields;
}
void DxilFieldAnnotation::SetBitFields(
const std::vector<DxilFieldAnnotation> &Fields) {
m_BitFields = Fields;
}
bool DxilFieldAnnotation::HasBitFieldWidth() const {
return m_BitFieldWidth != 0;
}
unsigned DxilFieldAnnotation::GetBitFieldWidth() const {
return m_BitFieldWidth;
}
void DxilFieldAnnotation::SetBitFieldWidth(const unsigned BitWidth) {
m_BitFieldWidth = BitWidth;
}
//------------------------------------------------------------------------------
//
// DxilPayloadFieldAnnotation class methods.
//
bool DxilPayloadFieldAnnotation::HasCompType() const {
return m_CompType.GetKind() != CompType::Kind::Invalid;
}
const CompType &DxilPayloadFieldAnnotation::GetCompType() const {
return m_CompType;
}
void DxilPayloadFieldAnnotation::SetCompType(CompType::Kind kind) {
m_CompType = CompType(kind);
}
uint32_t DxilPayloadFieldAnnotation::GetPayloadFieldQualifierMask() const {
return m_bitmask;
}
unsigned DxilPayloadFieldAnnotation::GetBitOffsetForShaderStage(
DXIL::PayloadAccessShaderStage shaderStage) {
unsigned bitOffset = static_cast<unsigned>(shaderStage) *
DXIL::PayloadAccessQualifierBitsPerStage;
return bitOffset;
}
void DxilPayloadFieldAnnotation::SetPayloadFieldQualifierMask(
uint32_t fieldBitmask) {
DXASSERT((fieldBitmask & ~DXIL::PayloadAccessQualifierValidMask) == 0,
"Unknown payload access qualifier bits set");
m_bitmask = fieldBitmask & DXIL::PayloadAccessQualifierValidMask;
}
void DxilPayloadFieldAnnotation::AddPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage shaderStage,
DXIL::PayloadAccessQualifier qualifier) {
unsigned accessBits = static_cast<unsigned>(qualifier);
DXASSERT((accessBits & ~DXIL::PayloadAccessQualifierValidMaskPerStage) == 0,
"Unknown payload access qualifier bits set");
accessBits &= DXIL::PayloadAccessQualifierValidMaskPerStage;
accessBits <<= GetBitOffsetForShaderStage(shaderStage);
m_bitmask |= accessBits;
}
DXIL::PayloadAccessQualifier
DxilPayloadFieldAnnotation::GetPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage shaderStage) const {
int bitOffset = GetBitOffsetForShaderStage(shaderStage);
// default type is always ReadWrite
DXIL::PayloadAccessQualifier accessType =
DXIL::PayloadAccessQualifier::ReadWrite;
const unsigned readBit =
static_cast<unsigned>(DXIL::PayloadAccessQualifier::Read);
const unsigned writeBit =
static_cast<unsigned>(DXIL::PayloadAccessQualifier::Write);
unsigned accessBits = m_bitmask >> bitOffset;
if (accessBits & readBit) {
// set Read if the first bit is set
accessType = DXIL::PayloadAccessQualifier::Read;
}
if (accessBits & writeBit) {
// set Write only if the second bit set, if both are set set to ReadWrite
accessType = accessType == DXIL::PayloadAccessQualifier::ReadWrite
? DXIL::PayloadAccessQualifier::Write
: DXIL::PayloadAccessQualifier::ReadWrite;
}
return accessType;
}
bool DxilPayloadFieldAnnotation::HasAnnotations() const {
return m_bitmask != 0;
}
//------------------------------------------------------------------------------
//
// DxilStructAnnotation class methods.
//
DxilTemplateArgAnnotation::DxilTemplateArgAnnotation()
: m_Type(nullptr), m_Integral(0) {}
bool DxilTemplateArgAnnotation::IsType() const { return m_Type != nullptr; }
const llvm::Type *DxilTemplateArgAnnotation::GetType() const { return m_Type; }
void DxilTemplateArgAnnotation::SetType(const llvm::Type *pType) {
m_Type = pType;
}
bool DxilTemplateArgAnnotation::IsIntegral() const { return m_Type == nullptr; }
int64_t DxilTemplateArgAnnotation::GetIntegral() const { return m_Integral; }
void DxilTemplateArgAnnotation::SetIntegral(int64_t i64) {
m_Type = nullptr;
m_Integral = i64;
}
unsigned DxilStructAnnotation::GetNumFields() const {
return (unsigned)m_FieldAnnotations.size();
}
DxilFieldAnnotation &
DxilStructAnnotation::GetFieldAnnotation(unsigned FieldIdx) {
return m_FieldAnnotations[FieldIdx];
}
const DxilFieldAnnotation &
DxilStructAnnotation::GetFieldAnnotation(unsigned FieldIdx) const {
return m_FieldAnnotations[FieldIdx];
}
const StructType *DxilStructAnnotation::GetStructType() const {
return m_pStructType;
}
void DxilStructAnnotation::SetStructType(const llvm::StructType *Ty) {
m_pStructType = Ty;
}
unsigned DxilStructAnnotation::GetCBufferSize() const { return m_CBufferSize; }
void DxilStructAnnotation::SetCBufferSize(unsigned size) {
m_CBufferSize = size;
}
void DxilStructAnnotation::MarkEmptyStruct() {
if (m_ResourcesContained == HasResources::True)
m_ResourcesContained = HasResources::Only;
else
m_FieldAnnotations.clear();
}
bool DxilStructAnnotation::IsEmptyStruct() {
return m_FieldAnnotations.empty();
}
bool DxilStructAnnotation::IsEmptyBesidesResources() {
return m_ResourcesContained == HasResources::Only ||
m_FieldAnnotations.empty();
}
// ContainsResources is for codegen only, not meant for metadata
void DxilStructAnnotation::SetContainsResources() {
if (m_ResourcesContained == HasResources::False)
m_ResourcesContained = HasResources::True;
}
bool DxilStructAnnotation::ContainsResources() const {
return m_ResourcesContained != HasResources::False;
}
// For template args, GetNumTemplateArgs() will return 0 if not a template
unsigned DxilStructAnnotation::GetNumTemplateArgs() const {
return (unsigned)m_TemplateAnnotations.size();
}
void DxilStructAnnotation::SetNumTemplateArgs(unsigned count) {
DXASSERT(m_TemplateAnnotations.empty(), "template args already initialized");
m_TemplateAnnotations.resize(count);
}
DxilTemplateArgAnnotation &
DxilStructAnnotation::GetTemplateArgAnnotation(unsigned argIdx) {
return m_TemplateAnnotations[argIdx];
}
const DxilTemplateArgAnnotation &
DxilStructAnnotation::GetTemplateArgAnnotation(unsigned argIdx) const {
return m_TemplateAnnotations[argIdx];
}
//------------------------------------------------------------------------------
//
// DxilParameterAnnotation class methods.
//
DxilParameterAnnotation::DxilParameterAnnotation()
: DxilFieldAnnotation(), m_inputQual(DxilParamInputQual::In) {}
DxilParamInputQual DxilParameterAnnotation::GetParamInputQual() const {
return m_inputQual;
}
void DxilParameterAnnotation::SetParamInputQual(DxilParamInputQual qual) {
m_inputQual = qual;
}
const std::vector<unsigned> &
DxilParameterAnnotation::GetSemanticIndexVec() const {
return m_semanticIndex;
}
void DxilParameterAnnotation::SetSemanticIndexVec(
const std::vector<unsigned> &Vec) {
m_semanticIndex = Vec;
}
void DxilParameterAnnotation::AppendSemanticIndex(unsigned SemIdx) {
m_semanticIndex.emplace_back(SemIdx);
}
bool DxilParameterAnnotation::IsParamInputQualNode() {
return (m_inputQual == DxilParamInputQual::NodeIO);
}
//------------------------------------------------------------------------------
//
// DxilFunctionAnnotation class methods.
//
unsigned DxilFunctionAnnotation::GetNumParameters() const {
return (unsigned)m_parameterAnnotations.size();
}
DxilParameterAnnotation &
DxilFunctionAnnotation::GetParameterAnnotation(unsigned ParamIdx) {
return m_parameterAnnotations[ParamIdx];
}
const DxilParameterAnnotation &
DxilFunctionAnnotation::GetParameterAnnotation(unsigned ParamIdx) const {
return m_parameterAnnotations[ParamIdx];
}
DxilParameterAnnotation &DxilFunctionAnnotation::GetRetTypeAnnotation() {
return m_retTypeAnnotation;
}
const DxilParameterAnnotation &
DxilFunctionAnnotation::GetRetTypeAnnotation() const {
return m_retTypeAnnotation;
}
const Function *DxilFunctionAnnotation::GetFunction() const {
return m_pFunction;
}
//------------------------------------------------------------------------------
//
// DxilPayloadAnnotation class methods.
//
unsigned DxilPayloadAnnotation::GetNumFields() const {
return (unsigned)m_FieldAnnotations.size();
}
DxilPayloadFieldAnnotation &
DxilPayloadAnnotation::GetFieldAnnotation(unsigned FieldIdx) {
return m_FieldAnnotations[FieldIdx];
}
const DxilPayloadFieldAnnotation &
DxilPayloadAnnotation::GetFieldAnnotation(unsigned FieldIdx) const {
return m_FieldAnnotations[FieldIdx];
}
const StructType *DxilPayloadAnnotation::GetStructType() const {
return m_pStructType;
}
void DxilPayloadAnnotation::SetStructType(const llvm::StructType *Ty) {
m_pStructType = Ty;
}
//------------------------------------------------------------------------------
//
// DxilTypeSystem class methods.
//
DxilTypeSystem::DxilTypeSystem(Module *pModule)
: m_pModule(pModule),
m_LowPrecisionMode(DXIL::LowPrecisionMode::Undefined) {}
DxilStructAnnotation *
DxilTypeSystem::AddStructAnnotation(const StructType *pStructType,
unsigned numTemplateArgs) {
DXASSERT_NOMSG(m_StructAnnotations.find(pStructType) ==
m_StructAnnotations.end());
DxilStructAnnotation *pA = new DxilStructAnnotation();
m_StructAnnotations[pStructType] = unique_ptr<DxilStructAnnotation>(pA);
pA->m_pStructType = pStructType;
pA->m_FieldAnnotations.resize(pStructType->getNumElements());
pA->SetNumTemplateArgs(numTemplateArgs);
return pA;
}
void DxilTypeSystem::FinishStructAnnotation(DxilStructAnnotation &SA) {
const llvm::StructType *ST = SA.GetStructType();
DXASSERT(SA.GetNumFields() == ST->getNumElements(),
"otherwise, mismatched field count.");
// Update resource containment
for (unsigned i = 0; i < SA.GetNumFields() && !SA.ContainsResources(); i++) {
if (IsResourceContained(ST->getElementType(i)))
SA.SetContainsResources();
}
// Mark if empty
if (SA.GetCBufferSize() == 0)
SA.MarkEmptyStruct();
}
DxilStructAnnotation *
DxilTypeSystem::GetStructAnnotation(const StructType *pStructType) {
auto it = m_StructAnnotations.find(pStructType);
if (it != m_StructAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
const DxilStructAnnotation *
DxilTypeSystem::GetStructAnnotation(const StructType *pStructType) const {
auto it = m_StructAnnotations.find(pStructType);
if (it != m_StructAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
void DxilTypeSystem::EraseStructAnnotation(const StructType *pStructType) {
DXASSERT_NOMSG(m_StructAnnotations.count(pStructType));
m_StructAnnotations.remove_if(
[pStructType](const std::pair<const StructType *,
std::unique_ptr<DxilStructAnnotation>> &I) {
return pStructType == I.first;
});
}
// Recurse type, removing any found StructType from the set
static void RemoveUsedStructsFromSet(
Type *Ty, std::unordered_set<const llvm::StructType *> &unused_structs) {
if (Ty->isPointerTy())
RemoveUsedStructsFromSet(Ty->getPointerElementType(), unused_structs);
else if (Ty->isArrayTy())
RemoveUsedStructsFromSet(Ty->getArrayElementType(), unused_structs);
else if (Ty->isStructTy()) {
StructType *ST = cast<StructType>(Ty);
// Only recurse first time into this struct
if (unused_structs.erase(ST)) {
for (auto &ET : ST->elements()) {
RemoveUsedStructsFromSet(ET, unused_structs);
}
}
}
}
void DxilTypeSystem::EraseUnusedStructAnnotations() {
// Add all structures with annotations to a set
// Iterate globals, resource types, and functions, recursing used structures
// to remove matching struct annotations from set
std::unordered_set<const llvm::StructType *> unused_structs;
for (auto &it : m_StructAnnotations) {
unused_structs.insert(it.first);
}
for (auto &GV : m_pModule->globals()) {
RemoveUsedStructsFromSet(GV.getType(), unused_structs);
}
DxilModule &DM = m_pModule->GetDxilModule();
for (auto &&C : DM.GetCBuffers()) {
RemoveUsedStructsFromSet(C->GetHLSLType(), unused_structs);
}
for (auto &&Srv : DM.GetSRVs()) {
RemoveUsedStructsFromSet(Srv->GetHLSLType(), unused_structs);
}
for (auto &&Uav : DM.GetUAVs()) {
RemoveUsedStructsFromSet(Uav->GetHLSLType(), unused_structs);
}
for (auto &F : m_pModule->functions()) {
FunctionType *FT = F.getFunctionType();
RemoveUsedStructsFromSet(FT->getReturnType(), unused_structs);
for (auto &argTy : FT->params()) {
RemoveUsedStructsFromSet(argTy, unused_structs);
}
}
// erase remaining structures in set
for (auto *ST : unused_structs) {
EraseStructAnnotation(ST);
}
}
DxilTypeSystem::StructAnnotationMap &DxilTypeSystem::GetStructAnnotationMap() {
return m_StructAnnotations;
}
const DxilTypeSystem::StructAnnotationMap &
DxilTypeSystem::GetStructAnnotationMap() const {
return m_StructAnnotations;
}
DxilPayloadAnnotation *
DxilTypeSystem::AddPayloadAnnotation(const StructType *pStructType) {
DXASSERT_NOMSG(m_PayloadAnnotations.find(pStructType) ==
m_PayloadAnnotations.end());
DxilPayloadAnnotation *pA = new DxilPayloadAnnotation();
m_PayloadAnnotations[pStructType] = unique_ptr<DxilPayloadAnnotation>(pA);
pA->m_pStructType = pStructType;
pA->m_FieldAnnotations.resize(pStructType->getNumElements());
return pA;
}
DxilPayloadAnnotation *
DxilTypeSystem::GetPayloadAnnotation(const StructType *pStructType) {
auto it = m_PayloadAnnotations.find(pStructType);
if (it != m_PayloadAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
const DxilPayloadAnnotation *
DxilTypeSystem::GetPayloadAnnotation(const StructType *pStructType) const {
auto it = m_PayloadAnnotations.find(pStructType);
if (it != m_PayloadAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
void DxilTypeSystem::ErasePayloadAnnotation(const StructType *pStructType) {
DXASSERT_NOMSG(m_StructAnnotations.count(pStructType));
m_PayloadAnnotations.remove_if(
[pStructType](
const std::pair<const StructType *,
std::unique_ptr<DxilPayloadAnnotation>> &I) {
return pStructType == I.first;
});
}
DxilTypeSystem::PayloadAnnotationMap &
DxilTypeSystem::GetPayloadAnnotationMap() {
return m_PayloadAnnotations;
}
const DxilTypeSystem::PayloadAnnotationMap &
DxilTypeSystem::GetPayloadAnnotationMap() const {
return m_PayloadAnnotations;
}
DxilFunctionAnnotation *
DxilTypeSystem::AddFunctionAnnotation(const Function *pFunction) {
DXASSERT_NOMSG(m_FunctionAnnotations.find(pFunction) ==
m_FunctionAnnotations.end());
DxilFunctionAnnotation *pA = new DxilFunctionAnnotation();
m_FunctionAnnotations[pFunction] = unique_ptr<DxilFunctionAnnotation>(pA);
pA->m_pFunction = pFunction;
pA->m_parameterAnnotations.resize(
pFunction->getFunctionType()->getNumParams());
return pA;
}
void DxilTypeSystem::FinishFunctionAnnotation(DxilFunctionAnnotation &FA) {
auto FT = FA.GetFunction()->getFunctionType();
// Update resource containment
if (IsResourceContained(FT->getReturnType()))
FA.SetContainsResourceArgs();
for (unsigned i = 0; i < FT->getNumParams() && !FA.ContainsResourceArgs();
i++) {
if (IsResourceContained(FT->getParamType(i)))
FA.SetContainsResourceArgs();
}
}
DxilFunctionAnnotation *
DxilTypeSystem::GetFunctionAnnotation(const Function *pFunction) {
auto it = m_FunctionAnnotations.find(pFunction);
if (it != m_FunctionAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
const DxilFunctionAnnotation *
DxilTypeSystem::GetFunctionAnnotation(const Function *pFunction) const {
auto it = m_FunctionAnnotations.find(pFunction);
if (it != m_FunctionAnnotations.end()) {
return it->second.get();
} else {
return nullptr;
}
}
void DxilTypeSystem::EraseFunctionAnnotation(const Function *pFunction) {
DXASSERT_NOMSG(m_FunctionAnnotations.count(pFunction));
m_FunctionAnnotations.remove_if(
[pFunction](const std::pair<const Function *,
std::unique_ptr<DxilFunctionAnnotation>> &I) {
return pFunction == I.first;
});
}
DxilTypeSystem::FunctionAnnotationMap &
DxilTypeSystem::GetFunctionAnnotationMap() {
return m_FunctionAnnotations;
}
StructType *DxilTypeSystem::GetSNormF32Type(unsigned NumComps) {
return GetNormFloatType(CompType::getSNormF32(), NumComps);
}
StructType *DxilTypeSystem::GetUNormF32Type(unsigned NumComps) {
return GetNormFloatType(CompType::getUNormF32(), NumComps);
}
StructType *DxilTypeSystem::GetNormFloatType(CompType CT, unsigned NumComps) {
Type *pCompType = CT.GetLLVMType(m_pModule->getContext());
DXASSERT_NOMSG(pCompType->isFloatTy());
Type *pFieldType = pCompType;
string TypeName;
raw_string_ostream NameStream(TypeName);
if (NumComps > 1) {
(NameStream << "dx.types." << NumComps << "x" << CT.GetName()).flush();
pFieldType = FixedVectorType::get(pFieldType, NumComps);
} else {
(NameStream << "dx.types." << CT.GetName()).flush();
}
StructType *pStructType = m_pModule->getTypeByName(TypeName);
if (pStructType == nullptr) {
pStructType =
StructType::create(m_pModule->getContext(), pFieldType, TypeName);
DxilStructAnnotation &TA = *AddStructAnnotation(pStructType);
DxilFieldAnnotation &FA = TA.GetFieldAnnotation(0);
FA.SetCompType(CT.GetKind());
DXASSERT_NOMSG(CT.IsSNorm() || CT.IsUNorm());
}
return pStructType;
}
void DxilTypeSystem::CopyTypeAnnotation(const llvm::Type *Ty,
const DxilTypeSystem &src) {
if (isa<PointerType>(Ty))
Ty = Ty->getPointerElementType();
while (isa<ArrayType>(Ty))
Ty = Ty->getArrayElementType();
// Only struct type has annotation.
if (!isa<StructType>(Ty))
return;
const StructType *ST = cast<StructType>(Ty);
// Already exist.
if (GetStructAnnotation(ST))
return;
if (const DxilStructAnnotation *annot = src.GetStructAnnotation(ST)) {
DxilStructAnnotation *dstAnnot = AddStructAnnotation(ST);
// Copy the annotation.
*dstAnnot = *annot;
// Copy field type annotations.
for (Type *Ty : ST->elements()) {
CopyTypeAnnotation(Ty, src);
}
}
}
void DxilTypeSystem::CopyFunctionAnnotation(const llvm::Function *pDstFunction,
const llvm::Function *pSrcFunction,
const DxilTypeSystem &src) {
const DxilFunctionAnnotation *annot = src.GetFunctionAnnotation(pSrcFunction);
// Don't have annotation.
if (!annot)
return;
// Already exist.
if (GetFunctionAnnotation(pDstFunction))
return;
DxilFunctionAnnotation *dstAnnot = AddFunctionAnnotation(pDstFunction);
// Copy the annotation.
*dstAnnot = *annot;
dstAnnot->m_pFunction = pDstFunction;
// Clone ret type annotation.
CopyTypeAnnotation(pDstFunction->getReturnType(), src);
// Clone param type annotations.
for (const Argument &arg : pDstFunction->args()) {
CopyTypeAnnotation(arg.getType(), src);
}
}
DXIL::SigPointKind SigPointFromInputQual(DxilParamInputQual Q,
DXIL::ShaderKind SK, bool isPC) {
DXASSERT(Q != DxilParamInputQual::Inout,
"Inout not expected for SigPointFromInputQual");
switch (SK) {
case DXIL::ShaderKind::Vertex:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::VSIn;
case DxilParamInputQual::Out:
return DXIL::SigPointKind::VSOut;
default:
break;
}
break;
case DXIL::ShaderKind::Hull:
switch (Q) {
case DxilParamInputQual::In:
if (isPC)
return DXIL::SigPointKind::PCIn;
else
return DXIL::SigPointKind::HSIn;
case DxilParamInputQual::Out:
if (isPC)
return DXIL::SigPointKind::PCOut;
else
return DXIL::SigPointKind::HSCPOut;
case DxilParamInputQual::InputPatch:
return DXIL::SigPointKind::HSCPIn;
case DxilParamInputQual::OutputPatch:
return DXIL::SigPointKind::HSCPOut;
default:
break;
}
break;
case DXIL::ShaderKind::Domain:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::DSIn;
case DxilParamInputQual::Out:
return DXIL::SigPointKind::DSOut;
case DxilParamInputQual::InputPatch:
case DxilParamInputQual::OutputPatch:
return DXIL::SigPointKind::DSCPIn;
default:
break;
}
break;
case DXIL::ShaderKind::Geometry:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::GSIn;
case DxilParamInputQual::InputPrimitive:
return DXIL::SigPointKind::GSVIn;
case DxilParamInputQual::OutStream0:
case DxilParamInputQual::OutStream1:
case DxilParamInputQual::OutStream2:
case DxilParamInputQual::OutStream3:
return DXIL::SigPointKind::GSOut;
default:
break;
}
break;
case DXIL::ShaderKind::Pixel:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::PSIn;
case DxilParamInputQual::Out:
return DXIL::SigPointKind::PSOut;
default:
break;
}
break;
case DXIL::ShaderKind::Compute:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::CSIn;
default:
break;
}
break;
case DXIL::ShaderKind::Mesh:
switch (Q) {
case DxilParamInputQual::In:
case DxilParamInputQual::InPayload:
return DXIL::SigPointKind::MSIn;
case DxilParamInputQual::OutIndices:
case DxilParamInputQual::OutVertices:
return DXIL::SigPointKind::MSOut;
case DxilParamInputQual::OutPrimitives:
return DXIL::SigPointKind::MSPOut;
default:
break;
}
break;
case DXIL::ShaderKind::Amplification:
switch (Q) {
case DxilParamInputQual::In:
return DXIL::SigPointKind::ASIn;
default:
break;
}
break;
default:
break;
}
return DXIL::SigPointKind::Invalid;
}
void RemapSemantic(llvm::StringRef &oldSemName, llvm::StringRef &oldSemFullName,
const char *newSemName, DxilParameterAnnotation ¶mInfo,
llvm::LLVMContext &Context) {
// format deprecation warning
dxilutil::EmitWarningOnContext(
Context, Twine("DX9-style semantic \"") + oldSemName +
Twine("\" mapped to DX10 system semantic \"") + newSemName +
Twine("\" due to -Gec flag. This functionality is "
"deprecated in newer language versions."));
// create new semantic name with the same index
std::string newSemNameStr(newSemName);
unsigned indexLen = oldSemFullName.size() - oldSemName.size();
if (indexLen > 0) {
newSemNameStr = newSemNameStr.append(
oldSemFullName.data() + oldSemName.size(), indexLen);
}
paramInfo.SetSemanticString(newSemNameStr);
}
void RemapObsoleteSemantic(DxilParameterAnnotation ¶mInfo,
DXIL::SigPointKind sigPoint,
llvm::LLVMContext &Context) {
DXASSERT(paramInfo.HasSemanticString(), "expected paramInfo with semantic");
//*ppWarningMsg = nullptr;
llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
llvm::StringRef semName;
unsigned semIndex;
Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
if (sigPoint == DXIL::SigPointKind::PSOut) {
if (semName.size() == 5) {
if (_strnicmp(semName.data(), "COLOR", 5) == 0) {
RemapSemantic(semName, semFullName, "SV_Target", paramInfo, Context);
} else if (_strnicmp(semName.data(), "DEPTH", 5) == 0) {
RemapSemantic(semName, semFullName, "SV_Depth", paramInfo, Context);
}
}
} else if ((sigPoint == DXIL::SigPointKind::VSOut && semName.size() == 8 &&
_strnicmp(semName.data(), "POSITION", 8) == 0) ||
(sigPoint == DXIL::SigPointKind::PSIn && semName.size() == 4 &&
_strnicmp(semName.data(), "VPOS", 4) == 0)) {
RemapSemantic(semName, semFullName, "SV_Position", paramInfo, Context);
}
}
bool DxilTypeSystem::UseMinPrecision() {
return m_LowPrecisionMode == DXIL::LowPrecisionMode::UseMinPrecision;
}
void DxilTypeSystem::SetMinPrecision(bool bMinPrecision) {
DXIL::LowPrecisionMode mode =
bMinPrecision ? DXIL::LowPrecisionMode::UseMinPrecision
: DXIL::LowPrecisionMode::UseNativeLowPrecision;
DXASSERT((mode == m_LowPrecisionMode ||
m_LowPrecisionMode == DXIL::LowPrecisionMode::Undefined),
"LowPrecisionMode should only be set once.");
m_LowPrecisionMode = mode;
}
bool DxilTypeSystem::IsResourceContained(llvm::Type *Ty) {
// strip pointer/array
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
if (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
if (auto ST = dyn_cast<StructType>(Ty)) {
if (dxilutil::IsHLSLResourceType(Ty)) {
return true;
} else if (auto SA = GetStructAnnotation(ST)) {
if (SA->ContainsResources())
return true;
}
}
return false;
}
DxilStructTypeIterator::DxilStructTypeIterator(
llvm::StructType *sTy, DxilStructAnnotation *sAnnotation, unsigned idx)
: STy(sTy), SAnnotation(sAnnotation), index(idx) {
DXASSERT(
sTy->getNumElements() == sAnnotation->GetNumFields(),
"Otherwise the pairing of annotation and struct type does not match.");
}
// prefix
DxilStructTypeIterator &DxilStructTypeIterator::operator++() {
index++;
return *this;
}
// postfix
DxilStructTypeIterator DxilStructTypeIterator::operator++(int) {
DxilStructTypeIterator iter(STy, SAnnotation, index);
index++;
return iter;
}
bool DxilStructTypeIterator::operator==(DxilStructTypeIterator iter) {
return iter.STy == STy && iter.SAnnotation == SAnnotation &&
iter.index == index;
}
bool DxilStructTypeIterator::operator!=(DxilStructTypeIterator iter) {
return !(operator==(iter));
}
std::pair<llvm::Type *, DxilFieldAnnotation *>
DxilStructTypeIterator::operator*() {
return std::pair<llvm::Type *, DxilFieldAnnotation *>(
STy->getElementType(index), &SAnnotation->GetFieldAnnotation(index));
}
DxilStructTypeIterator begin(llvm::StructType *STy,
DxilStructAnnotation *SAnno) {
return {STy, SAnno, 0};
}
DxilStructTypeIterator end(llvm::StructType *STy, DxilStructAnnotation *SAnno) {
return {STy, SAnno, STy->getNumElements()};
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilModuleHelper.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilModuleHelper.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilCounters.h"
#include "dxc/DXIL/DxilEntryProps.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilSignatureElement.h"
#include "dxc/DXIL/DxilSubobject.h"
#include "dxc/Support/Global.h"
#include "dxc/WinAdapter.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/raw_ostream.h"
#include <unordered_set>
#ifndef _WIN32
using llvm::make_unique;
#else
using std::make_unique;
#endif
using namespace llvm;
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
class DxilErrorDiagnosticInfo : public DiagnosticInfo {
private:
const char *m_message;
public:
DxilErrorDiagnosticInfo(const char *str)
: DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
m_message(str) {}
void print(DiagnosticPrinter &DP) const override { DP << m_message; }
};
} // namespace
namespace hlsl {
// Avoid dependency on DxilModule from llvm::Module using this:
void DxilModule_RemoveGlobal(llvm::Module *M, llvm::GlobalObject *G) {
if (M && G && M->HasDxilModule()) {
if (llvm::Function *F = dyn_cast<llvm::Function>(G))
M->GetDxilModule().RemoveFunction(F);
}
}
void DxilModule_ResetModule(llvm::Module *M) {
if (M && M->HasDxilModule())
delete &M->GetDxilModule();
M->SetDxilModule(nullptr);
}
void SetDxilHook(Module &M) {
M.pfnRemoveGlobal = &DxilModule_RemoveGlobal;
M.pfnResetDxilModule = &DxilModule_ResetModule;
}
void ClearDxilHook(Module &M) {
if (M.pfnRemoveGlobal == &DxilModule_RemoveGlobal)
M.pfnRemoveGlobal = nullptr;
}
hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
LLVMContext &Ctx = pModule->getContext();
std::string diagStr;
raw_string_ostream diagStream(diagStr);
hlsl::DxilModule *pDxilModule = nullptr;
// TODO: add detail error in DxilMDHelper.
try {
pDxilModule = &pModule->GetOrCreateDxilModule();
} catch (const ::hlsl::Exception &hlslException) {
diagStream << "load dxil metadata failed -";
try {
const char *msg = hlslException.what();
if (msg == nullptr || *msg == '\0')
diagStream << " error code " << hlslException.hr << "\n";
else
diagStream << msg;
} catch (...) {
diagStream << " unable to retrieve error message.\n";
}
Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
} catch (...) {
Ctx.diagnose(DxilErrorDiagnosticInfo(
"load dxil metadata failed - unknown error.\n"));
}
return pDxilModule;
}
} // namespace hlsl
namespace llvm {
hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
std::unique_ptr<hlsl::DxilModule> M;
if (!HasDxilModule()) {
M = make_unique<hlsl::DxilModule>(this);
if (!skipInit) {
M->LoadDxilMetadata();
}
SetDxilModule(M.release());
}
return GetDxilModule();
}
} // namespace llvm
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilSemantic.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilSemantic.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilSemantic.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilSigPoint.h"
#include "dxc/DXIL/DxilSignature.h"
#include "dxc/Support/Global.h"
#include <string>
using std::string;
namespace hlsl {
//------------------------------------------------------------------------------
//
// Semantic class methods.
//
Semantic::Semantic(Kind Kind, const char *pszName)
: m_Kind(Kind), m_pszName(pszName) {}
const Semantic *Semantic::GetByName(llvm::StringRef name) {
if (!HasSVPrefix(name))
return GetArbitrary();
// The search is a simple linear scan as it is fairly infrequent operation and
// the list is short. The search can be improved if linear traversal has
// inadequate performance.
for (unsigned i = (unsigned)Kind::Arbitrary + 1; i < (unsigned)Kind::Invalid;
i++) {
if (name.compare_lower(ms_SemanticTable[i].m_pszName) == 0)
return &ms_SemanticTable[i];
}
return GetInvalid();
}
const Semantic *Semantic::GetByName(llvm::StringRef Name,
DXIL::SigPointKind sigPointKind,
unsigned MajorVersion,
unsigned MinorVersion) {
return Get(GetByName(Name)->GetKind(), sigPointKind, MajorVersion,
MinorVersion);
}
const Semantic *Semantic::Get(Kind kind) {
if (kind < Kind::Invalid)
return &Semantic::ms_SemanticTable[(unsigned)kind];
return GetInvalid();
}
const Semantic *Semantic::Get(Kind kind, DXIL::SigPointKind sigPointKind,
unsigned MajorVersion, unsigned MinorVersion) {
if (sigPointKind == DXIL::SigPointKind::Invalid)
return GetInvalid();
const Semantic *pSemantic = Get(kind);
DXIL::SemanticInterpretationKind SI = SigPoint::GetInterpretation(
pSemantic->GetKind(), sigPointKind, MajorVersion, MinorVersion);
if (SI == DXIL::SemanticInterpretationKind::NA)
return GetInvalid();
if (SI == DXIL::SemanticInterpretationKind::Arb)
return GetArbitrary();
return pSemantic;
}
const Semantic *Semantic::GetInvalid() {
return &Semantic::ms_SemanticTable[(unsigned)Kind::Invalid];
}
const Semantic *Semantic::GetArbitrary() {
return &Semantic::ms_SemanticTable[(unsigned)Kind::Arbitrary];
}
bool Semantic::HasSVPrefix(llvm::StringRef Name) {
return Name.size() >= 3 && (Name[0] == 'S' || Name[0] == 's') &&
(Name[1] == 'V' || Name[1] == 'v') && Name[2] == '_';
}
void Semantic::DecomposeNameAndIndex(llvm::StringRef FullName,
llvm::StringRef *pName, unsigned *pIndex) {
unsigned L = FullName.size(), i;
for (i = L; i > 0; i--) {
char d = FullName[i - 1];
if ('0' > d || d > '9')
break;
}
*pName = FullName.substr(0, i);
if (i < L)
*pIndex = atoi(FullName.data() + i);
else
*pIndex = 0;
}
Semantic::Kind Semantic::GetKind() const { return m_Kind; }
const char *Semantic::GetName() const { return m_pszName; }
bool Semantic::IsArbitrary() const { return GetKind() == Kind::Arbitrary; }
bool Semantic::IsInvalid() const { return m_Kind == Kind::Invalid; }
typedef Semantic SP;
const Semantic Semantic::ms_SemanticTable[kNumSemanticRecords] = {
// Kind Name
SP(Kind::Arbitrary, nullptr),
SP(Kind::VertexID, "SV_VertexID"),
SP(Kind::InstanceID, "SV_InstanceID"),
SP(Kind::Position, "SV_Position"),
SP(Kind::RenderTargetArrayIndex, "SV_RenderTargetArrayIndex"),
SP(Kind::ViewPortArrayIndex, "SV_ViewportArrayIndex"),
SP(Kind::ClipDistance, "SV_ClipDistance"),
SP(Kind::CullDistance, "SV_CullDistance"),
SP(Kind::OutputControlPointID, "SV_OutputControlPointID"),
SP(Kind::DomainLocation, "SV_DomainLocation"),
SP(Kind::PrimitiveID, "SV_PrimitiveID"),
SP(Kind::GSInstanceID, "SV_GSInstanceID"),
SP(Kind::SampleIndex, "SV_SampleIndex"),
SP(Kind::IsFrontFace, "SV_IsFrontFace"),
SP(Kind::Coverage, "SV_Coverage"),
SP(Kind::InnerCoverage, "SV_InnerCoverage"),
SP(Kind::Target, "SV_Target"),
SP(Kind::Depth, "SV_Depth"),
SP(Kind::DepthLessEqual, "SV_DepthLessEqual"),
SP(Kind::DepthGreaterEqual, "SV_DepthGreaterEqual"),
SP(Kind::StencilRef, "SV_StencilRef"),
SP(Kind::DispatchThreadID, "SV_DispatchThreadID"),
SP(Kind::GroupID, "SV_GroupID"),
SP(Kind::GroupIndex, "SV_GroupIndex"),
SP(Kind::GroupThreadID, "SV_GroupThreadID"),
SP(Kind::TessFactor, "SV_TessFactor"),
SP(Kind::InsideTessFactor, "SV_InsideTessFactor"),
SP(Kind::ViewID, "SV_ViewID"),
SP(Kind::Barycentrics, "SV_Barycentrics"),
SP(Kind::ShadingRate, "SV_ShadingRate"),
SP(Kind::CullPrimitive, "SV_CullPrimitive"),
SP(Kind::StartVertexLocation, "SV_StartVertexLocation"),
SP(Kind::StartInstanceLocation, "SV_StartInstanceLocation"),
SP(Kind::Invalid, nullptr),
};
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilCBuffer.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilCBuffer.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilCBuffer.h"
#include "dxc/Support/Global.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// DxilCBuffer methods.
//
DxilCBuffer::DxilCBuffer()
: DxilResourceBase(DxilResourceBase::Class::CBuffer), m_SizeInBytes(0) {
SetKind(DxilResourceBase::Kind::CBuffer);
}
DxilCBuffer::~DxilCBuffer() {}
unsigned DxilCBuffer::GetSize() const { return m_SizeInBytes; }
void DxilCBuffer::SetSize(unsigned InstanceSizeInBytes) {
m_SizeInBytes = InstanceSizeInBytes;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilSignature.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilSignature.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilSignature.h"
#include "dxc/DXIL/DxilSigPoint.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/STLExtras.h"
using std::unique_ptr;
using std::vector;
namespace hlsl {
//------------------------------------------------------------------------------
//
// Singnature methods.
//
DxilSignature::DxilSignature(DXIL::ShaderKind shaderKind,
DXIL::SignatureKind sigKind, bool useMinPrecision)
: m_sigPointKind(SigPoint::GetKind(shaderKind, sigKind,
/*isPatchConstantFunction*/ false,
/*isSpecialInput*/ false)),
m_UseMinPrecision(useMinPrecision) {}
DxilSignature::DxilSignature(DXIL::SigPointKind sigPointKind,
bool useMinPrecision)
: m_sigPointKind(sigPointKind), m_UseMinPrecision(useMinPrecision) {}
DxilSignature::DxilSignature(const DxilSignature &src)
: m_sigPointKind(src.m_sigPointKind),
m_UseMinPrecision(src.m_UseMinPrecision) {
const bool bSetID = false;
for (auto &Elt : src.GetElements()) {
std::unique_ptr<DxilSignatureElement> newElt = CreateElement();
newElt->Initialize(Elt->GetName(), Elt->GetCompType(),
Elt->GetInterpolationMode()->GetKind(), Elt->GetRows(),
Elt->GetCols(), Elt->GetStartRow(), Elt->GetStartCol(),
Elt->GetID(), Elt->GetSemanticIndexVec());
AppendElement(std::move(newElt), bSetID);
}
}
DxilSignature::~DxilSignature() {}
bool DxilSignature::IsInput() const {
return SigPoint::GetSigPoint(m_sigPointKind)->IsInput();
}
bool DxilSignature::IsOutput() const {
return SigPoint::GetSigPoint(m_sigPointKind)->IsOutput();
}
unique_ptr<DxilSignatureElement> DxilSignature::CreateElement() {
return std::make_unique<DxilSignatureElement>(m_sigPointKind);
}
unsigned DxilSignature::AppendElement(std::unique_ptr<DxilSignatureElement> pSE,
bool bSetID) {
DXASSERT_NOMSG((unsigned)m_Elements.size() < UINT_MAX);
unsigned Id = (unsigned)m_Elements.size();
if (bSetID) {
pSE->SetID(Id);
}
m_Elements.emplace_back(std::move(pSE));
return Id;
}
DxilSignatureElement &DxilSignature::GetElement(unsigned idx) {
return *m_Elements[idx];
}
const DxilSignatureElement &DxilSignature::GetElement(unsigned idx) const {
return *m_Elements[idx];
}
const std::vector<std::unique_ptr<DxilSignatureElement>> &
DxilSignature::GetElements() const {
return m_Elements;
}
bool DxilSignature::ShouldBeAllocated(DXIL::SemanticInterpretationKind Kind) {
switch (Kind) {
case DXIL::SemanticInterpretationKind::NA:
case DXIL::SemanticInterpretationKind::NotInSig:
case DXIL::SemanticInterpretationKind::NotPacked:
case DXIL::SemanticInterpretationKind::Shadow:
return false;
default:
break;
}
return true;
}
bool DxilSignature::IsFullyAllocated() const {
for (auto &SE : m_Elements) {
if (!ShouldBeAllocated(SE.get()->GetInterpretation()))
continue;
if (!SE->IsAllocated())
return false;
}
return true;
}
unsigned DxilSignature::NumVectorsUsed(unsigned streamIndex) const {
unsigned NumVectors = 0;
for (auto &SE : m_Elements) {
if (SE->IsAllocated() && SE->GetOutputStream() == streamIndex)
NumVectors =
std::max(NumVectors, (unsigned)SE->GetStartRow() + SE->GetRows());
}
return NumVectors;
}
unsigned DxilSignature::GetRowCount() const {
unsigned maxRow = 0;
for (auto &E : GetElements()) {
unsigned endRow = E->GetStartRow() + E->GetRows();
if (maxRow < endRow) {
maxRow = endRow;
}
}
return maxRow;
}
//------------------------------------------------------------------------------
//
// EntrySingnature methods.
//
DxilEntrySignature::DxilEntrySignature(const DxilEntrySignature &src)
: InputSignature(src.InputSignature), OutputSignature(src.OutputSignature),
PatchConstOrPrimSignature(src.PatchConstOrPrimSignature) {}
} // namespace hlsl
#include "dxc/DXIL/DxilSigPoint.inl"
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilSubobject.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilSubobject.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilSubobject.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/WinIncludes.h"
#include "llvm/ADT/STLExtras.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// Subobject methods.
//
DxilSubobject::DxilSubobject(DxilSubobject &&other)
: m_Owner(other.m_Owner), m_Kind(other.m_Kind),
m_Name(m_Owner.InternString(other.m_Name)),
m_Exports(std::move(other.m_Exports)) {
DXASSERT_NOMSG(DXIL::IsValidSubobjectKind(m_Kind));
CopyUnionedContents(other);
}
DxilSubobject::DxilSubobject(DxilSubobjects &owner, Kind kind,
llvm::StringRef name)
: m_Owner(owner), m_Kind(kind), m_Name(m_Owner.InternString(name)),
m_Exports() {
DXASSERT_NOMSG(DXIL::IsValidSubobjectKind(m_Kind));
}
DxilSubobject::DxilSubobject(DxilSubobjects &owner, const DxilSubobject &other,
llvm::StringRef name)
: m_Owner(owner), m_Kind(other.m_Kind), m_Name(name),
m_Exports(other.m_Exports.begin(), other.m_Exports.end()) {
DXASSERT_NOMSG(DXIL::IsValidSubobjectKind(m_Kind));
CopyUnionedContents(other);
if (&m_Owner != &other.m_Owner)
InternStrings();
}
void DxilSubobject::CopyUnionedContents(const DxilSubobject &other) {
switch (m_Kind) {
case Kind::StateObjectConfig:
StateObjectConfig.Flags = other.StateObjectConfig.Flags;
break;
case Kind::GlobalRootSignature:
case Kind::LocalRootSignature:
RootSignature.Size = other.RootSignature.Size;
RootSignature.Data = other.RootSignature.Data;
break;
case Kind::SubobjectToExportsAssociation:
SubobjectToExportsAssociation.Subobject =
other.SubobjectToExportsAssociation.Subobject;
break;
case Kind::RaytracingShaderConfig:
RaytracingShaderConfig.MaxPayloadSizeInBytes =
other.RaytracingShaderConfig.MaxPayloadSizeInBytes;
RaytracingShaderConfig.MaxAttributeSizeInBytes =
other.RaytracingShaderConfig.MaxAttributeSizeInBytes;
break;
case Kind::RaytracingPipelineConfig:
RaytracingPipelineConfig.MaxTraceRecursionDepth =
other.RaytracingPipelineConfig.MaxTraceRecursionDepth;
break;
case Kind::HitGroup:
HitGroup.Type = other.HitGroup.Type;
HitGroup.AnyHit = other.HitGroup.AnyHit;
HitGroup.ClosestHit = other.HitGroup.ClosestHit;
HitGroup.Intersection = other.HitGroup.Intersection;
break;
case Kind::RaytracingPipelineConfig1:
RaytracingPipelineConfig1.MaxTraceRecursionDepth =
other.RaytracingPipelineConfig1.MaxTraceRecursionDepth;
RaytracingPipelineConfig1.Flags = other.RaytracingPipelineConfig1.Flags;
break;
default:
DXASSERT(0, "invalid kind");
break;
}
}
void DxilSubobject::InternStrings() {
// Transfer strings if necessary
m_Name = m_Owner.InternString(m_Name).data();
switch (m_Kind) {
case Kind::SubobjectToExportsAssociation:
SubobjectToExportsAssociation.Subobject =
m_Owner.InternString(SubobjectToExportsAssociation.Subobject).data();
for (auto &ptr : m_Exports)
ptr = m_Owner.InternString(ptr).data();
break;
case Kind::HitGroup:
HitGroup.AnyHit = m_Owner.InternString(HitGroup.AnyHit).data();
HitGroup.ClosestHit = m_Owner.InternString(HitGroup.ClosestHit).data();
HitGroup.Intersection = m_Owner.InternString(HitGroup.Intersection).data();
break;
default:
break;
}
}
DxilSubobject::~DxilSubobject() {}
// StateObjectConfig
bool DxilSubobject::GetStateObjectConfig(uint32_t &Flags) const {
if (m_Kind == Kind::StateObjectConfig) {
Flags = StateObjectConfig.Flags;
return true;
}
return false;
}
// Local/Global RootSignature
bool DxilSubobject::GetRootSignature(bool local, const void *&Data,
uint32_t &Size, const char **pText) const {
Kind expected = local ? Kind::LocalRootSignature : Kind::GlobalRootSignature;
if (m_Kind == expected) {
Data = RootSignature.Data;
Size = RootSignature.Size;
if (pText)
*pText = RootSignature.Text;
return true;
}
return false;
}
// SubobjectToExportsAssociation
bool DxilSubobject::GetSubobjectToExportsAssociation(
llvm::StringRef &Subobject, const char *const *&Exports,
uint32_t &NumExports) const {
if (m_Kind == Kind::SubobjectToExportsAssociation) {
Subobject = SubobjectToExportsAssociation.Subobject;
Exports = m_Exports.data();
NumExports = (uint32_t)m_Exports.size();
return true;
}
return false;
}
// RaytracingShaderConfig
bool DxilSubobject::GetRaytracingShaderConfig(
uint32_t &MaxPayloadSizeInBytes, uint32_t &MaxAttributeSizeInBytes) const {
if (m_Kind == Kind::RaytracingShaderConfig) {
MaxPayloadSizeInBytes = RaytracingShaderConfig.MaxPayloadSizeInBytes;
MaxAttributeSizeInBytes = RaytracingShaderConfig.MaxAttributeSizeInBytes;
return true;
}
return false;
}
// RaytracingPipelineConfig
bool DxilSubobject::GetRaytracingPipelineConfig(
uint32_t &MaxTraceRecursionDepth) const {
if (m_Kind == Kind::RaytracingPipelineConfig) {
MaxTraceRecursionDepth = RaytracingPipelineConfig.MaxTraceRecursionDepth;
return true;
}
return false;
}
// HitGroup
bool DxilSubobject::GetHitGroup(DXIL::HitGroupType &hitGroupType,
llvm::StringRef &AnyHit,
llvm::StringRef &ClosestHit,
llvm::StringRef &Intersection) const {
if (m_Kind == Kind::HitGroup) {
hitGroupType = HitGroup.Type;
AnyHit = HitGroup.AnyHit;
ClosestHit = HitGroup.ClosestHit;
Intersection = HitGroup.Intersection;
return true;
}
return false;
}
// RaytracingPipelineConfig1
bool DxilSubobject::GetRaytracingPipelineConfig1(
uint32_t &MaxTraceRecursionDepth, uint32_t &Flags) const {
if (m_Kind == Kind::RaytracingPipelineConfig1) {
MaxTraceRecursionDepth = RaytracingPipelineConfig1.MaxTraceRecursionDepth;
Flags = RaytracingPipelineConfig1.Flags;
return true;
}
return false;
}
DxilSubobjects::DxilSubobjects() : m_BytesStorage(), m_Subobjects() {}
DxilSubobjects::DxilSubobjects(DxilSubobjects &&other)
: m_BytesStorage(std::move(other.m_BytesStorage)),
m_Subobjects(std::move(other.m_Subobjects)) {}
DxilSubobjects::~DxilSubobjects() {}
llvm::StringRef DxilSubobjects::InternString(llvm::StringRef value) {
auto it = m_BytesStorage.find(value);
if (it != m_BytesStorage.end())
return it->first;
size_t size = value.size();
StoredBytes stored(
std::make_pair(std::unique_ptr<char[]>(new char[size + 1]), size + 1));
memcpy(stored.first.get(), value.data(), size);
stored.first[size] = 0;
llvm::StringRef key(stored.first.get(), size);
m_BytesStorage[key] = std::move(stored);
return key;
}
const void *DxilSubobjects::InternRawBytes(const void *ptr, size_t size) {
auto it = m_BytesStorage.find(llvm::StringRef((const char *)ptr, size));
if (it != m_BytesStorage.end())
return it->first.data();
StoredBytes stored(
std::make_pair(std::unique_ptr<char[]>(new char[size]), size));
memcpy(stored.first.get(), ptr, size);
llvm::StringRef key(stored.first.get(), size);
m_BytesStorage[key] = std::move(stored);
return key.data();
}
DxilSubobject *DxilSubobjects::FindSubobject(llvm::StringRef name) {
auto it = m_Subobjects.find(name);
if (it != m_Subobjects.end())
return it->second.get();
return nullptr;
}
void DxilSubobjects::RemoveSubobject(llvm::StringRef name) {
auto it = m_Subobjects.find(name);
if (it != m_Subobjects.end())
m_Subobjects.erase(it);
}
DxilSubobject &DxilSubobjects::CloneSubobject(const DxilSubobject &Subobject,
llvm::StringRef Name) {
Name = InternString(Name);
DXASSERT(FindSubobject(Name) == nullptr,
"otherwise, name collision between subobjects");
std::unique_ptr<DxilSubobject> ptr(new DxilSubobject(*this, Subobject, Name));
DxilSubobject &ref = *ptr;
m_Subobjects[Name] = std::move(ptr);
return ref;
}
// Create DxilSubobjects
DxilSubobject &DxilSubobjects::CreateStateObjectConfig(llvm::StringRef Name,
uint32_t Flags) {
DXASSERT_NOMSG(0 == ((~(uint32_t)DXIL::StateObjectFlags::ValidMask) & Flags));
auto &obj = CreateSubobject(Kind::StateObjectConfig, Name);
obj.StateObjectConfig.Flags = Flags;
return obj;
}
DxilSubobject &
DxilSubobjects::CreateRootSignature(llvm::StringRef Name, bool local,
const void *Data, uint32_t Size,
llvm::StringRef *pText /*= nullptr*/) {
auto &obj = CreateSubobject(
local ? Kind::LocalRootSignature : Kind::GlobalRootSignature, Name);
obj.RootSignature.Data = InternRawBytes(Data, Size);
obj.RootSignature.Size = Size;
obj.RootSignature.Text = (pText ? InternString(*pText).data() : nullptr);
return obj;
}
DxilSubobject &DxilSubobjects::CreateSubobjectToExportsAssociation(
llvm::StringRef Name, llvm::StringRef Subobject, llvm::StringRef *Exports,
uint32_t NumExports) {
auto &obj = CreateSubobject(Kind::SubobjectToExportsAssociation, Name);
Subobject = InternString(Subobject);
obj.SubobjectToExportsAssociation.Subobject = Subobject.data();
for (unsigned i = 0; i < NumExports; i++) {
obj.m_Exports.emplace_back(InternString(Exports[i]).data());
}
return obj;
}
DxilSubobject &
DxilSubobjects::CreateRaytracingShaderConfig(llvm::StringRef Name,
uint32_t MaxPayloadSizeInBytes,
uint32_t MaxAttributeSizeInBytes) {
auto &obj = CreateSubobject(Kind::RaytracingShaderConfig, Name);
obj.RaytracingShaderConfig.MaxPayloadSizeInBytes = MaxPayloadSizeInBytes;
obj.RaytracingShaderConfig.MaxAttributeSizeInBytes = MaxAttributeSizeInBytes;
return obj;
}
DxilSubobject &DxilSubobjects::CreateRaytracingPipelineConfig(
llvm::StringRef Name, uint32_t MaxTraceRecursionDepth) {
auto &obj = CreateSubobject(Kind::RaytracingPipelineConfig, Name);
obj.RaytracingPipelineConfig.MaxTraceRecursionDepth = MaxTraceRecursionDepth;
return obj;
}
DxilSubobject &DxilSubobjects::CreateHitGroup(llvm::StringRef Name,
DXIL::HitGroupType hitGroupType,
llvm::StringRef AnyHit,
llvm::StringRef ClosestHit,
llvm::StringRef Intersection) {
auto &obj = CreateSubobject(Kind::HitGroup, Name);
AnyHit = InternString(AnyHit);
ClosestHit = InternString(ClosestHit);
Intersection = InternString(Intersection);
obj.HitGroup.Type = hitGroupType;
obj.HitGroup.AnyHit = AnyHit.data();
obj.HitGroup.ClosestHit = ClosestHit.data();
obj.HitGroup.Intersection = Intersection.data();
return obj;
}
DxilSubobject &DxilSubobjects::CreateRaytracingPipelineConfig1(
llvm::StringRef Name, uint32_t MaxTraceRecursionDepth, uint32_t Flags) {
auto &obj = CreateSubobject(Kind::RaytracingPipelineConfig1, Name);
obj.RaytracingPipelineConfig1.MaxTraceRecursionDepth = MaxTraceRecursionDepth;
DXASSERT_NOMSG(
0 == ((~(uint32_t)DXIL::RaytracingPipelineFlags::ValidMask) & Flags));
obj.RaytracingPipelineConfig1.Flags = Flags;
return obj;
}
DxilSubobject &DxilSubobjects::CreateSubobject(Kind kind,
llvm::StringRef Name) {
Name = InternString(Name);
IFTBOOLMSG(FindSubobject(Name) == nullptr, DXC_E_GENERAL_INTERNAL_ERROR,
"Subobject name collision");
IFTBOOLMSG(!Name.empty(), DXC_E_GENERAL_INTERNAL_ERROR,
"Empty Subobject name");
std::unique_ptr<DxilSubobject> ptr(new DxilSubobject(*this, kind, Name));
DxilSubobject &ref = *ptr;
m_Subobjects[Name] = std::move(ptr);
return ref;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilCompType.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilCompType.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilCompType.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
using namespace llvm;
namespace hlsl {
//------------------------------------------------------------------------------
//
// CompType class methods.
//
CompType::CompType() : m_Kind(Kind::Invalid) {}
CompType::CompType(Kind K) : m_Kind(K) {
DXASSERT(m_Kind >= Kind::Invalid && m_Kind < Kind::LastEntry,
"otherwise the caller passed out-of-range value");
}
CompType::CompType(unsigned int K) : CompType((Kind)K) {}
bool CompType::operator==(const CompType &o) const {
return m_Kind == o.m_Kind;
}
CompType::Kind CompType::GetKind() const { return m_Kind; }
uint8_t CompType::GetSizeInBits() const {
switch (m_Kind) {
case Kind::Invalid:
return 0;
case Kind::I1:
return 1;
case Kind::SNormF16:
case Kind::UNormF16:
case Kind::I16:
case Kind::F16:
case Kind::U16:
return 16;
case Kind::SNormF32:
case Kind::UNormF32:
case Kind::I32:
case Kind::U32:
case Kind::F32:
case Kind::PackedS8x32:
case Kind::PackedU8x32:
return 32;
case Kind::I64:
case Kind::U64:
case Kind::SNormF64:
case Kind::UNormF64:
case Kind::F64:
return 64;
default:
DXASSERT(false, "invalid type kind");
}
return 0;
}
CompType CompType::getInvalid() { return CompType(); }
CompType CompType::getF16() { return CompType(Kind::F16); }
CompType CompType::getF32() { return CompType(Kind::F32); }
CompType CompType::getF64() { return CompType(Kind::F64); }
CompType CompType::getI16() { return CompType(Kind::I16); }
CompType CompType::getI32() { return CompType(Kind::I32); }
CompType CompType::getI64() { return CompType(Kind::I64); }
CompType CompType::getU16() { return CompType(Kind::U16); }
CompType CompType::getU32() { return CompType(Kind::U32); }
CompType CompType::getU64() { return CompType(Kind::U64); }
CompType CompType::getI1() { return CompType(Kind::I1); }
CompType CompType::getSNormF16() { return CompType(Kind::SNormF16); }
CompType CompType::getUNormF16() { return CompType(Kind::UNormF16); }
CompType CompType::getSNormF32() { return CompType(Kind::SNormF32); }
CompType CompType::getUNormF32() { return CompType(Kind::UNormF32); }
CompType CompType::getSNormF64() { return CompType(Kind::SNormF64); }
CompType CompType::getUNormF64() { return CompType(Kind::UNormF64); }
bool CompType::IsInvalid() const { return m_Kind == Kind::Invalid; }
bool CompType::IsFloatTy() const {
return m_Kind == Kind::F16 || m_Kind == Kind::F32 || m_Kind == Kind::F64;
}
bool CompType::IsIntTy() const { return IsSIntTy() || IsUIntTy(); }
bool CompType::IsSIntTy() const {
return m_Kind == Kind::I16 || m_Kind == Kind::I32 || m_Kind == Kind::I64;
}
bool CompType::IsUIntTy() const {
return m_Kind == Kind::U16 || m_Kind == Kind::U32 || m_Kind == Kind::U64 ||
m_Kind == Kind::PackedS8x32 || m_Kind == Kind::PackedU8x32;
}
bool CompType::IsBoolTy() const { return m_Kind == Kind::I1; }
bool CompType::IsSNorm() const {
return m_Kind == Kind::SNormF16 || m_Kind == Kind::SNormF32 ||
m_Kind == Kind::SNormF64;
}
bool CompType::IsUNorm() const {
return m_Kind == Kind::UNormF16 || m_Kind == Kind::UNormF32 ||
m_Kind == Kind::UNormF64;
}
bool CompType::Is64Bit() const {
switch (m_Kind) {
case DXIL::ComponentType::F64:
case DXIL::ComponentType::SNormF64:
case DXIL::ComponentType::UNormF64:
case DXIL::ComponentType::I64:
case DXIL::ComponentType::U64:
return true;
default:
return false;
}
}
bool CompType::Is16Bit() const {
switch (m_Kind) {
case DXIL::ComponentType::F16:
case DXIL::ComponentType::I16:
case DXIL::ComponentType::SNormF16:
case DXIL::ComponentType::UNormF16:
case DXIL::ComponentType::U16:
return true;
default:
return false;
}
}
CompType CompType::GetBaseCompType() const {
switch (m_Kind) {
case Kind::I1:
return CompType(Kind::I1);
case Kind::I16:
LLVM_FALLTHROUGH;
case Kind::PackedS8x32:
LLVM_FALLTHROUGH;
case Kind::PackedU8x32:
LLVM_FALLTHROUGH;
case Kind::I32:
return CompType(Kind::I32);
case Kind::I64:
return CompType(Kind::I64);
case Kind::U16:
LLVM_FALLTHROUGH;
case Kind::U32:
return CompType(Kind::U32);
case Kind::U64:
return CompType(Kind::U64);
case Kind::SNormF16:
LLVM_FALLTHROUGH;
case Kind::UNormF16:
LLVM_FALLTHROUGH;
case Kind::F16:
LLVM_FALLTHROUGH;
case Kind::SNormF32:
LLVM_FALLTHROUGH;
case Kind::UNormF32:
LLVM_FALLTHROUGH;
case Kind::F32:
return CompType(Kind::F32);
case Kind::SNormF64:
LLVM_FALLTHROUGH;
case Kind::UNormF64:
LLVM_FALLTHROUGH;
case Kind::F64:
return CompType(Kind::F64);
default:
DXASSERT(false, "invalid type kind");
}
return CompType();
}
bool CompType::HasMinPrec() const {
switch (m_Kind) {
case Kind::I16:
case Kind::U16:
case Kind::F16:
case Kind::SNormF16:
case Kind::UNormF16:
return true;
case Kind::I1:
case Kind::PackedS8x32:
case Kind::PackedU8x32:
case Kind::I32:
case Kind::U32:
case Kind::I64:
case Kind::U64:
case Kind::F32:
case Kind::F64:
case Kind::SNormF32:
case Kind::UNormF32:
case Kind::SNormF64:
case Kind::UNormF64:
break;
default:
DXASSERT(false, "invalid comp type");
}
return false;
}
Type *CompType::GetLLVMType(LLVMContext &Ctx) const {
switch (m_Kind) {
case Kind::I1:
return (Type *)Type::getInt1Ty(Ctx);
case Kind::I16:
case Kind::U16:
return (Type *)Type::getInt16Ty(Ctx);
case Kind::PackedS8x32:
case Kind::PackedU8x32:
case Kind::I32:
case Kind::U32:
return (Type *)Type::getInt32Ty(Ctx);
case Kind::I64:
case Kind::U64:
return (Type *)Type::getInt64Ty(Ctx);
case Kind::SNormF16:
case Kind::UNormF16:
case Kind::F16:
return Type::getHalfTy(Ctx);
case Kind::SNormF32:
case Kind::UNormF32:
case Kind::F32:
return Type::getFloatTy(Ctx);
case Kind::SNormF64:
case Kind::UNormF64:
case Kind::F64:
return Type::getDoubleTy(Ctx);
default:
DXASSERT(false, "invalid type kind");
}
return nullptr;
}
PointerType *CompType::GetLLVMPtrType(LLVMContext &Ctx,
const unsigned AddrSpace) const {
switch (m_Kind) {
case Kind::I1:
return Type::getInt1PtrTy(Ctx, AddrSpace);
case Kind::I16:
case Kind::U16:
return Type::getInt16PtrTy(Ctx, AddrSpace);
case Kind::PackedS8x32:
case Kind::PackedU8x32:
case Kind::I32:
case Kind::U32:
return Type::getInt32PtrTy(Ctx, AddrSpace);
case Kind::I64:
case Kind::U64:
return Type::getInt64PtrTy(Ctx, AddrSpace);
case Kind::SNormF16:
case Kind::UNormF16:
case Kind::F16:
return Type::getHalfPtrTy(Ctx, AddrSpace);
case Kind::SNormF32:
case Kind::UNormF32:
case Kind::F32:
return Type::getFloatPtrTy(Ctx, AddrSpace);
case Kind::SNormF64:
case Kind::UNormF64:
case Kind::F64:
return Type::getDoublePtrTy(Ctx, AddrSpace);
default:
DXASSERT(false, "invalid type kind");
}
return nullptr;
}
Type *CompType::GetLLVMBaseType(llvm::LLVMContext &Ctx) const {
return GetBaseCompType().GetLLVMType(Ctx);
}
CompType CompType::GetCompType(Type *type) {
LLVMContext &Ctx = type->getContext();
if (type == Type::getInt1Ty(Ctx))
return CompType(Kind::I1);
if (type == Type::getInt16Ty(Ctx))
return CompType(Kind::I16);
if (type == Type::getInt32Ty(Ctx))
return CompType(Kind::I32);
if (type == Type::getInt64Ty(Ctx))
return CompType(Kind::I64);
if (type == Type::getHalfTy(Ctx))
return CompType(Kind::F16);
if (type == Type::getFloatTy(Ctx))
return CompType(Kind::F32);
if (type == Type::getDoubleTy(Ctx))
return CompType(Kind::F64);
DXASSERT(false, "invalid type kind");
return CompType();
}
static const char *s_TypeKindNames[(unsigned)CompType::Kind::LastEntry] = {
"invalid", "i1", "i16", "u16", "i32",
"u32", "i64", "u64", "f16", "f32",
"f64", "snorm_f16", "unorm_f16", "snorm_f32", "unorm_f32",
"snorm_f64", "unorm_f64", "p32i8", "p32u8",
};
const char *CompType::GetName() const {
return s_TypeKindNames[(unsigned)m_Kind];
}
static const char *s_TypeKindHLSLNames[(unsigned)CompType::Kind::LastEntry] = {
"unknown", "bool", "int16_t", "uint16_t",
"int", "uint", "int64_t", "uint64_t",
"half", "float", "double", "snorm_half",
"unorm_half", "snorm_float", "unorm_float", "snorm_double",
"unorm_double", "int8_t_packed", "uint8_t_packed",
};
static const char
*s_TypeKindHLSLNamesMinPrecision[(unsigned)CompType::Kind::LastEntry] = {
"unknown", "bool", "min16i", "min16ui",
"int", "uint", "int64_t", "uint64_t",
"min16float", "float", "double", "snorm_min16f",
"unorm_min16f", "snorm_float", "unorm_float", "snorm_double",
"unorm_double", "int8_t_packed", "uint8_t_packed",
};
const char *CompType::GetHLSLName(bool MinPrecision) const {
return MinPrecision ? s_TypeKindHLSLNamesMinPrecision[(unsigned)m_Kind]
: s_TypeKindHLSLNames[(unsigned)m_Kind];
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilInterpolationMode.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilInterpolationMode.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilInterpolationMode.h"
#include "dxc/Support/Global.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// InterpolationMode class methods.
//
InterpolationMode::InterpolationMode() : m_Kind(Kind::Undefined) {}
InterpolationMode::InterpolationMode(Kind Kind) : m_Kind(Kind) {}
InterpolationMode::InterpolationMode(unsigned long long kind) {
m_Kind = (Kind)kind;
if (m_Kind >= Kind::Invalid) {
m_Kind = Kind::Invalid;
}
}
// NoInterpolation,
// bLinear,
// bNoperspective,
// bCentroid,
// bSample
static const DXIL::InterpolationMode interpModeTab[] = {
DXIL::InterpolationMode::Undefined, // 0 , False , False ,
// False , False , False
DXIL::InterpolationMode::LinearSample, // 1 , False , False ,
// False , False ,
// True
DXIL::InterpolationMode::LinearCentroid, // 2 , False , False
// , False , True ,
// False
DXIL::InterpolationMode::LinearSample, // 3 , False , False ,
// False , True , True
DXIL::InterpolationMode::LinearNoperspective, // 4 , False ,
// False , True ,
// False , False
DXIL::InterpolationMode::
LinearNoperspectiveSample, // 5 , False , False ,
// True , False , True
DXIL::InterpolationMode::
LinearNoperspectiveCentroid, // 6 , False , False ,
// True , True , False
DXIL::InterpolationMode::LinearNoperspectiveSample, // 7 , False ,
// False , True
// , True , True
DXIL::InterpolationMode::Linear, // 8 , False , True ,
// False , False , False
DXIL::InterpolationMode::LinearSample, // 9 , False , True ,
// False , False ,
// True
DXIL::InterpolationMode::LinearCentroid, // 10 , False , True
// , False , True ,
// False
DXIL::InterpolationMode::LinearSample, // 11 , False , True ,
// False , True , True
DXIL::InterpolationMode::LinearNoperspective, // 12 , False ,
// True , True , False
// , False
DXIL::InterpolationMode::LinearNoperspectiveSample, // 13 , False ,
// True , True
// , False , True
DXIL::InterpolationMode::
LinearNoperspectiveCentroid, // 14 , False , True ,
// True , True , False
DXIL::InterpolationMode::LinearNoperspectiveSample, // 15 , False ,
// True , True
// , True , True
DXIL::InterpolationMode::Constant, // 16 , True , False ,
// False , False , False
DXIL::InterpolationMode::Invalid, // 17 , True , False , False
// , False , True
DXIL::InterpolationMode::Invalid, // 18 , True , False , False
// , True , False
DXIL::InterpolationMode::Invalid, // 19 , True , False , False
// , True , True
DXIL::InterpolationMode::Invalid, // 20 , True , False , True
// , False , False
DXIL::InterpolationMode::Invalid, // 21 , True , False , True
// , False , True
DXIL::InterpolationMode::Invalid, // 22 , True , False , True
// , True , False
DXIL::InterpolationMode::Invalid, // 23 , True , False , True
// , True , True
DXIL::InterpolationMode::Invalid, // 24 , True , True ,
// False , False , False
DXIL::InterpolationMode::Invalid, // 25 , True , True ,
// False , False , True
DXIL::InterpolationMode::Invalid, // 26 , True , True ,
// False , True , False
DXIL::InterpolationMode::Invalid, // 27 , True , True ,
// False , True , True
DXIL::InterpolationMode::Invalid, // 28 , True , True ,
// True , False , False
DXIL::InterpolationMode::Invalid, // 29 , True , True ,
// True , False , True
DXIL::InterpolationMode::Invalid, // 30 , True , True ,
// True , True , False
DXIL::InterpolationMode::Invalid, // 31 , True , True ,
// True , True , True
};
InterpolationMode::InterpolationMode(bool bNoInterpolation, bool bLinear,
bool bNoperspective, bool bCentroid,
bool bSample) {
unsigned mask = (unsigned)bNoInterpolation << 4;
mask |= ((unsigned)bLinear) << 3;
mask |= ((unsigned)bNoperspective) << 2;
mask |= ((unsigned)bCentroid) << 1;
mask |= ((unsigned)bSample);
m_Kind = interpModeTab[mask];
// interpModeTab is generate from following code.
// m_Kind = Kind::Invalid; // Cases not set below are invalid.
// bool bAnyLinear = bLinear | bNoperspective | bCentroid | bSample;
// if (bNoInterpolation) {
// if (!bAnyLinear) m_Kind = Kind::Constant;
//}
// else if (bAnyLinear) {
// if (bSample) { // warning case: sample overrides centroid.
// if (bNoperspective) m_Kind = Kind::LinearNoperspectiveSample;
// else m_Kind = Kind::LinearSample;
// }
// else {
// if (!bNoperspective && !bCentroid) m_Kind = Kind::Linear;
// else if (!bNoperspective && bCentroid) m_Kind = Kind::LinearCentroid;
// else if ( bNoperspective && !bCentroid) m_Kind =
// Kind::LinearNoperspective; else if ( bNoperspective && bCentroid)
// m_Kind = Kind::LinearNoperspectiveCentroid;
// }
//}
// else {
// m_Kind = Kind::Undefined;
//}
}
InterpolationMode &InterpolationMode::operator=(const InterpolationMode &o) {
if (this != &o) {
m_Kind = o.m_Kind;
}
return *this;
}
bool InterpolationMode::operator==(const InterpolationMode &o) const {
return m_Kind == o.m_Kind;
}
bool InterpolationMode::IsAnyLinear() const {
return m_Kind < Kind::Invalid && m_Kind != Kind::Undefined &&
m_Kind != Kind::Constant;
}
bool InterpolationMode::IsAnyNoPerspective() const {
return IsLinearNoperspective() || IsLinearNoperspectiveCentroid() ||
IsLinearNoperspectiveSample();
}
bool InterpolationMode::IsAnyCentroid() const {
return IsLinearCentroid() || IsLinearNoperspectiveCentroid();
}
bool InterpolationMode::IsAnySample() const {
return IsLinearSample() || IsLinearNoperspectiveSample();
}
const char *InterpolationMode::GetName() const {
switch (m_Kind) {
case Kind::Undefined:
return "";
case Kind::Constant:
return "nointerpolation";
case Kind::Linear:
return "linear";
case Kind::LinearCentroid:
return "centroid";
case Kind::LinearNoperspective:
return "noperspective";
case Kind::LinearNoperspectiveCentroid:
return "noperspective centroid";
case Kind::LinearSample:
return "sample";
case Kind::LinearNoperspectiveSample:
return "noperspective sample";
default:
DXASSERT(false, "invalid interpolation mode");
return "invalid";
}
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilSampler.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilSampler.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilSampler.h"
#include "dxc/Support/Global.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// Sampler class methods.
//
DxilSampler::DxilSampler()
: DxilResourceBase(DxilResourceBase::Class::Sampler),
m_SamplerKind(DXIL::SamplerKind::Invalid) {
DxilResourceBase::SetKind(DxilResourceBase::Kind::Sampler);
}
DxilSampler::SamplerKind DxilSampler::GetSamplerKind() const {
return m_SamplerKind;
}
bool DxilSampler::IsCompSampler() const {
return m_SamplerKind == SamplerKind::Comparison;
}
void DxilSampler::SetSamplerKind(SamplerKind K) { m_SamplerKind = K; }
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilPDB.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilPDB.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Helpers to wrap debug information in a PDB container. //
// //
///////////////////////////////////////////////////////////////////////////////
//
// This file contains code that helps creating our special PDB format. PDB
// format contains streams at fixed locations. Outside of those fixed
// locations, unless they are listed in the stream hash table, there is be no
// way to know what the stream is. As far as normal PDB's are concerned, they
// dont' really exist.
//
// For our purposes, we always put our data in one stream at a fixed index
// defined below. The data is an ordinary DXIL container format, with parts
// that are relevant for debugging.
//
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"
#include "dxc/DXIL/DxilPDB.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/dxcapi.impl.h"
#include "dxc/dxcapi.h"
using namespace llvm;
// MSF header
static const char kMsfMagic[] = {
'M', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't', ' ', 'C',
'/', 'C', '+', '+', ' ', 'M', 'S', 'F', ' ', '7', '.',
'0', '0', '\r', '\n', '\x1a', 'D', 'S', '\0', '\0', '\0'};
static const uint32_t kPdbStreamIndex =
1; // This is the fixed stream index where the PDB stream header is
static const uint32_t kDataStreamIndex =
5; // This is the fixed stream index where we will store our custom data.
static const uint32_t kMsfBlockSize = 512;
// The superblock is overlaid at the beginning of the file (offset 0).
// It starts with a magic header and is followed by information which
// describes the layout of the file system.
struct MSF_SuperBlock {
char MagicBytes[sizeof(kMsfMagic)];
// The file system is split into a variable number of fixed size elements.
// These elements are referred to as blocks. The size of a block may vary
// from system to system.
support::ulittle32_t BlockSize;
// The index of the free block map.
support::ulittle32_t FreeBlockMapBlock;
// This contains the number of blocks resident in the file system. In
// practice, NumBlocks * BlockSize is equivalent to the size of the MSF
// file.
support::ulittle32_t NumBlocks;
// This contains the number of bytes which make up the directory.
support::ulittle32_t NumDirectoryBytes;
// This field's purpose is not yet known.
support::ulittle32_t Unknown1;
// This contains the block # of the block map.
support::ulittle32_t BlockMapAddr;
};
static_assert(sizeof(MSF_SuperBlock) <= kMsfBlockSize, "MSF Block too small.");
// Calculate how many blocks are needed
static uint32_t CalculateNumBlocks(uint32_t BlockSize, uint32_t Size) {
return (Size / BlockSize) + ((Size % BlockSize) ? 1 : 0);
}
static HRESULT ReadAllBytes(IStream *pStream, void *pDst, size_t uSize) {
ULONG uBytesRead = 0;
IFR(pStream->Read(pDst, uSize, &uBytesRead));
if (uBytesRead != uSize)
return E_FAIL;
return S_OK;
}
struct MSFWriter {
struct Stream {
ArrayRef<char> Data;
unsigned NumBlocks = 0;
};
struct StreamLayout {
MSF_SuperBlock SB;
};
int m_NumBlocks = 0;
SmallVector<Stream, 8> m_Streams;
static uint32_t GetNumBlocks(uint32_t Size) {
return CalculateNumBlocks(kMsfBlockSize, Size);
}
uint32_t AddStream(ArrayRef<char> Data) {
uint32_t ID = m_Streams.size();
Stream S;
S.Data = Data;
S.NumBlocks = GetNumBlocks(Data.size());
m_NumBlocks += S.NumBlocks;
m_Streams.push_back(S);
return ID;
}
uint32_t AddEmptyStream() { return AddStream({}); }
uint32_t CalculateDirectorySize() {
uint32_t DirectorySizeInBytes = 0;
DirectorySizeInBytes += sizeof(uint32_t);
DirectorySizeInBytes += m_Streams.size() * 4;
for (unsigned i = 0; i < m_Streams.size(); i++) {
DirectorySizeInBytes += m_Streams[i].NumBlocks * 4;
}
return DirectorySizeInBytes;
}
MSF_SuperBlock CalculateSuperblock() {
MSF_SuperBlock SB = {};
memcpy(SB.MagicBytes, kMsfMagic, sizeof(kMsfMagic));
SB.BlockSize = kMsfBlockSize;
SB.NumDirectoryBytes = CalculateDirectorySize();
SB.NumBlocks = 3 + m_NumBlocks + GetNumBlocks(SB.NumDirectoryBytes);
SB.FreeBlockMapBlock = 1;
SB.BlockMapAddr = 3;
return SB;
}
struct BlockWriter {
uint32_t BlocksWritten = 0;
raw_ostream &OS;
BlockWriter(raw_ostream &OS) : OS(OS) {}
void WriteZeroPads(uint32_t Count) {
for (unsigned i = 0; i < Count; i++)
OS.write(0);
}
void WriteEmptyBlock() {
BlocksWritten++;
WriteZeroPads(kMsfBlockSize);
}
void WriteBlocks(uint32_t NumBlocks, const void *Data, uint32_t Size) {
assert(NumBlocks >= GetNumBlocks(Size) &&
"Cannot fit data into the requested number of blocks!");
uint32_t TotalSize = NumBlocks * kMsfBlockSize;
OS.write(static_cast<char *>(const_cast<void *>(Data)), Size);
WriteZeroPads(TotalSize - Size);
BlocksWritten += NumBlocks;
}
void WriteUint32(uint32_t Value) {
support::ulittle32_t ValueLE;
ValueLE = Value;
OS.write((char *)&ValueLE, sizeof(ValueLE));
}
};
void WriteBlocks(raw_ostream &OS, ArrayRef<char> Data, uint32_t NumBlocks) {
assert(NumBlocks >= GetNumBlocks(Data.size()) &&
"Cannot fit data into the requested number of blocks!");
uint32_t TotalSize = NumBlocks * kMsfBlockSize;
OS.write(Data.data(), Data.size());
WriteZeroPadding(OS, TotalSize - Data.size());
}
void WriteZeroPadding(raw_ostream &OS, int Count) {
for (int i = 0; i < Count; i++)
OS.write(0);
}
static support::ulittle32_t MakeUint32LE(uint32_t Value) {
support::ulittle32_t ValueLE;
ValueLE = Value;
return ValueLE;
}
void WriteToStream(raw_ostream &OS) {
MSF_SuperBlock SB = CalculateSuperblock();
const uint32_t NumDirectoryBlocks = GetNumBlocks(SB.NumDirectoryBytes);
const uint32_t StreamDirectoryAddr = SB.BlockMapAddr;
const uint32_t BlockAddrSize =
NumDirectoryBlocks * sizeof(support::ulittle32_t);
const uint32_t NumBlockAddrBlocks = GetNumBlocks(BlockAddrSize);
const uint32_t StreamDirectoryStart =
StreamDirectoryAddr + NumBlockAddrBlocks;
const uint32_t StreamStart = StreamDirectoryStart + NumDirectoryBlocks;
BlockWriter Writer(OS);
Writer.WriteBlocks(1, &SB, sizeof(SB)); // Super Block
Writer.WriteEmptyBlock(); // FPM 1
Writer.WriteEmptyBlock(); // FPM 2
// BlockAddr
// This block contains a list of uint32's that point to the blocks that
// make up the stream directory.
{
SmallVector<support::ulittle32_t, 4> BlockAddr;
uint32_t Start = StreamDirectoryStart;
for (unsigned i = 0; i < NumDirectoryBlocks; i++) {
support::ulittle32_t V;
V = Start++;
BlockAddr.push_back(V);
}
assert(BlockAddrSize == sizeof(BlockAddr[0]) * BlockAddr.size());
Writer.WriteBlocks(NumBlockAddrBlocks, BlockAddr.data(), BlockAddrSize);
}
// Stream Directory. Describes where all the streams are
// Looks like this:
//
{
SmallVector<support::ulittle32_t, 32> StreamDirectoryData;
StreamDirectoryData.push_back(MakeUint32LE(m_Streams.size()));
for (unsigned i = 0; i < m_Streams.size(); i++) {
StreamDirectoryData.push_back(MakeUint32LE(m_Streams[i].Data.size()));
}
uint32_t Start = StreamStart;
for (unsigned i = 0; i < m_Streams.size(); i++) {
auto &Stream = m_Streams[i];
for (unsigned j = 0; j < Stream.NumBlocks; j++) {
StreamDirectoryData.push_back(MakeUint32LE(Start++));
}
}
Writer.WriteBlocks(NumDirectoryBlocks, StreamDirectoryData.data(),
StreamDirectoryData.size() *
sizeof(StreamDirectoryData[0]));
}
// Write the streams.
{
for (unsigned i = 0; i < m_Streams.size(); i++) {
auto &Stream = m_Streams[i];
Writer.WriteBlocks(Stream.NumBlocks, Stream.Data.data(),
Stream.Data.size());
}
}
}
};
enum class PdbStreamVersion : uint32_t {
VC2 = 19941610,
VC4 = 19950623,
VC41 = 19950814,
VC50 = 19960307,
VC98 = 19970604,
VC70Dep = 19990604,
VC70 = 20000404,
VC80 = 20030901,
VC110 = 20091201,
VC140 = 20140508,
};
struct PdbStreamHeader {
support::ulittle32_t Version;
support::ulittle32_t Signature;
support::ulittle32_t Age;
uint8_t UniqueId[16];
};
static_assert(sizeof(PdbStreamHeader) == 28, "PDB Header incorrect.");
static SmallVector<char, 0> WritePdbStream(ArrayRef<BYTE> Hash) {
PdbStreamHeader Header = {};
Header.Version = (uint32_t)PdbStreamVersion::VC70;
Header.Age = 1;
Header.Signature = 0;
DXASSERT_NOMSG(Hash.size() == sizeof(Header.UniqueId));
memcpy(Header.UniqueId, Hash.data(),
std::min(Hash.size(), sizeof(Header.UniqueId)));
SmallVector<char, 0> Result;
raw_svector_ostream OS(Result);
auto WriteU32 = [&](uint32_t val) {
support::ulittle32_t valLE;
valLE = val;
OS.write((char *)&valLE, sizeof(valLE));
};
OS.write((char *)&Header, 28);
WriteU32(0); // String buffer size
WriteU32(0); // Size
WriteU32(1); // Capacity // Capacity is required to be 1.
WriteU32(0); // Present count
WriteU32(0); // Deleted count
WriteU32(0); // Key
WriteU32(0); // Value
OS.flush();
return Result;
}
HRESULT hlsl::pdb::WriteDxilPDB(IMalloc *pMalloc, IDxcBlob *pContainer,
ArrayRef<BYTE> HashData, IDxcBlob **ppOutBlob) {
return hlsl::pdb::WriteDxilPDB(
pMalloc,
llvm::ArrayRef<BYTE>((const BYTE *)pContainer->GetBufferPointer(),
pContainer->GetBufferSize()),
HashData, ppOutBlob);
}
HRESULT hlsl::pdb::WriteDxilPDB(IMalloc *pMalloc,
llvm::ArrayRef<BYTE> ContainerData,
llvm::ArrayRef<BYTE> HashData,
IDxcBlob **ppOutBlob) {
if (!hlsl::IsValidDxilContainer(
(const hlsl::DxilContainerHeader *)ContainerData.data(),
ContainerData.size()))
return E_FAIL;
SmallVector<char, 0> PdbStream = WritePdbStream(HashData);
MSFWriter Writer;
Writer.AddEmptyStream(); // Old Directory
Writer.AddStream(PdbStream); // PDB Header
// Fixed streams
Writer.AddEmptyStream(); // TPI
Writer.AddEmptyStream(); // DBI
Writer.AddEmptyStream(); // IPI
Writer.AddStream(
llvm::ArrayRef<char>((const char *)ContainerData.data(),
ContainerData.size())); // Actual data block
CComPtr<hlsl::AbstractMemoryStream> pStream;
IFR(hlsl::CreateMemoryStream(pMalloc, &pStream));
raw_stream_ostream OS(pStream);
Writer.WriteToStream(OS);
OS.flush();
IFR(pStream.QueryInterface(ppOutBlob));
return S_OK;
}
struct PDBReader {
IStream *m_pStream = nullptr;
IMalloc *m_pMalloc = nullptr;
UINT32 m_uOriginalOffset = 0;
MSF_SuperBlock m_SB = {};
HRESULT m_Status = S_OK;
HRESULT SetPosition(INT32 sOffset) {
LARGE_INTEGER Distance = {};
Distance.QuadPart = m_uOriginalOffset + sOffset;
ULARGE_INTEGER NewLocation = {};
return m_pStream->Seek(Distance, STREAM_SEEK_SET, &NewLocation);
}
PDBReader(IMalloc *pMalloc, IStream *pStream)
: m_pStream(pStream), m_pMalloc(pMalloc) {
m_Status = ReadSuperblock(&m_SB);
}
// Reset the stream back to its original position, regardless of
// we succeeded or failed.
~PDBReader() { SetPosition(0); }
HRESULT GetStatus() { return m_Status; }
HRESULT ReadSuperblock(MSF_SuperBlock *pSB) {
IFR(ReadAllBytes(m_pStream, pSB, sizeof(*pSB)));
if (memcmp(pSB->MagicBytes, kMsfMagic, sizeof(kMsfMagic)) != 0)
return E_FAIL;
return S_OK;
}
HRESULT ReadU32(UINT32 *pValue) {
support::ulittle32_t ValueLE;
IFR(ReadAllBytes(m_pStream, &ValueLE, sizeof(ValueLE)));
*pValue = ValueLE;
return S_OK;
}
HRESULT GoToBeginningOfBlock(UINT32 uBlock) {
return SetPosition(uBlock * m_SB.BlockSize);
}
HRESULT OffsetByU32(int sCount) {
LARGE_INTEGER Offset = {};
ULARGE_INTEGER BytesMoved = {};
Offset.QuadPart = sCount * sizeof(UINT32);
return m_pStream->Seek(Offset, STREAM_SEEK_CUR, &BytesMoved);
}
HRESULT ReadWholeStream(uint32_t StreamIndex, IDxcBlob **ppData) {
if (FAILED(m_Status))
return m_Status;
UINT32 uNumDirectoryBlocks =
CalculateNumBlocks(m_SB.BlockSize, m_SB.NumDirectoryBytes);
// Load in the directory blocks
llvm::SmallVector<uint32_t, 32> DirectoryBlocks;
IFR(GoToBeginningOfBlock(m_SB.BlockMapAddr))
for (unsigned i = 0; i < uNumDirectoryBlocks; i++) {
UINT32 uBlock = 0;
IFR(ReadU32(&uBlock));
DirectoryBlocks.push_back(uBlock);
}
// Load Num streams
UINT32 uNumStreams = 0;
IFR(GoToBeginningOfBlock(DirectoryBlocks[0]));
IFR(ReadU32(&uNumStreams));
// If we don't have enough streams, then give up.
if (uNumStreams <= StreamIndex)
return E_FAIL;
llvm::SmallVector<uint32_t, 6> StreamSizes;
IFR(ReadU32ListFromBlocks(DirectoryBlocks, 1, uNumStreams, StreamSizes));
UINT32 uOffsets = 0;
for (unsigned i = 0; i < StreamIndex; i++) {
UINT32 uNumBlocks = CalculateNumBlocks(m_SB.BlockSize, StreamSizes[i]);
uOffsets += uNumBlocks;
}
llvm::SmallVector<uint32_t, 12> DataBlocks;
IFR(ReadU32ListFromBlocks(
DirectoryBlocks, 1 + uNumStreams + uOffsets,
CalculateNumBlocks(m_SB.BlockSize, StreamSizes[StreamIndex]),
DataBlocks));
if (DataBlocks.size() == 0)
return E_FAIL;
IFR(GoToBeginningOfBlock(DataBlocks[0]));
CComPtr<hlsl::AbstractMemoryStream> pResult;
IFR(CreateMemoryStream(m_pMalloc, &pResult));
std::vector<char> CopyBuffer;
CopyBuffer.resize(m_SB.BlockSize);
for (unsigned i = 0; i < DataBlocks.size(); i++) {
IFR(GoToBeginningOfBlock(DataBlocks[i]));
IFR(ReadAllBytes(m_pStream, CopyBuffer.data(), m_SB.BlockSize));
ULONG uSizeWritten = 0;
IFR(pResult->Write(CopyBuffer.data(), m_SB.BlockSize, &uSizeWritten));
if (uSizeWritten != m_SB.BlockSize)
return E_FAIL;
}
IFR(pResult.QueryInterface(ppData));
return S_OK;
}
HRESULT ReadU32ListFromBlocks(ArrayRef<uint32_t> Blocks, UINT32 uOffsetByU32,
UINT32 uNumU32,
SmallVectorImpl<uint32_t> &Output) {
if (Blocks.size() == 0)
return E_FAIL;
Output.clear();
for (unsigned i = 0; i < uNumU32; i++) {
UINT32 uOffsetInBytes = (uOffsetByU32 + i) * sizeof(UINT32);
UINT32 BlockIndex = uOffsetInBytes / m_SB.BlockSize;
UINT32 ByteOffset = uOffsetInBytes % m_SB.BlockSize;
UINT32 uBlock = Blocks[BlockIndex];
IFR(GoToBeginningOfBlock(uBlock));
IFR(OffsetByU32(ByteOffset / sizeof(UINT32)));
UINT32 uData = 0;
IFR(ReadU32(&uData));
Output.push_back(uData);
}
return S_OK;
}
};
HRESULT hlsl::pdb::LoadDataFromStream(IMalloc *pMalloc, IStream *pIStream,
IDxcBlob **ppHash,
IDxcBlob **ppContainer) {
PDBReader Reader(pMalloc, pIStream);
if (ppHash) {
CComPtr<IDxcBlob> pPdbStream;
IFR(Reader.ReadWholeStream(kPdbStreamIndex, &pPdbStream));
if (pPdbStream->GetBufferSize() < sizeof(PdbStreamHeader))
return E_FAIL;
PdbStreamHeader PdbHeader = {};
memcpy(&PdbHeader, pPdbStream->GetBufferPointer(), sizeof(PdbHeader));
CComPtr<hlsl::AbstractMemoryStream> pHash;
IFR(CreateMemoryStream(pMalloc, &pHash));
ULONG uBytesWritten = 0;
IFR(pHash->Write(PdbHeader.UniqueId, sizeof(PdbHeader.UniqueId),
&uBytesWritten));
if (uBytesWritten != sizeof(PdbHeader.UniqueId))
return E_FAIL;
IFR(pHash.QueryInterface(ppHash));
}
CComPtr<IDxcBlob> pContainer;
IFR(Reader.ReadWholeStream(kDataStreamIndex, &pContainer));
if (!hlsl::IsValidDxilContainer(
(hlsl::DxilContainerHeader *)pContainer->GetBufferPointer(),
pContainer->GetBufferSize()))
return E_FAIL;
*ppContainer = pContainer.Detach();
return S_OK;
}
HRESULT hlsl::pdb::LoadDataFromStream(IMalloc *pMalloc, IStream *pIStream,
IDxcBlob **ppContainer) {
return LoadDataFromStream(pMalloc, pIStream, nullptr, ppContainer);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilUtilDbgInfoAndMisc.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilUtilDbgInfoAndMisc.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Dxil helper functions. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/HLSL/DxilConvergentName.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace hlsl;
namespace {
// Attempt to merge the two GEPs into a single GEP.
//
// If `AsCast` is non-null the merged GEP will be wrapped
// in an addrspacecast before replacing users. This allows
// merging GEPs of the form
//
// gep(addrspacecast(gep(p0, gep_args0) to p1*), gep_args1)
// into
// addrspacecast(gep(p0, gep_args0+gep_args1) to p1*)
//
Value *MergeGEP(GEPOperator *SrcGEP, GEPOperator *GEP,
AddrSpaceCastOperator *AsCast) {
IRBuilder<> Builder(GEP->getContext());
StringRef Name = "";
if (Instruction *I = dyn_cast<Instruction>(GEP)) {
Builder.SetInsertPoint(I);
Name = GEP->getName();
}
SmallVector<Value *, 8> Indices;
// Find out whether the last index in the source GEP is a sequential idx.
bool EndsWithSequential = false;
for (gep_type_iterator I = gep_type_begin(*SrcGEP), E = gep_type_end(*SrcGEP);
I != E; ++I)
EndsWithSequential = !(*I)->isStructTy();
if (EndsWithSequential) {
Value *Sum;
Value *SO1 = SrcGEP->getOperand(SrcGEP->getNumOperands() - 1);
Value *GO1 = GEP->getOperand(1);
if (SO1 == Constant::getNullValue(SO1->getType())) {
Sum = GO1;
} else if (GO1 == Constant::getNullValue(GO1->getType())) {
Sum = SO1;
} else {
// If they aren't the same type, then the input hasn't been processed
// by the loop above yet (which canonicalizes sequential index types to
// intptr_t). Just avoid transforming this until the input has been
// normalized.
if (SO1->getType() != GO1->getType())
return nullptr;
// Only do the combine when GO1 and SO1 are both constants. Only in
// this case, we are sure the cost after the merge is never more than
// that before the merge.
if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
return nullptr;
Sum = Builder.CreateAdd(SO1, GO1);
}
// Update the GEP in place if possible.
if (SrcGEP->getNumOperands() == 2 && !AsCast) {
GEP->setOperand(0, SrcGEP->getOperand(0));
GEP->setOperand(1, Sum);
return GEP;
}
Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end() - 1);
Indices.push_back(Sum);
Indices.append(GEP->op_begin() + 2, GEP->op_end());
} else if (isa<Constant>(*GEP->idx_begin()) &&
cast<Constant>(*GEP->idx_begin())->isNullValue() &&
SrcGEP->getNumOperands() != 1) {
// Otherwise we can do the fold if the first index of the GEP is a zero
Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end());
Indices.append(GEP->idx_begin() + 1, GEP->idx_end());
}
DXASSERT(!Indices.empty(), "must merge");
Value *newGEP =
Builder.CreateInBoundsGEP(nullptr, SrcGEP->getOperand(0), Indices, Name);
// Wrap the new gep in an addrspacecast if needed.
if (AsCast)
newGEP = Builder.CreateAddrSpaceCast(
newGEP, PointerType::get(GEP->getType()->getPointerElementType(),
AsCast->getDestAddressSpace()));
GEP->replaceAllUsesWith(newGEP);
if (Instruction *I = dyn_cast<Instruction>(GEP))
I->eraseFromParent();
return newGEP;
}
// Examine the gep and try to merge it when the input pointer is
// itself a gep. We handle two forms here:
//
// gep(gep(p))
// gep(addrspacecast(gep(p)))
//
// If the gep was merged successfully then return the updated value, otherwise
// return nullptr.
//
// When the gep is sucessfully merged we will delete the gep and also try to
// delete the nested gep and addrspacecast.
static Value *TryMegeWithNestedGEP(GEPOperator *GEP) {
// Sentinal value to return when we fail to merge.
Value *FailedToMerge = nullptr;
Value *Ptr = GEP->getPointerOperand();
GEPOperator *prevGEP = dyn_cast<GEPOperator>(Ptr);
AddrSpaceCastOperator *AsCast = nullptr;
// If there is no directly nested gep try looking through an addrspacecast to
// find one.
if (!prevGEP) {
AsCast = dyn_cast<AddrSpaceCastOperator>(Ptr);
if (AsCast)
prevGEP = dyn_cast<GEPOperator>(AsCast->getPointerOperand());
}
// Not a nested gep expression.
if (!prevGEP)
return FailedToMerge;
// Try merging the two geps.
Value *newGEP = MergeGEP(prevGEP, GEP, AsCast);
if (!newGEP)
return FailedToMerge;
// Delete the nested gep and addrspacecast if no more users.
if (AsCast && AsCast->user_empty() && isa<AddrSpaceCastInst>(AsCast))
cast<AddrSpaceCastInst>(AsCast)->eraseFromParent();
if (prevGEP->user_empty() && isa<GetElementPtrInst>(prevGEP))
cast<GetElementPtrInst>(prevGEP)->eraseFromParent();
return newGEP;
}
} // namespace
namespace hlsl {
namespace dxilutil {
bool MergeGepUse(Value *V) {
bool changed = false;
SmallVector<Value *, 16> worklist;
auto addUsersToWorklist = [&worklist](Value *V) {
if (!V->user_empty()) {
// Add users in reverse to the worklist, so they are processed in order
// This makes it equivalent to recursive traversal
size_t start = worklist.size();
worklist.append(V->user_begin(), V->user_end());
size_t end = worklist.size();
std::reverse(worklist.data() + start, worklist.data() + end);
}
};
addUsersToWorklist(V);
while (worklist.size()) {
V = worklist.pop_back_val();
if (isa<BitCastOperator>(V)) {
if (Value *NewV = dxilutil::TryReplaceBaseCastWithGep(V)) {
changed = true;
worklist.push_back(NewV);
} else {
// merge any GEP users of the untranslated bitcast
addUsersToWorklist(V);
}
} else if (isa<AddrSpaceCastOperator>(V)) {
addUsersToWorklist(V);
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
if (Value *newGEP = TryMegeWithNestedGEP(GEP)) {
changed = true;
worklist.push_back(newGEP);
} else {
addUsersToWorklist(GEP);
}
}
}
return changed;
}
std::unique_ptr<llvm::Module> LoadModuleFromBitcode(llvm::MemoryBuffer *MB,
llvm::LLVMContext &Ctx,
std::string &DiagStr) {
// Note: the DiagStr is not used.
auto pModule = llvm::parseBitcodeFile(MB->getMemBufferRef(), Ctx);
if (!pModule) {
return nullptr;
}
return std::unique_ptr<llvm::Module>(pModule.get().release());
}
std::unique_ptr<llvm::Module>
LoadModuleFromBitcodeLazy(std::unique_ptr<llvm::MemoryBuffer> &&MB,
llvm::LLVMContext &Ctx, std::string &DiagStr) {
// Note: the DiagStr is not used.
auto pModule = llvm::getLazyBitcodeModule(std::move(MB), Ctx, nullptr, true);
if (!pModule) {
return nullptr;
}
return std::unique_ptr<llvm::Module>(pModule.get().release());
}
std::unique_ptr<llvm::Module> LoadModuleFromBitcode(llvm::StringRef BC,
llvm::LLVMContext &Ctx,
std::string &DiagStr) {
std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf(
llvm::MemoryBuffer::getMemBuffer(BC, "", false));
return LoadModuleFromBitcode(pBitcodeBuf.get(), Ctx, DiagStr);
}
DIGlobalVariable *FindGlobalVariableDebugInfo(GlobalVariable *GV,
DebugInfoFinder &DbgInfoFinder) {
struct GlobalFinder {
GlobalVariable *GV;
bool operator()(llvm::DIGlobalVariable *const arg) const {
return arg->getVariable() == GV;
}
};
GlobalFinder F = {GV};
DebugInfoFinder::global_variable_iterator Found =
std::find_if(DbgInfoFinder.global_variables().begin(),
DbgInfoFinder.global_variables().end(), F);
if (Found != DbgInfoFinder.global_variables().end()) {
return *Found;
}
return nullptr;
}
static void EmitWarningOrErrorOnInstruction(Instruction *I, Twine Msg,
DiagnosticSeverity severity);
// If we don't have debug location and this is select/phi,
// try recursing users to find instruction with debug info.
// Only recurse phi/select and limit depth to prevent doing
// too much work if no debug location found.
static bool
EmitWarningOrErrorOnInstructionFollowPhiSelect(Instruction *I, Twine Msg,
DiagnosticSeverity severity,
unsigned depth = 0) {
if (depth > 4)
return false;
if (I->getDebugLoc().get()) {
EmitWarningOrErrorOnInstruction(I, Msg, severity);
return true;
}
if (isa<PHINode>(I) || isa<SelectInst>(I)) {
for (auto U : I->users())
if (Instruction *UI = dyn_cast<Instruction>(U))
if (EmitWarningOrErrorOnInstructionFollowPhiSelect(UI, Msg, severity,
depth + 1))
return true;
}
return false;
}
static void EmitWarningOrErrorOnInstruction(Instruction *I, Twine Msg,
DiagnosticSeverity severity) {
const DebugLoc &DL = I->getDebugLoc();
if (!DL.get() && (isa<PHINode>(I) || isa<SelectInst>(I))) {
if (EmitWarningOrErrorOnInstructionFollowPhiSelect(I, Msg, severity))
return;
}
I->getContext().diagnose(
DiagnosticInfoDxil(I->getParent()->getParent(), DL.get(), Msg, severity));
}
void EmitErrorOnInstruction(Instruction *I, Twine Msg) {
EmitWarningOrErrorOnInstruction(I, Msg, DiagnosticSeverity::DS_Error);
}
void EmitWarningOnInstruction(Instruction *I, Twine Msg) {
EmitWarningOrErrorOnInstruction(I, Msg, DiagnosticSeverity::DS_Warning);
}
static void EmitWarningOrErrorOnFunction(llvm::LLVMContext &Ctx, Function *F,
Twine Msg,
DiagnosticSeverity severity) {
DILocation *DLoc = nullptr;
if (DISubprogram *DISP = getDISubprogram(F)) {
DLoc = DILocation::get(F->getContext(), DISP->getLine(), 0, DISP,
nullptr /*InlinedAt*/);
}
Ctx.diagnose(DiagnosticInfoDxil(F, DLoc, Msg, severity));
}
void EmitErrorOnFunction(llvm::LLVMContext &Ctx, Function *F, Twine Msg) {
EmitWarningOrErrorOnFunction(Ctx, F, Msg, DiagnosticSeverity::DS_Error);
}
void EmitWarningOnFunction(llvm::LLVMContext &Ctx, Function *F, Twine Msg) {
EmitWarningOrErrorOnFunction(Ctx, F, Msg, DiagnosticSeverity::DS_Warning);
}
static void EmitWarningOrErrorOnGlobalVariable(llvm::LLVMContext &Ctx,
GlobalVariable *GV, Twine Msg,
DiagnosticSeverity severity) {
DIGlobalVariable *DIV = nullptr;
if (GV) {
Module &M = *GV->getParent();
if (hasDebugInfo(M)) {
DebugInfoFinder FinderObj;
DebugInfoFinder &Finder = FinderObj;
// Debug modules have no dxil modules. Use it if you got it.
if (M.HasDxilModule())
Finder = M.GetDxilModule().GetOrCreateDebugInfoFinder();
else
Finder.processModule(M);
DIV = FindGlobalVariableDebugInfo(GV, Finder);
}
}
Ctx.diagnose(DiagnosticInfoDxil(nullptr /*Function*/, DIV, Msg, severity));
}
void EmitErrorOnGlobalVariable(llvm::LLVMContext &Ctx, GlobalVariable *GV,
Twine Msg) {
EmitWarningOrErrorOnGlobalVariable(Ctx, GV, Msg,
DiagnosticSeverity::DS_Error);
}
void EmitWarningOnGlobalVariable(llvm::LLVMContext &Ctx, GlobalVariable *GV,
Twine Msg) {
EmitWarningOrErrorOnGlobalVariable(Ctx, GV, Msg,
DiagnosticSeverity::DS_Warning);
}
const char *kResourceMapErrorMsg =
"local resource not guaranteed to map to unique global resource.";
void EmitResMappingError(Instruction *Res) {
EmitErrorOnInstruction(Res, kResourceMapErrorMsg);
}
// Mostly just a locationless diagnostic output
static void EmitWarningOrErrorOnContext(LLVMContext &Ctx, Twine Msg,
DiagnosticSeverity severity) {
Ctx.diagnose(DiagnosticInfoDxil(nullptr /*Func*/, Msg, severity));
}
void EmitErrorOnContext(LLVMContext &Ctx, Twine Msg) {
EmitWarningOrErrorOnContext(Ctx, Msg, DiagnosticSeverity::DS_Error);
}
void EmitWarningOnContext(LLVMContext &Ctx, Twine Msg) {
EmitWarningOrErrorOnContext(Ctx, Msg, DiagnosticSeverity::DS_Warning);
}
void EmitNoteOnContext(LLVMContext &Ctx, Twine Msg) {
EmitWarningOrErrorOnContext(Ctx, Msg, DiagnosticSeverity::DS_Note);
}
Value::user_iterator mdv_users_end(Value *V) { return Value::user_iterator(); }
Value::user_iterator mdv_users_begin(Value *V) {
if (auto *L = LocalAsMetadata::getIfExists(V)) {
if (auto *MDV = MetadataAsValue::getIfExists(L->getContext(), L)) {
return MDV->user_begin();
}
}
return mdv_users_end(V);
}
static DbgValueInst *FindDbgValueInst(Value *Val) {
for (auto it = mdv_users_begin(Val), end = mdv_users_end(Val); it != end;
it++) {
if (DbgValueInst *DbgValInst = dyn_cast<DbgValueInst>(*it))
return DbgValInst;
}
return nullptr;
}
void MigrateDebugValue(Value *Old, Value *New) {
DbgValueInst *DbgValInst = FindDbgValueInst(Old);
if (DbgValInst == nullptr)
return;
DbgValInst->setOperand(
0, MetadataAsValue::get(New->getContext(), ValueAsMetadata::get(New)));
// Move the dbg value after the new instruction
if (Instruction *NewInst = dyn_cast<Instruction>(New)) {
if (NewInst->getNextNode() != DbgValInst) {
DbgValInst->removeFromParent();
DbgValInst->insertAfter(NewInst);
}
}
}
// Propagates any llvm.dbg.value instruction for a given vector
// to the elements that were used to create it through a series
// of insertelement instructions.
//
// This is used after lowering a vector-returning intrinsic.
// If we just keep the debug info on the recomposed vector,
// we will lose it when we break it apart again during later
// optimization stages.
void TryScatterDebugValueToVectorElements(Value *Val) {
if (!isa<InsertElementInst>(Val) || !Val->getType()->isVectorTy())
return;
DbgValueInst *VecDbgValInst = FindDbgValueInst(Val);
if (VecDbgValInst == nullptr)
return;
Type *ElemTy = Val->getType()->getVectorElementType();
DIBuilder DbgInfoBuilder(*VecDbgValInst->getModule());
unsigned ElemSizeInBits =
VecDbgValInst->getModule()->getDataLayout().getTypeSizeInBits(ElemTy);
DIExpression *ParentBitPiece = VecDbgValInst->getExpression();
if (ParentBitPiece != nullptr && !ParentBitPiece->isBitPiece())
ParentBitPiece = nullptr;
while (InsertElementInst *InsertElt = dyn_cast<InsertElementInst>(Val)) {
Value *NewElt = InsertElt->getOperand(1);
unsigned EltIdx = static_cast<unsigned>(
cast<ConstantInt>(InsertElt->getOperand(2))->getLimitedValue());
unsigned OffsetInBits = EltIdx * ElemSizeInBits;
if (ParentBitPiece) {
assert(OffsetInBits + ElemSizeInBits <=
ParentBitPiece->getBitPieceSize() &&
"Nested bit piece expression exceeds bounds of its parent.");
OffsetInBits += ParentBitPiece->getBitPieceOffset();
}
DIExpression *DIExpr =
DbgInfoBuilder.createBitPieceExpression(OffsetInBits, ElemSizeInBits);
// Offset is basically unused and deprecated in later LLVM versions.
// Emit it as zero otherwise later versions of the bitcode reader will drop
// the intrinsic.
DbgInfoBuilder.insertDbgValueIntrinsic(
NewElt, /* Offset */ 0, VecDbgValInst->getVariable(), DIExpr,
VecDbgValInst->getDebugLoc(), InsertElt);
Val = InsertElt->getOperand(0);
}
}
} // namespace dxilutil
} // namespace hlsl
///////////////////////////////////////////////////////////////////////////////
namespace {
class DxilLoadMetadata : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilLoadMetadata() : ModulePass(ID) {}
StringRef getPassName() const override {
return "HLSL load DxilModule from metadata";
}
bool runOnModule(Module &M) override {
if (!M.HasDxilModule()) {
(void)M.GetOrCreateDxilModule();
return true;
}
return false;
}
};
} // namespace
char DxilLoadMetadata::ID = 0;
ModulePass *llvm::createDxilLoadMetadataPass() {
return new DxilLoadMetadata();
}
INITIALIZE_PASS(DxilLoadMetadata, "hlsl-dxilload",
"HLSL load DxilModule from metadata", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilResourceBinding.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilResourceBinding.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilResourceBinding.h"
#include "dxc/DXIL/DxilCBuffer.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResource.h"
#include "dxc/DXIL/DxilResourceBase.h"
#include "dxc/DXIL/DxilSampler.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilUtil.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
using namespace llvm;
namespace hlsl {
bool DxilResourceBinding::operator==(const DxilResourceBinding &B) {
return rangeLowerBound == B.rangeLowerBound &&
rangeUpperBound == B.rangeUpperBound && spaceID == B.spaceID &&
resourceClass == B.resourceClass;
}
bool DxilResourceBinding::operator!=(const DxilResourceBinding &B) {
return !(*this == B);
}
namespace resource_helper {
// The constant is as struct with int fields.
// ShaderModel 6.6 has 4 fileds.
llvm::Constant *getAsConstant(const DxilResourceBinding &B, llvm::Type *Ty,
const ShaderModel &) {
StructType *ST = cast<StructType>(Ty);
switch (ST->getNumElements()) {
case 4: {
Constant *RawDwords[] = {
ConstantInt::get(ST->getElementType(0), B.rangeLowerBound),
ConstantInt::get(ST->getElementType(1), B.rangeUpperBound),
ConstantInt::get(ST->getElementType(2), B.spaceID),
ConstantInt::get(ST->getElementType(3), B.resourceClass)};
return ConstantStruct::get(ST, RawDwords);
} break;
default:
return nullptr;
break;
}
return nullptr;
}
DxilResourceBinding loadBindingFromConstant(const llvm::Constant &C) {
DxilResourceBinding B;
// Ty Should match C.getType().
Type *Ty = C.getType();
StructType *ST = cast<StructType>(Ty);
switch (ST->getNumElements()) {
case 4: {
if (isa<ConstantAggregateZero>(&C)) {
B.rangeLowerBound = 0;
B.rangeUpperBound = 0;
B.spaceID = 0;
B.resourceClass = 0;
} else {
const ConstantStruct *CS = cast<ConstantStruct>(&C);
const Constant *rangeLowerBound = CS->getOperand(0);
const Constant *rangeUpperBound = CS->getOperand(1);
const Constant *spaceID = CS->getOperand(2);
const Constant *resourceClass = CS->getOperand(3);
B.rangeLowerBound = cast<ConstantInt>(rangeLowerBound)->getLimitedValue();
B.rangeUpperBound = cast<ConstantInt>(rangeUpperBound)->getLimitedValue();
B.spaceID = cast<ConstantInt>(spaceID)->getLimitedValue();
B.resourceClass = cast<ConstantInt>(resourceClass)->getLimitedValue();
}
} break;
default:
B.resourceClass = (uint8_t)DXIL::ResourceClass::Invalid;
break;
}
return B;
}
DxilResourceBinding loadBindingFromCreateHandleFromBinding(
const DxilInst_CreateHandleFromBinding &createHandle, llvm::Type *Ty,
const ShaderModel &) {
Constant *B = cast<Constant>(createHandle.get_bind());
return loadBindingFromConstant(*B);
}
DxilResourceBinding loadBindingFromResourceBase(DxilResourceBase *Res) {
DxilResourceBinding B = {};
B.resourceClass = (uint8_t)DXIL::ResourceClass::Invalid;
if (!Res)
return B;
B.rangeLowerBound = Res->GetLowerBound();
B.rangeUpperBound = Res->GetUpperBound();
B.spaceID = Res->GetSpaceID();
B.resourceClass = (uint8_t)Res->GetClass();
return B;
}
} // namespace resource_helper
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilOperations.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilOperations.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Implementation of DXIL operation tables. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using std::string;
using std::vector;
namespace hlsl {
using OC = OP::OpCode;
using OCC = OP::OpCodeClass;
//------------------------------------------------------------------------------
//
// OP class const-static data and related static methods.
//
/* <py>
import hctdb_instrhelp
</py> */
/* <py::lines('OPCODE-OLOADS')>hctdb_instrhelp.get_oloads_props()</py>*/
// OPCODE-OLOADS:BEGIN
const OP::OpCodeProperty OP::m_OpCodeProps[(unsigned)OP::OpCode::NumOpCodes] = {
// OpCode OpCode name, OpCodeClass
// OpCodeClass name, void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj, function attribute
// Temporary, indexable, input, output registers void, h, f, d,
// i1, i8, i16, i32, i64, udt, obj , function attribute
{
OC::TempRegLoad,
"TempRegLoad",
OCC::TempRegLoad,
"tempRegLoad",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::TempRegStore,
"TempRegStore",
OCC::TempRegStore,
"tempRegStore",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
{
OC::MinPrecXRegLoad,
"MinPrecXRegLoad",
OCC::MinPrecXRegLoad,
"minPrecXRegLoad",
{false, true, false, false, false, false, true, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::MinPrecXRegStore,
"MinPrecXRegStore",
OCC::MinPrecXRegStore,
"minPrecXRegStore",
{false, true, false, false, false, false, true, false, false, false,
false},
Attribute::None,
},
{
OC::LoadInput,
"LoadInput",
OCC::LoadInput,
"loadInput",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::StoreOutput,
"StoreOutput",
OCC::StoreOutput,
"storeOutput",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
// Unary float void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::FAbs,
"FAbs",
OCC::Unary,
"unary",
{false, true, true, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Saturate,
"Saturate",
OCC::Unary,
"unary",
{false, true, true, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::IsNaN,
"IsNaN",
OCC::IsSpecialFloat,
"isSpecialFloat",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::IsInf,
"IsInf",
OCC::IsSpecialFloat,
"isSpecialFloat",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::IsFinite,
"IsFinite",
OCC::IsSpecialFloat,
"isSpecialFloat",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::IsNormal,
"IsNormal",
OCC::IsSpecialFloat,
"isSpecialFloat",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Cos,
"Cos",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Sin,
"Sin",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Tan,
"Tan",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Acos,
"Acos",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Asin,
"Asin",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Atan,
"Atan",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Hcos,
"Hcos",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Hsin,
"Hsin",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Htan,
"Htan",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Exp,
"Exp",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Frc,
"Frc",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Log,
"Log",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Sqrt,
"Sqrt",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Rsqrt,
"Rsqrt",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Unary float - rounding void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::Round_ne,
"Round_ne",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Round_ni,
"Round_ni",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Round_pi,
"Round_pi",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Round_z,
"Round_z",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Unary int void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::Bfrev,
"Bfrev",
OCC::Unary,
"unary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
{
OC::Countbits,
"Countbits",
OCC::UnaryBits,
"unaryBits",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
{
OC::FirstbitLo,
"FirstbitLo",
OCC::UnaryBits,
"unaryBits",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Unary uint void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::FirstbitHi,
"FirstbitHi",
OCC::UnaryBits,
"unaryBits",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Unary int void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::FirstbitSHi,
"FirstbitSHi",
OCC::UnaryBits,
"unaryBits",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Binary float void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::FMax,
"FMax",
OCC::Binary,
"binary",
{false, true, true, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::FMin,
"FMin",
OCC::Binary,
"binary",
{false, true, true, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Binary int void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::IMax,
"IMax",
OCC::Binary,
"binary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
{
OC::IMin,
"IMin",
OCC::Binary,
"binary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Binary uint void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::UMax,
"UMax",
OCC::Binary,
"binary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
{
OC::UMin,
"UMin",
OCC::Binary,
"binary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Binary int with two outputs void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::IMul,
"IMul",
OCC::BinaryWithTwoOuts,
"binaryWithTwoOuts",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Binary uint with two outputs void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::UMul,
"UMul",
OCC::BinaryWithTwoOuts,
"binaryWithTwoOuts",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::UDiv,
"UDiv",
OCC::BinaryWithTwoOuts,
"binaryWithTwoOuts",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Binary uint with carry or borrow void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::UAddc,
"UAddc",
OCC::BinaryWithCarryOrBorrow,
"binaryWithCarryOrBorrow",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::USubb,
"USubb",
OCC::BinaryWithCarryOrBorrow,
"binaryWithCarryOrBorrow",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Tertiary float void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::FMad,
"FMad",
OCC::Tertiary,
"tertiary",
{false, true, true, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Fma,
"Fma",
OCC::Tertiary,
"tertiary",
{false, false, false, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Tertiary int void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::IMad,
"IMad",
OCC::Tertiary,
"tertiary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Tertiary uint void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::UMad,
"UMad",
OCC::Tertiary,
"tertiary",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadNone,
},
// Tertiary int void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::Msad,
"Msad",
OCC::Tertiary,
"tertiary",
{false, false, false, false, false, false, false, true, true, false,
false},
Attribute::ReadNone,
},
{
OC::Ibfe,
"Ibfe",
OCC::Tertiary,
"tertiary",
{false, false, false, false, false, false, false, true, true, false,
false},
Attribute::ReadNone,
},
// Tertiary uint void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::Ubfe,
"Ubfe",
OCC::Tertiary,
"tertiary",
{false, false, false, false, false, false, false, true, true, false,
false},
Attribute::ReadNone,
},
// Quaternary void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::Bfi,
"Bfi",
OCC::Quaternary,
"quaternary",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Dot void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::Dot2,
"Dot2",
OCC::Dot2,
"dot2",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Dot3,
"Dot3",
OCC::Dot3,
"dot3",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Dot4,
"Dot4",
OCC::Dot4,
"dot4",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Resources void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::CreateHandle,
"CreateHandle",
OCC::CreateHandle,
"createHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::CBufferLoad,
"CBufferLoad",
OCC::CBufferLoad,
"cbufferLoad",
{false, true, true, true, false, true, true, true, true, false, false},
Attribute::ReadOnly,
},
{
OC::CBufferLoadLegacy,
"CBufferLoadLegacy",
OCC::CBufferLoadLegacy,
"cbufferLoadLegacy",
{false, true, true, true, false, false, true, true, true, false, false},
Attribute::ReadOnly,
},
// Resources - sample void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::Sample,
"Sample",
OCC::Sample,
"sample",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleBias,
"SampleBias",
OCC::SampleBias,
"sampleBias",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleLevel,
"SampleLevel",
OCC::SampleLevel,
"sampleLevel",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleGrad,
"SampleGrad",
OCC::SampleGrad,
"sampleGrad",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleCmp,
"SampleCmp",
OCC::SampleCmp,
"sampleCmp",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleCmpLevelZero,
"SampleCmpLevelZero",
OCC::SampleCmpLevelZero,
"sampleCmpLevelZero",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Resources void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::TextureLoad,
"TextureLoad",
OCC::TextureLoad,
"textureLoad",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::TextureStore,
"TextureStore",
OCC::TextureStore,
"textureStore",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
{
OC::BufferLoad,
"BufferLoad",
OCC::BufferLoad,
"bufferLoad",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::BufferStore,
"BufferStore",
OCC::BufferStore,
"bufferStore",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
{
OC::BufferUpdateCounter,
"BufferUpdateCounter",
OCC::BufferUpdateCounter,
"bufferUpdateCounter",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::CheckAccessFullyMapped,
"CheckAccessFullyMapped",
OCC::CheckAccessFullyMapped,
"checkAccessFullyMapped",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::GetDimensions,
"GetDimensions",
OCC::GetDimensions,
"getDimensions",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Resources - gather void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::TextureGather,
"TextureGather",
OCC::TextureGather,
"textureGather",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::TextureGatherCmp,
"TextureGatherCmp",
OCC::TextureGatherCmp,
"textureGatherCmp",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadOnly,
},
// Resources - sample void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::Texture2DMSGetSamplePosition,
"Texture2DMSGetSamplePosition",
OCC::Texture2DMSGetSamplePosition,
"texture2DMSGetSamplePosition",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RenderTargetGetSamplePosition,
"RenderTargetGetSamplePosition",
OCC::RenderTargetGetSamplePosition,
"renderTargetGetSamplePosition",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RenderTargetGetSampleCount,
"RenderTargetGetSampleCount",
OCC::RenderTargetGetSampleCount,
"renderTargetGetSampleCount",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Synchronization void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::AtomicBinOp,
"AtomicBinOp",
OCC::AtomicBinOp,
"atomicBinOp",
{false, false, false, false, false, false, false, true, true, false,
false},
Attribute::None,
},
{
OC::AtomicCompareExchange,
"AtomicCompareExchange",
OCC::AtomicCompareExchange,
"atomicCompareExchange",
{false, false, false, false, false, false, false, true, true, false,
false},
Attribute::None,
},
{
OC::Barrier,
"Barrier",
OCC::Barrier,
"barrier",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoDuplicate,
},
// Derivatives void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::CalculateLOD,
"CalculateLOD",
OCC::CalculateLOD,
"calculateLOD",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Pixel shader void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::Discard,
"Discard",
OCC::Discard,
"discard",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Derivatives void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::DerivCoarseX,
"DerivCoarseX",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::DerivCoarseY,
"DerivCoarseY",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::DerivFineX,
"DerivFineX",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::DerivFineY,
"DerivFineY",
OCC::Unary,
"unary",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Pixel shader void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::EvalSnapped,
"EvalSnapped",
OCC::EvalSnapped,
"evalSnapped",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::EvalSampleIndex,
"EvalSampleIndex",
OCC::EvalSampleIndex,
"evalSampleIndex",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::EvalCentroid,
"EvalCentroid",
OCC::EvalCentroid,
"evalCentroid",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::SampleIndex,
"SampleIndex",
OCC::SampleIndex,
"sampleIndex",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::Coverage,
"Coverage",
OCC::Coverage,
"coverage",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::InnerCoverage,
"InnerCoverage",
OCC::InnerCoverage,
"innerCoverage",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Compute/Mesh/Amplification/Node shader void, h, f, d, i1,
// i8, i16, i32, i64, udt, obj , function attribute
{
OC::ThreadId,
"ThreadId",
OCC::ThreadId,
"threadId",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::GroupId,
"GroupId",
OCC::GroupId,
"groupId",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::ThreadIdInGroup,
"ThreadIdInGroup",
OCC::ThreadIdInGroup,
"threadIdInGroup",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::FlattenedThreadIdInGroup,
"FlattenedThreadIdInGroup",
OCC::FlattenedThreadIdInGroup,
"flattenedThreadIdInGroup",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Geometry shader void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::EmitStream,
"EmitStream",
OCC::EmitStream,
"emitStream",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::CutStream,
"CutStream",
OCC::CutStream,
"cutStream",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::EmitThenCutStream,
"EmitThenCutStream",
OCC::EmitThenCutStream,
"emitThenCutStream",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::GSInstanceID,
"GSInstanceID",
OCC::GSInstanceID,
"gsInstanceID",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Double precision void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::MakeDouble,
"MakeDouble",
OCC::MakeDouble,
"makeDouble",
{false, false, false, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::SplitDouble,
"SplitDouble",
OCC::SplitDouble,
"splitDouble",
{false, false, false, true, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Domain and hull shader void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::LoadOutputControlPoint,
"LoadOutputControlPoint",
OCC::LoadOutputControlPoint,
"loadOutputControlPoint",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::LoadPatchConstant,
"LoadPatchConstant",
OCC::LoadPatchConstant,
"loadPatchConstant",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
// Domain shader void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::DomainLocation,
"DomainLocation",
OCC::DomainLocation,
"domainLocation",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Hull shader void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::StorePatchConstant,
"StorePatchConstant",
OCC::StorePatchConstant,
"storePatchConstant",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
{
OC::OutputControlPointID,
"OutputControlPointID",
OCC::OutputControlPointID,
"outputControlPointID",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Hull, Domain and Geometry shaders void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::PrimitiveID,
"PrimitiveID",
OCC::PrimitiveID,
"primitiveID",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Other void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::CycleCounterLegacy,
"CycleCounterLegacy",
OCC::CycleCounterLegacy,
"cycleCounterLegacy",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Wave void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::WaveIsFirstLane,
"WaveIsFirstLane",
OCC::WaveIsFirstLane,
"waveIsFirstLane",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WaveGetLaneIndex,
"WaveGetLaneIndex",
OCC::WaveGetLaneIndex,
"waveGetLaneIndex",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::WaveGetLaneCount,
"WaveGetLaneCount",
OCC::WaveGetLaneCount,
"waveGetLaneCount",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::WaveAnyTrue,
"WaveAnyTrue",
OCC::WaveAnyTrue,
"waveAnyTrue",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WaveAllTrue,
"WaveAllTrue",
OCC::WaveAllTrue,
"waveAllTrue",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WaveActiveAllEqual,
"WaveActiveAllEqual",
OCC::WaveActiveAllEqual,
"waveActiveAllEqual",
{false, true, true, true, true, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveActiveBallot,
"WaveActiveBallot",
OCC::WaveActiveBallot,
"waveActiveBallot",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WaveReadLaneAt,
"WaveReadLaneAt",
OCC::WaveReadLaneAt,
"waveReadLaneAt",
{false, true, true, true, true, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveReadLaneFirst,
"WaveReadLaneFirst",
OCC::WaveReadLaneFirst,
"waveReadLaneFirst",
{false, true, true, true, true, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveActiveOp,
"WaveActiveOp",
OCC::WaveActiveOp,
"waveActiveOp",
{false, true, true, true, true, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveActiveBit,
"WaveActiveBit",
OCC::WaveActiveBit,
"waveActiveBit",
{false, false, false, false, false, true, true, true, true, false,
false},
Attribute::None,
},
{
OC::WavePrefixOp,
"WavePrefixOp",
OCC::WavePrefixOp,
"wavePrefixOp",
{false, true, true, true, false, true, true, true, true, false, false},
Attribute::None,
},
// Quad Wave Ops void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::QuadReadLaneAt,
"QuadReadLaneAt",
OCC::QuadReadLaneAt,
"quadReadLaneAt",
{false, true, true, true, true, true, true, true, true, false, false},
Attribute::None,
},
{
OC::QuadOp,
"QuadOp",
OCC::QuadOp,
"quadOp",
{false, true, true, true, false, true, true, true, true, false, false},
Attribute::None,
},
// Bitcasts with different sizes void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::BitcastI16toF16,
"BitcastI16toF16",
OCC::BitcastI16toF16,
"bitcastI16toF16",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::BitcastF16toI16,
"BitcastF16toI16",
OCC::BitcastF16toI16,
"bitcastF16toI16",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::BitcastI32toF32,
"BitcastI32toF32",
OCC::BitcastI32toF32,
"bitcastI32toF32",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::BitcastF32toI32,
"BitcastF32toI32",
OCC::BitcastF32toI32,
"bitcastF32toI32",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::BitcastI64toF64,
"BitcastI64toF64",
OCC::BitcastI64toF64,
"bitcastI64toF64",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::BitcastF64toI64,
"BitcastF64toI64",
OCC::BitcastF64toI64,
"bitcastF64toI64",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Legacy floating-point void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::LegacyF32ToF16,
"LegacyF32ToF16",
OCC::LegacyF32ToF16,
"legacyF32ToF16",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::LegacyF16ToF32,
"LegacyF16ToF32",
OCC::LegacyF16ToF32,
"legacyF16ToF32",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Double precision void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::LegacyDoubleToFloat,
"LegacyDoubleToFloat",
OCC::LegacyDoubleToFloat,
"legacyDoubleToFloat",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::LegacyDoubleToSInt32,
"LegacyDoubleToSInt32",
OCC::LegacyDoubleToSInt32,
"legacyDoubleToSInt32",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::LegacyDoubleToUInt32,
"LegacyDoubleToUInt32",
OCC::LegacyDoubleToUInt32,
"legacyDoubleToUInt32",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Wave void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::WaveAllBitCount,
"WaveAllBitCount",
OCC::WaveAllOp,
"waveAllOp",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WavePrefixBitCount,
"WavePrefixBitCount",
OCC::WavePrefixOp,
"wavePrefixOp",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Pixel shader void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::AttributeAtVertex,
"AttributeAtVertex",
OCC::AttributeAtVertex,
"attributeAtVertex",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
// Graphics shader void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::ViewID,
"ViewID",
OCC::ViewID,
"viewID",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Resources void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::RawBufferLoad,
"RawBufferLoad",
OCC::RawBufferLoad,
"rawBufferLoad",
{false, true, true, true, false, false, true, true, true, false, false},
Attribute::ReadOnly,
},
{
OC::RawBufferStore,
"RawBufferStore",
OCC::RawBufferStore,
"rawBufferStore",
{false, true, true, true, false, false, true, true, true, false, false},
Attribute::None,
},
// Raytracing object space uint System Values void, h, f, d, i1,
// i8, i16, i32, i64, udt, obj , function attribute
{
OC::InstanceID,
"InstanceID",
OCC::InstanceID,
"instanceID",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::InstanceIndex,
"InstanceIndex",
OCC::InstanceIndex,
"instanceIndex",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Raytracing hit uint System Values void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::HitKind,
"HitKind",
OCC::HitKind,
"hitKind",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Raytracing uint System Values void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::RayFlags,
"RayFlags",
OCC::RayFlags,
"rayFlags",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Ray Dispatch Arguments void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::DispatchRaysIndex,
"DispatchRaysIndex",
OCC::DispatchRaysIndex,
"dispatchRaysIndex",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::DispatchRaysDimensions,
"DispatchRaysDimensions",
OCC::DispatchRaysDimensions,
"dispatchRaysDimensions",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Ray Vectors void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::WorldRayOrigin,
"WorldRayOrigin",
OCC::WorldRayOrigin,
"worldRayOrigin",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::WorldRayDirection,
"WorldRayDirection",
OCC::WorldRayDirection,
"worldRayDirection",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Ray object space Vectors void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::ObjectRayOrigin,
"ObjectRayOrigin",
OCC::ObjectRayOrigin,
"objectRayOrigin",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::ObjectRayDirection,
"ObjectRayDirection",
OCC::ObjectRayDirection,
"objectRayDirection",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Ray Transforms void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::ObjectToWorld,
"ObjectToWorld",
OCC::ObjectToWorld,
"objectToWorld",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::WorldToObject,
"WorldToObject",
OCC::WorldToObject,
"worldToObject",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// RayT void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::RayTMin,
"RayTMin",
OCC::RayTMin,
"rayTMin",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::RayTCurrent,
"RayTCurrent",
OCC::RayTCurrent,
"rayTCurrent",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// AnyHit Terminals void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::IgnoreHit,
"IgnoreHit",
OCC::IgnoreHit,
"ignoreHit",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoReturn,
},
{
OC::AcceptHitAndEndSearch,
"AcceptHitAndEndSearch",
OCC::AcceptHitAndEndSearch,
"acceptHitAndEndSearch",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoReturn,
},
// Indirect Shader Invocation void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::TraceRay,
"TraceRay",
OCC::TraceRay,
"traceRay",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::None,
},
{
OC::ReportHit,
"ReportHit",
OCC::ReportHit,
"reportHit",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::None,
},
{
OC::CallShader,
"CallShader",
OCC::CallShader,
"callShader",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::None,
},
// Library create handle from resource struct (like HL intrinsic) void, h,
// f, d, i1, i8, i16, i32, i64, udt, obj , function
// attribute
{
OC::CreateHandleForLib,
"CreateHandleForLib",
OCC::CreateHandleForLib,
"createHandleForLib",
{false, false, false, false, false, false, false, false, false, false,
true},
Attribute::ReadOnly,
},
// Raytracing object space uint System Values void, h, f, d, i1,
// i8, i16, i32, i64, udt, obj , function attribute
{
OC::PrimitiveIndex,
"PrimitiveIndex",
OCC::PrimitiveIndex,
"primitiveIndex",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Dot product with accumulate void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::Dot2AddHalf,
"Dot2AddHalf",
OCC::Dot2AddHalf,
"dot2AddHalf",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::Dot4AddI8Packed,
"Dot4AddI8Packed",
OCC::Dot4AddPacked,
"dot4AddPacked",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::Dot4AddU8Packed,
"Dot4AddU8Packed",
OCC::Dot4AddPacked,
"dot4AddPacked",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Wave void, h, f, d, i1, i8, i16, i32, i64, udt,
// obj , function attribute
{
OC::WaveMatch,
"WaveMatch",
OCC::WaveMatch,
"waveMatch",
{false, true, true, true, false, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveMultiPrefixOp,
"WaveMultiPrefixOp",
OCC::WaveMultiPrefixOp,
"waveMultiPrefixOp",
{false, true, true, true, false, true, true, true, true, false, false},
Attribute::None,
},
{
OC::WaveMultiPrefixBitCount,
"WaveMultiPrefixBitCount",
OCC::WaveMultiPrefixBitCount,
"waveMultiPrefixBitCount",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Mesh shader instructions void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::SetMeshOutputCounts,
"SetMeshOutputCounts",
OCC::SetMeshOutputCounts,
"setMeshOutputCounts",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::EmitIndices,
"EmitIndices",
OCC::EmitIndices,
"emitIndices",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::GetMeshPayload,
"GetMeshPayload",
OCC::GetMeshPayload,
"getMeshPayload",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::ReadOnly,
},
{
OC::StoreVertexOutput,
"StoreVertexOutput",
OCC::StoreVertexOutput,
"storeVertexOutput",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
{
OC::StorePrimitiveOutput,
"StorePrimitiveOutput",
OCC::StorePrimitiveOutput,
"storePrimitiveOutput",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
// Amplification shader instructions void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::DispatchMesh,
"DispatchMesh",
OCC::DispatchMesh,
"dispatchMesh",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::None,
},
// Sampler Feedback void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::WriteSamplerFeedback,
"WriteSamplerFeedback",
OCC::WriteSamplerFeedback,
"writeSamplerFeedback",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WriteSamplerFeedbackBias,
"WriteSamplerFeedbackBias",
OCC::WriteSamplerFeedbackBias,
"writeSamplerFeedbackBias",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WriteSamplerFeedbackLevel,
"WriteSamplerFeedbackLevel",
OCC::WriteSamplerFeedbackLevel,
"writeSamplerFeedbackLevel",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::WriteSamplerFeedbackGrad,
"WriteSamplerFeedbackGrad",
OCC::WriteSamplerFeedbackGrad,
"writeSamplerFeedbackGrad",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Inline Ray Query void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::AllocateRayQuery,
"AllocateRayQuery",
OCC::AllocateRayQuery,
"allocateRayQuery",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_TraceRayInline,
"RayQuery_TraceRayInline",
OCC::RayQuery_TraceRayInline,
"rayQuery_TraceRayInline",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_Proceed,
"RayQuery_Proceed",
OCC::RayQuery_Proceed,
"rayQuery_Proceed",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_Abort,
"RayQuery_Abort",
OCC::RayQuery_Abort,
"rayQuery_Abort",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_CommitNonOpaqueTriangleHit,
"RayQuery_CommitNonOpaqueTriangleHit",
OCC::RayQuery_CommitNonOpaqueTriangleHit,
"rayQuery_CommitNonOpaqueTriangleHit",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_CommitProceduralPrimitiveHit,
"RayQuery_CommitProceduralPrimitiveHit",
OCC::RayQuery_CommitProceduralPrimitiveHit,
"rayQuery_CommitProceduralPrimitiveHit",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::RayQuery_CommittedStatus,
"RayQuery_CommittedStatus",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateType,
"RayQuery_CandidateType",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateObjectToWorld3x4,
"RayQuery_CandidateObjectToWorld3x4",
OCC::RayQuery_StateMatrix,
"rayQuery_StateMatrix",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateWorldToObject3x4,
"RayQuery_CandidateWorldToObject3x4",
OCC::RayQuery_StateMatrix,
"rayQuery_StateMatrix",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedObjectToWorld3x4,
"RayQuery_CommittedObjectToWorld3x4",
OCC::RayQuery_StateMatrix,
"rayQuery_StateMatrix",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedWorldToObject3x4,
"RayQuery_CommittedWorldToObject3x4",
OCC::RayQuery_StateMatrix,
"rayQuery_StateMatrix",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateProceduralPrimitiveNonOpaque,
"RayQuery_CandidateProceduralPrimitiveNonOpaque",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateTriangleFrontFace,
"RayQuery_CandidateTriangleFrontFace",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedTriangleFrontFace,
"RayQuery_CommittedTriangleFrontFace",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateTriangleBarycentrics,
"RayQuery_CandidateTriangleBarycentrics",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedTriangleBarycentrics,
"RayQuery_CommittedTriangleBarycentrics",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_RayFlags,
"RayQuery_RayFlags",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_WorldRayOrigin,
"RayQuery_WorldRayOrigin",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_WorldRayDirection,
"RayQuery_WorldRayDirection",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_RayTMin,
"RayQuery_RayTMin",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateTriangleRayT,
"RayQuery_CandidateTriangleRayT",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedRayT,
"RayQuery_CommittedRayT",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateInstanceIndex,
"RayQuery_CandidateInstanceIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateInstanceID,
"RayQuery_CandidateInstanceID",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateGeometryIndex,
"RayQuery_CandidateGeometryIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidatePrimitiveIndex,
"RayQuery_CandidatePrimitiveIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateObjectRayOrigin,
"RayQuery_CandidateObjectRayOrigin",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CandidateObjectRayDirection,
"RayQuery_CandidateObjectRayDirection",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedInstanceIndex,
"RayQuery_CommittedInstanceIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedInstanceID,
"RayQuery_CommittedInstanceID",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedGeometryIndex,
"RayQuery_CommittedGeometryIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedPrimitiveIndex,
"RayQuery_CommittedPrimitiveIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedObjectRayOrigin,
"RayQuery_CommittedObjectRayOrigin",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedObjectRayDirection,
"RayQuery_CommittedObjectRayDirection",
OCC::RayQuery_StateVector,
"rayQuery_StateVector",
{false, false, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Raytracing object space uint System Values, raytracing tier 1.1 void, h,
// f, d, i1, i8, i16, i32, i64, udt, obj , function
// attribute
{
OC::GeometryIndex,
"GeometryIndex",
OCC::GeometryIndex,
"geometryIndex",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
// Inline Ray Query void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::RayQuery_CandidateInstanceContributionToHitGroupIndex,
"RayQuery_CandidateInstanceContributionToHitGroupIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
{
OC::RayQuery_CommittedInstanceContributionToHitGroupIndex,
"RayQuery_CommittedInstanceContributionToHitGroupIndex",
OCC::RayQuery_StateScalar,
"rayQuery_StateScalar",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadOnly,
},
// Get handle from heap void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::AnnotateHandle,
"AnnotateHandle",
OCC::AnnotateHandle,
"annotateHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::CreateHandleFromBinding,
"CreateHandleFromBinding",
OCC::CreateHandleFromBinding,
"createHandleFromBinding",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::CreateHandleFromHeap,
"CreateHandleFromHeap",
OCC::CreateHandleFromHeap,
"createHandleFromHeap",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Unpacking intrinsics void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::Unpack4x8,
"Unpack4x8",
OCC::Unpack4x8,
"unpack4x8",
{false, false, false, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
// Packing intrinsics void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::Pack4x8,
"Pack4x8",
OCC::Pack4x8,
"pack4x8",
{false, false, false, false, false, false, true, true, false, false,
false},
Attribute::ReadNone,
},
// Helper Lanes void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::IsHelperLane,
"IsHelperLane",
OCC::IsHelperLane,
"isHelperLane",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Quad Wave Ops void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::QuadVote,
"QuadVote",
OCC::QuadVote,
"quadVote",
{false, false, false, false, true, false, false, false, false, false,
false},
Attribute::None,
},
// Resources - gather void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::TextureGatherRaw,
"TextureGatherRaw",
OCC::TextureGatherRaw,
"textureGatherRaw",
{false, false, false, false, false, false, true, true, true, false,
false},
Attribute::ReadOnly,
},
// Resources - sample void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::SampleCmpLevel,
"SampleCmpLevel",
OCC::SampleCmpLevel,
"sampleCmpLevel",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Resources void, h, f, d, i1, i8, i16, i32, i64,
// udt, obj , function attribute
{
OC::TextureStoreSample,
"TextureStoreSample",
OCC::TextureStoreSample,
"textureStoreSample",
{false, true, true, false, false, false, true, true, false, false,
false},
Attribute::None,
},
// void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute
{
OC::Reserved0,
"Reserved0",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved1,
"Reserved1",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved2,
"Reserved2",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved3,
"Reserved3",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved4,
"Reserved4",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved5,
"Reserved5",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved6,
"Reserved6",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved7,
"Reserved7",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved8,
"Reserved8",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved9,
"Reserved9",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved10,
"Reserved10",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::Reserved11,
"Reserved11",
OCC::Reserved,
"reserved",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Create/Annotate Node Handles void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::AllocateNodeOutputRecords,
"AllocateNodeOutputRecords",
OCC::AllocateNodeOutputRecords,
"allocateNodeOutputRecords",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Get Pointer to Node Record in Address Space 6 void, h, f, d,
// i1, i8, i16, i32, i64, udt, obj , function attribute
{
OC::GetNodeRecordPtr,
"GetNodeRecordPtr",
OCC::GetNodeRecordPtr,
"getNodeRecordPtr",
{false, false, false, false, false, false, false, false, false, true,
false},
Attribute::ReadNone,
},
// Work Graph intrinsics void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::IncrementOutputCount,
"IncrementOutputCount",
OCC::IncrementOutputCount,
"incrementOutputCount",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::OutputComplete,
"OutputComplete",
OCC::OutputComplete,
"outputComplete",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
{
OC::GetInputRecordCount,
"GetInputRecordCount",
OCC::GetInputRecordCount,
"getInputRecordCount",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::FinishedCrossGroupSharing,
"FinishedCrossGroupSharing",
OCC::FinishedCrossGroupSharing,
"finishedCrossGroupSharing",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::None,
},
// Synchronization void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::BarrierByMemoryType,
"BarrierByMemoryType",
OCC::BarrierByMemoryType,
"barrierByMemoryType",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoDuplicate,
},
{
OC::BarrierByMemoryHandle,
"BarrierByMemoryHandle",
OCC::BarrierByMemoryHandle,
"barrierByMemoryHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoDuplicate,
},
{
OC::BarrierByNodeRecordHandle,
"BarrierByNodeRecordHandle",
OCC::BarrierByNodeRecordHandle,
"barrierByNodeRecordHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::NoDuplicate,
},
// Create/Annotate Node Handles void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::CreateNodeOutputHandle,
"CreateNodeOutputHandle",
OCC::createNodeOutputHandle,
"createNodeOutputHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::IndexNodeHandle,
"IndexNodeHandle",
OCC::IndexNodeHandle,
"indexNodeHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::AnnotateNodeHandle,
"AnnotateNodeHandle",
OCC::AnnotateNodeHandle,
"annotateNodeHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::CreateNodeInputRecordHandle,
"CreateNodeInputRecordHandle",
OCC::CreateNodeInputRecordHandle,
"createNodeInputRecordHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
{
OC::AnnotateNodeRecordHandle,
"AnnotateNodeRecordHandle",
OCC::AnnotateNodeRecordHandle,
"annotateNodeRecordHandle",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadNone,
},
// Work Graph intrinsics void, h, f, d, i1, i8, i16,
// i32, i64, udt, obj , function attribute
{
OC::NodeOutputIsValid,
"NodeOutputIsValid",
OCC::NodeOutputIsValid,
"nodeOutputIsValid",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::GetRemainingRecursionLevels,
"GetRemainingRecursionLevels",
OCC::GetRemainingRecursionLevels,
"getRemainingRecursionLevels",
{true, false, false, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Comparison Samples void, h, f, d, i1, i8, i16, i32,
// i64, udt, obj , function attribute
{
OC::SampleCmpGrad,
"SampleCmpGrad",
OCC::SampleCmpGrad,
"sampleCmpGrad",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
{
OC::SampleCmpBias,
"SampleCmpBias",
OCC::SampleCmpBias,
"sampleCmpBias",
{false, true, true, false, false, false, false, false, false, false,
false},
Attribute::ReadOnly,
},
// Extended Command Information void, h, f, d, i1, i8,
// i16, i32, i64, udt, obj , function attribute
{
OC::StartVertexLocation,
"StartVertexLocation",
OCC::StartVertexLocation,
"startVertexLocation",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
{
OC::StartInstanceLocation,
"StartInstanceLocation",
OCC::StartInstanceLocation,
"startInstanceLocation",
{false, false, false, false, false, false, false, true, false, false,
false},
Attribute::ReadNone,
},
};
// OPCODE-OLOADS:END
const char *OP::m_OverloadTypeName[kNumTypeOverloads] = {
"void", "f16", "f32", "f64", "i1", "i8",
"i16", "i32", "i64", "udt", "obj", // These should not be used
};
const char *OP::m_NamePrefix = "dx.op.";
const char *OP::m_TypePrefix = "dx.types.";
const char *OP::m_MatrixTypePrefix = "class.matrix."; // Allowed in library
// Keep sync with DXIL::AtomicBinOpCode
static const char *AtomicBinOpCodeName[] = {
"AtomicAdd", "AtomicAnd", "AtomicOr", "AtomicXor", "AtomicIMin",
"AtomicIMax", "AtomicUMin", "AtomicUMax", "AtomicExchange",
"AtomicInvalid" // Must be last.
};
unsigned OP::GetTypeSlot(Type *pType) {
Type::TypeID T = pType->getTypeID();
switch (T) {
case Type::VoidTyID:
return 0;
case Type::HalfTyID:
return 1;
case Type::FloatTyID:
return 2;
case Type::DoubleTyID:
return 3;
case Type::IntegerTyID: {
IntegerType *pIT = dyn_cast<IntegerType>(pType);
unsigned Bits = pIT->getBitWidth();
switch (Bits) {
case 1:
return 4;
case 8:
return 5;
case 16:
return 6;
case 32:
return 7;
case 64:
return 8;
}
llvm_unreachable("Invalid Bits size");
}
case Type::PointerTyID: {
pType = cast<PointerType>(pType)->getElementType();
if (pType->isStructTy())
return kUserDefineTypeSlot;
DXASSERT(!pType->isPointerTy(), "pointer-to-pointer type unsupported");
return GetTypeSlot(pType);
}
case Type::StructTyID:
return kObjectTypeSlot;
default:
break;
}
return UINT_MAX;
}
const char *OP::GetOverloadTypeName(unsigned TypeSlot) {
DXASSERT(TypeSlot < kUserDefineTypeSlot, "otherwise caller passed OOB index");
return m_OverloadTypeName[TypeSlot];
}
llvm::StringRef OP::GetTypeName(Type *Ty, std::string &str) {
unsigned TypeSlot = OP::GetTypeSlot(Ty);
if (TypeSlot < kUserDefineTypeSlot) {
return GetOverloadTypeName(TypeSlot);
} else if (TypeSlot == kUserDefineTypeSlot) {
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
StructType *ST = cast<StructType>(Ty);
return ST->getStructName();
} else if (TypeSlot == kObjectTypeSlot) {
StructType *ST = cast<StructType>(Ty);
return ST->getStructName();
} else {
raw_string_ostream os(str);
Ty->print(os);
os.flush();
return str;
}
}
llvm::StringRef OP::ConstructOverloadName(Type *Ty, DXIL::OpCode opCode,
std::string &funcNameStorage) {
if (Ty == Type::getVoidTy(Ty->getContext())) {
funcNameStorage =
(Twine(OP::m_NamePrefix) + Twine(GetOpCodeClassName(opCode))).str();
} else {
funcNameStorage =
(Twine(OP::m_NamePrefix) + Twine(GetOpCodeClassName(opCode)) + "." +
GetTypeName(Ty, funcNameStorage))
.str();
}
return funcNameStorage;
}
const char *OP::GetOpCodeName(OpCode opCode) {
return m_OpCodeProps[(unsigned)opCode].pOpCodeName;
}
const char *OP::GetAtomicOpName(DXIL::AtomicBinOpCode OpCode) {
unsigned opcode = static_cast<unsigned>(OpCode);
DXASSERT_LOCALVAR(
opcode, opcode < static_cast<unsigned>(DXIL::AtomicBinOpCode::Invalid),
"otherwise caller passed OOB index");
return AtomicBinOpCodeName[static_cast<unsigned>(OpCode)];
}
OP::OpCodeClass OP::GetOpCodeClass(OpCode opCode) {
return m_OpCodeProps[(unsigned)opCode].opCodeClass;
}
const char *OP::GetOpCodeClassName(OpCode opCode) {
return m_OpCodeProps[(unsigned)opCode].pOpCodeClassName;
}
llvm::Attribute::AttrKind OP::GetMemAccessAttr(OpCode opCode) {
return m_OpCodeProps[(unsigned)opCode].FuncAttr;
}
bool OP::IsOverloadLegal(OpCode opCode, Type *pType) {
if (!pType)
return false;
if (opCode == OpCode::NumOpCodes)
return false;
unsigned TypeSlot = GetTypeSlot(pType);
return TypeSlot != UINT_MAX &&
m_OpCodeProps[(unsigned)opCode].bAllowOverload[TypeSlot];
}
bool OP::CheckOpCodeTable() {
for (unsigned i = 0; i < (unsigned)OpCode::NumOpCodes; i++) {
if ((unsigned)m_OpCodeProps[i].opCode != i)
return false;
}
return true;
}
bool OP::IsDxilOpFuncName(StringRef name) {
return name.startswith(OP::m_NamePrefix);
}
bool OP::IsDxilOpFunc(const llvm::Function *F) {
// Test for null to allow IsDxilOpFunc(Call.getCalledFunc()) to be resilient
// to indirect calls
if (F == nullptr || !F->hasName())
return false;
return IsDxilOpFuncName(F->getName());
}
bool OP::IsDxilOpTypeName(StringRef name) {
return name.startswith(m_TypePrefix) || name.startswith(m_MatrixTypePrefix);
}
bool OP::IsDxilOpType(llvm::StructType *ST) {
if (!ST->hasName())
return false;
StringRef Name = ST->getName();
return IsDxilOpTypeName(Name);
}
bool OP::IsDupDxilOpType(llvm::StructType *ST) {
if (!ST->hasName())
return false;
StringRef Name = ST->getName();
if (!IsDxilOpTypeName(Name))
return false;
size_t DotPos = Name.rfind('.');
if (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
!isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
return false;
return true;
}
StructType *OP::GetOriginalDxilOpType(llvm::StructType *ST, llvm::Module &M) {
DXASSERT(IsDupDxilOpType(ST), "else should not call GetOriginalDxilOpType");
StringRef Name = ST->getName();
size_t DotPos = Name.rfind('.');
StructType *OriginalST = M.getTypeByName(Name.substr(0, DotPos));
DXASSERT(OriginalST, "else name collison without original type");
DXASSERT(ST->isLayoutIdentical(OriginalST),
"else invalid layout for dxil types");
return OriginalST;
}
bool OP::IsDxilOpFuncCallInst(const llvm::Instruction *I) {
const CallInst *CI = dyn_cast<CallInst>(I);
if (CI == nullptr)
return false;
return IsDxilOpFunc(CI->getCalledFunction());
}
bool OP::IsDxilOpFuncCallInst(const llvm::Instruction *I, OpCode opcode) {
if (!IsDxilOpFuncCallInst(I))
return false;
return (unsigned)getOpCode(I) == (unsigned)opcode;
}
OP::OpCode OP::getOpCode(const llvm::Instruction *I) {
auto *OpConst = llvm::dyn_cast<llvm::ConstantInt>(I->getOperand(0));
if (!OpConst)
return OpCode::NumOpCodes;
uint64_t OpCodeVal = OpConst->getZExtValue();
if (OpCodeVal >= static_cast<uint64_t>(OP::OpCode::NumOpCodes))
return OP::OpCode::NumOpCodes;
return static_cast<OP::OpCode>(OpCodeVal);
}
OP::OpCode OP::GetDxilOpFuncCallInst(const llvm::Instruction *I) {
DXASSERT(IsDxilOpFuncCallInst(I),
"else caller didn't call IsDxilOpFuncCallInst to check");
return getOpCode(I);
}
bool OP::IsDxilOpWave(OpCode C) {
unsigned op = (unsigned)C;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-WAVE')>hctdb_instrhelp.get_instrs_pred("op", "is_wave")</py>*/
// clang-format on
// OPCODE-WAVE:BEGIN
// Instructions: WaveIsFirstLane=110, WaveGetLaneIndex=111,
// WaveGetLaneCount=112, WaveAnyTrue=113, WaveAllTrue=114,
// WaveActiveAllEqual=115, WaveActiveBallot=116, WaveReadLaneAt=117,
// WaveReadLaneFirst=118, WaveActiveOp=119, WaveActiveBit=120,
// WavePrefixOp=121, QuadReadLaneAt=122, QuadOp=123, WaveAllBitCount=135,
// WavePrefixBitCount=136, WaveMatch=165, WaveMultiPrefixOp=166,
// WaveMultiPrefixBitCount=167, QuadVote=222
return (110 <= op && op <= 123) || (135 <= op && op <= 136) ||
(165 <= op && op <= 167) || op == 222;
// OPCODE-WAVE:END
}
bool OP::IsDxilOpGradient(OpCode C) {
unsigned op = (unsigned)C;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-GRADIENT')>hctdb_instrhelp.get_instrs_pred("op", "is_gradient")</py>*/
// clang-format on
// OPCODE-GRADIENT:BEGIN
// Instructions: Sample=60, SampleBias=61, SampleCmp=64, CalculateLOD=81,
// DerivCoarseX=83, DerivCoarseY=84, DerivFineX=85, DerivFineY=86,
// WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175, SampleCmpBias=255
return (60 <= op && op <= 61) || op == 64 || op == 81 ||
(83 <= op && op <= 86) || (174 <= op && op <= 175) || op == 255;
// OPCODE-GRADIENT:END
}
bool OP::IsDxilOpFeedback(OpCode C) {
unsigned op = (unsigned)C;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-FEEDBACK')>hctdb_instrhelp.get_instrs_pred("op", "is_feedback")</py>*/
// clang-format on
// OPCODE-FEEDBACK:BEGIN
// Instructions: WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175,
// WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177
return (174 <= op && op <= 177);
// OPCODE-FEEDBACK:END
}
bool OP::IsDxilOpBarrier(OpCode C) {
unsigned op = (unsigned)C;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-BARRIER')>hctdb_instrhelp.get_instrs_pred("op", "is_barrier")</py>*/
// clang-format on
// OPCODE-BARRIER:BEGIN
// Instructions: Barrier=80, BarrierByMemoryType=244,
// BarrierByMemoryHandle=245, BarrierByNodeRecordHandle=246
return op == 80 || (244 <= op && op <= 246);
// OPCODE-BARRIER:END
}
static unsigned MaskMemoryTypeFlagsIfAllowed(unsigned memoryTypeFlags,
unsigned allowedMask) {
// If the memory type is AllMemory, masking inapplicable flags is allowed.
if (memoryTypeFlags != (unsigned)DXIL::MemoryTypeFlag::AllMemory)
return memoryTypeFlags;
return memoryTypeFlags & allowedMask;
}
bool OP::BarrierRequiresGroup(const llvm::CallInst *CI) {
OpCode opcode = OP::GetDxilOpFuncCallInst(CI);
switch (opcode) {
case OpCode::Barrier: {
DxilInst_Barrier barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_barrierMode())) {
unsigned mode = barrier.get_barrierMode_val();
return (mode != (unsigned)DXIL::BarrierMode::UAVFenceGlobal);
}
return false;
}
case OpCode::BarrierByMemoryType: {
DxilInst_BarrierByMemoryType barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_MemoryTypeFlags())) {
unsigned memoryTypeFlags = barrier.get_MemoryTypeFlags_val();
memoryTypeFlags = MaskMemoryTypeFlagsIfAllowed(
memoryTypeFlags, ~(unsigned)DXIL::MemoryTypeFlag::GroupFlags);
if (memoryTypeFlags & (unsigned)DXIL::MemoryTypeFlag::GroupFlags)
return true;
}
}
LLVM_FALLTHROUGH;
case OpCode::BarrierByMemoryHandle:
case OpCode::BarrierByNodeRecordHandle: {
// BarrierByMemoryType, BarrierByMemoryHandle, and BarrierByNodeRecordHandle
// all have semanticFlags as the second operand.
DxilInst_BarrierByMemoryType barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_SemanticFlags())) {
unsigned semanticFlags = barrier.get_SemanticFlags_val();
if (semanticFlags & (unsigned)DXIL::BarrierSemanticFlag::GroupFlags)
return true;
}
return false;
}
default:
return false;
}
}
bool OP::BarrierRequiresNode(const llvm::CallInst *CI) {
OpCode opcode = OP::GetDxilOpFuncCallInst(CI);
switch (opcode) {
case OpCode::BarrierByNodeRecordHandle:
return true;
case OpCode::BarrierByMemoryType: {
DxilInst_BarrierByMemoryType barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_MemoryTypeFlags())) {
unsigned memoryTypeFlags = barrier.get_MemoryTypeFlags_val();
// Mask off node flags, if allowed.
memoryTypeFlags = MaskMemoryTypeFlagsIfAllowed(
memoryTypeFlags, ~(unsigned)DXIL::MemoryTypeFlag::NodeFlags);
return (memoryTypeFlags & (unsigned)DXIL::MemoryTypeFlag::NodeFlags) != 0;
}
return false;
}
default:
return false;
}
}
DXIL::BarrierMode OP::TranslateToBarrierMode(const llvm::CallInst *CI) {
OpCode opcode = OP::GetDxilOpFuncCallInst(CI);
switch (opcode) {
case OpCode::Barrier: {
DxilInst_Barrier barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_barrierMode())) {
unsigned mode = barrier.get_barrierMode_val();
return static_cast<DXIL::BarrierMode>(mode);
}
return DXIL::BarrierMode::Invalid;
}
case OpCode::BarrierByMemoryType: {
unsigned memoryTypeFlags = 0;
unsigned semanticFlags = 0;
DxilInst_BarrierByMemoryType barrier(const_cast<CallInst *>(CI));
if (isa<ConstantInt>(barrier.get_MemoryTypeFlags())) {
memoryTypeFlags = barrier.get_MemoryTypeFlags_val();
}
if (isa<ConstantInt>(barrier.get_SemanticFlags())) {
semanticFlags = barrier.get_SemanticFlags_val();
}
// Mask to legacy flags, if allowed.
memoryTypeFlags = MaskMemoryTypeFlagsIfAllowed(
memoryTypeFlags, (unsigned)DXIL::MemoryTypeFlag::LegacyFlags);
if (memoryTypeFlags & ~(unsigned)DXIL::MemoryTypeFlag::LegacyFlags)
return DXIL::BarrierMode::Invalid;
unsigned mode = 0;
if (memoryTypeFlags & (unsigned)DXIL::MemoryTypeFlag::GroupSharedMemory)
mode |= (unsigned)DXIL::BarrierMode::TGSMFence;
if (memoryTypeFlags & (unsigned)DXIL::MemoryTypeFlag::UavMemory) {
if (semanticFlags & (unsigned)DXIL::BarrierSemanticFlag::DeviceScope) {
mode |= (unsigned)DXIL::BarrierMode::UAVFenceGlobal;
} else if (semanticFlags &
(unsigned)DXIL::BarrierSemanticFlag::GroupScope) {
mode |= (unsigned)DXIL::BarrierMode::UAVFenceThreadGroup;
}
}
if (semanticFlags & (unsigned)DXIL::BarrierSemanticFlag::GroupSync)
mode |= (unsigned)DXIL::BarrierMode::SyncThreadGroup;
return static_cast<DXIL::BarrierMode>(mode);
}
default:
return DXIL::BarrierMode::Invalid;
}
}
#define SFLAG(stage) ((unsigned)1 << (unsigned)DXIL::ShaderKind::stage)
void OP::GetMinShaderModelAndMask(OpCode C, bool bWithTranslation,
unsigned &major, unsigned &minor,
unsigned &mask) {
unsigned op = (unsigned)C;
// Default is 6.0, all stages
major = 6;
minor = 0;
mask = ((unsigned)1 << (unsigned)DXIL::ShaderKind::Invalid) - 1;
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-SMMASK')>hctdb_instrhelp.get_min_sm_and_mask_text()</py>*/
// clang-format on
// OPCODE-SMMASK:BEGIN
// Instructions: ThreadId=93, GroupId=94, ThreadIdInGroup=95,
// FlattenedThreadIdInGroup=96
if ((93 <= op && op <= 96)) {
mask = SFLAG(Compute) | SFLAG(Mesh) | SFLAG(Amplification) | SFLAG(Node);
return;
}
// Instructions: DomainLocation=105
if (op == 105) {
mask = SFLAG(Domain);
return;
}
// Instructions: LoadOutputControlPoint=103, LoadPatchConstant=104
if ((103 <= op && op <= 104)) {
mask = SFLAG(Domain) | SFLAG(Hull);
return;
}
// Instructions: EmitStream=97, CutStream=98, EmitThenCutStream=99,
// GSInstanceID=100
if ((97 <= op && op <= 100)) {
mask = SFLAG(Geometry);
return;
}
// Instructions: PrimitiveID=108
if (op == 108) {
mask = SFLAG(Geometry) | SFLAG(Domain) | SFLAG(Hull);
return;
}
// Instructions: StorePatchConstant=106, OutputControlPointID=107
if ((106 <= op && op <= 107)) {
mask = SFLAG(Hull);
return;
}
// Instructions: QuadReadLaneAt=122, QuadOp=123
if ((122 <= op && op <= 123)) {
mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) |
SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Node);
return;
}
// Instructions: WaveIsFirstLane=110, WaveGetLaneIndex=111,
// WaveGetLaneCount=112, WaveAnyTrue=113, WaveAllTrue=114,
// WaveActiveAllEqual=115, WaveActiveBallot=116, WaveReadLaneAt=117,
// WaveReadLaneFirst=118, WaveActiveOp=119, WaveActiveBit=120,
// WavePrefixOp=121, WaveAllBitCount=135, WavePrefixBitCount=136
if ((110 <= op && op <= 121) || (135 <= op && op <= 136)) {
mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) |
SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Vertex) | SFLAG(Hull) |
SFLAG(Domain) | SFLAG(Geometry) | SFLAG(RayGeneration) |
SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) |
SFLAG(Miss) | SFLAG(Callable) | SFLAG(Node);
return;
}
// Instructions: Sample=60, SampleBias=61, SampleCmp=64, CalculateLOD=81,
// DerivCoarseX=83, DerivCoarseY=84, DerivFineX=85, DerivFineY=86
if ((60 <= op && op <= 61) || op == 64 || op == 81 ||
(83 <= op && op <= 86)) {
mask = SFLAG(Library) | SFLAG(Pixel) | SFLAG(Compute) |
SFLAG(Amplification) | SFLAG(Mesh) | SFLAG(Node);
return;
}
// Instructions: RenderTargetGetSamplePosition=76,
// RenderTargetGetSampleCount=77, Discard=82, EvalSnapped=87,
// EvalSampleIndex=88, EvalCentroid=89, SampleIndex=90, Coverage=91,
// InnerCoverage=92
if ((76 <= op && op <= 77) || op == 82 || (87 <= op && op <= 92)) {
mask = SFLAG(Pixel);
return;
}
// Instructions: AttributeAtVertex=137
if (op == 137) {
major = 6;
minor = 1;
mask = SFLAG(Pixel);
return;
}
// Instructions: ViewID=138
if (op == 138) {
major = 6;
minor = 1;
mask = SFLAG(Vertex) | SFLAG(Hull) | SFLAG(Domain) | SFLAG(Geometry) |
SFLAG(Pixel) | SFLAG(Mesh);
return;
}
// Instructions: RawBufferLoad=139, RawBufferStore=140
if ((139 <= op && op <= 140)) {
if (bWithTranslation) {
major = 6;
minor = 0;
} else {
major = 6;
minor = 2;
}
return;
}
// Instructions: IgnoreHit=155, AcceptHitAndEndSearch=156
if ((155 <= op && op <= 156)) {
major = 6;
minor = 3;
mask = SFLAG(AnyHit);
return;
}
// Instructions: CallShader=159
if (op == 159) {
major = 6;
minor = 3;
mask = SFLAG(Library) | SFLAG(ClosestHit) | SFLAG(RayGeneration) |
SFLAG(Miss) | SFLAG(Callable);
return;
}
// Instructions: ReportHit=158
if (op == 158) {
major = 6;
minor = 3;
mask = SFLAG(Library) | SFLAG(Intersection);
return;
}
// Instructions: InstanceID=141, InstanceIndex=142, HitKind=143,
// ObjectRayOrigin=149, ObjectRayDirection=150, ObjectToWorld=151,
// WorldToObject=152, PrimitiveIndex=161
if ((141 <= op && op <= 143) || (149 <= op && op <= 152) || op == 161) {
major = 6;
minor = 3;
mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) |
SFLAG(ClosestHit);
return;
}
// Instructions: RayFlags=144, WorldRayOrigin=147, WorldRayDirection=148,
// RayTMin=153, RayTCurrent=154
if (op == 144 || (147 <= op && op <= 148) || (153 <= op && op <= 154)) {
major = 6;
minor = 3;
mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) |
SFLAG(ClosestHit) | SFLAG(Miss);
return;
}
// Instructions: TraceRay=157
if (op == 157) {
major = 6;
minor = 3;
mask =
SFLAG(Library) | SFLAG(RayGeneration) | SFLAG(ClosestHit) | SFLAG(Miss);
return;
}
// Instructions: DispatchRaysIndex=145, DispatchRaysDimensions=146
if ((145 <= op && op <= 146)) {
major = 6;
minor = 3;
mask = SFLAG(Library) | SFLAG(RayGeneration) | SFLAG(Intersection) |
SFLAG(AnyHit) | SFLAG(ClosestHit) | SFLAG(Miss) | SFLAG(Callable);
return;
}
// Instructions: CreateHandleForLib=160
if (op == 160) {
if (bWithTranslation) {
major = 6;
minor = 0;
} else {
major = 6;
minor = 3;
}
return;
}
// Instructions: Dot2AddHalf=162, Dot4AddI8Packed=163, Dot4AddU8Packed=164
if ((162 <= op && op <= 164)) {
major = 6;
minor = 4;
return;
}
// Instructions: WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177,
// AllocateRayQuery=178, RayQuery_TraceRayInline=179, RayQuery_Proceed=180,
// RayQuery_Abort=181, RayQuery_CommitNonOpaqueTriangleHit=182,
// RayQuery_CommitProceduralPrimitiveHit=183, RayQuery_CommittedStatus=184,
// RayQuery_CandidateType=185, RayQuery_CandidateObjectToWorld3x4=186,
// RayQuery_CandidateWorldToObject3x4=187,
// RayQuery_CommittedObjectToWorld3x4=188,
// RayQuery_CommittedWorldToObject3x4=189,
// RayQuery_CandidateProceduralPrimitiveNonOpaque=190,
// RayQuery_CandidateTriangleFrontFace=191,
// RayQuery_CommittedTriangleFrontFace=192,
// RayQuery_CandidateTriangleBarycentrics=193,
// RayQuery_CommittedTriangleBarycentrics=194, RayQuery_RayFlags=195,
// RayQuery_WorldRayOrigin=196, RayQuery_WorldRayDirection=197,
// RayQuery_RayTMin=198, RayQuery_CandidateTriangleRayT=199,
// RayQuery_CommittedRayT=200, RayQuery_CandidateInstanceIndex=201,
// RayQuery_CandidateInstanceID=202, RayQuery_CandidateGeometryIndex=203,
// RayQuery_CandidatePrimitiveIndex=204,
// RayQuery_CandidateObjectRayOrigin=205,
// RayQuery_CandidateObjectRayDirection=206,
// RayQuery_CommittedInstanceIndex=207, RayQuery_CommittedInstanceID=208,
// RayQuery_CommittedGeometryIndex=209, RayQuery_CommittedPrimitiveIndex=210,
// RayQuery_CommittedObjectRayOrigin=211,
// RayQuery_CommittedObjectRayDirection=212,
// RayQuery_CandidateInstanceContributionToHitGroupIndex=214,
// RayQuery_CommittedInstanceContributionToHitGroupIndex=215
if ((176 <= op && op <= 212) || (214 <= op && op <= 215)) {
major = 6;
minor = 5;
return;
}
// Instructions: DispatchMesh=173
if (op == 173) {
major = 6;
minor = 5;
mask = SFLAG(Amplification);
return;
}
// Instructions: WaveMatch=165, WaveMultiPrefixOp=166,
// WaveMultiPrefixBitCount=167
if ((165 <= op && op <= 167)) {
major = 6;
minor = 5;
mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) |
SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Vertex) | SFLAG(Hull) |
SFLAG(Domain) | SFLAG(Geometry) | SFLAG(RayGeneration) |
SFLAG(Intersection) | SFLAG(AnyHit) | SFLAG(ClosestHit) |
SFLAG(Miss) | SFLAG(Callable) | SFLAG(Node);
return;
}
// Instructions: GeometryIndex=213
if (op == 213) {
major = 6;
minor = 5;
mask = SFLAG(Library) | SFLAG(Intersection) | SFLAG(AnyHit) |
SFLAG(ClosestHit);
return;
}
// Instructions: WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175
if ((174 <= op && op <= 175)) {
major = 6;
minor = 5;
mask = SFLAG(Library) | SFLAG(Pixel);
return;
}
// Instructions: SetMeshOutputCounts=168, EmitIndices=169, GetMeshPayload=170,
// StoreVertexOutput=171, StorePrimitiveOutput=172
if ((168 <= op && op <= 172)) {
major = 6;
minor = 5;
mask = SFLAG(Mesh);
return;
}
// Instructions: CreateHandleFromHeap=218, Unpack4x8=219, Pack4x8=220,
// IsHelperLane=221
if ((218 <= op && op <= 221)) {
major = 6;
minor = 6;
return;
}
// Instructions: AnnotateHandle=216, CreateHandleFromBinding=217
if ((216 <= op && op <= 217)) {
if (bWithTranslation) {
major = 6;
minor = 0;
} else {
major = 6;
minor = 6;
}
return;
}
// Instructions: TextureGatherRaw=223, SampleCmpLevel=224,
// TextureStoreSample=225
if ((223 <= op && op <= 225)) {
major = 6;
minor = 7;
return;
}
// Instructions: QuadVote=222
if (op == 222) {
if (bWithTranslation) {
major = 6;
minor = 0;
} else {
major = 6;
minor = 7;
}
mask = SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) |
SFLAG(Mesh) | SFLAG(Pixel) | SFLAG(Node);
return;
}
// Instructions: BarrierByMemoryHandle=245, SampleCmpGrad=254
if (op == 245 || op == 254) {
major = 6;
minor = 8;
return;
}
// Instructions: SampleCmpBias=255
if (op == 255) {
major = 6;
minor = 8;
mask = SFLAG(Library) | SFLAG(Pixel) | SFLAG(Compute) |
SFLAG(Amplification) | SFLAG(Mesh) | SFLAG(Node);
return;
}
// Instructions: AllocateNodeOutputRecords=238, GetNodeRecordPtr=239,
// IncrementOutputCount=240, OutputComplete=241, GetInputRecordCount=242,
// FinishedCrossGroupSharing=243, BarrierByNodeRecordHandle=246,
// CreateNodeOutputHandle=247, IndexNodeHandle=248, AnnotateNodeHandle=249,
// CreateNodeInputRecordHandle=250, AnnotateNodeRecordHandle=251,
// NodeOutputIsValid=252, GetRemainingRecursionLevels=253
if ((238 <= op && op <= 243) || (246 <= op && op <= 253)) {
major = 6;
minor = 8;
mask = SFLAG(Node);
return;
}
// Instructions: StartVertexLocation=256, StartInstanceLocation=257
if ((256 <= op && op <= 257)) {
major = 6;
minor = 8;
mask = SFLAG(Vertex);
return;
}
// Instructions: BarrierByMemoryType=244
if (op == 244) {
if (bWithTranslation) {
major = 6;
minor = 0;
} else {
major = 6;
minor = 8;
}
return;
}
// OPCODE-SMMASK:END
}
void OP::GetMinShaderModelAndMask(const llvm::CallInst *CI,
bool bWithTranslation, unsigned valMajor,
unsigned valMinor, unsigned &major,
unsigned &minor, unsigned &mask) {
OpCode opcode = OP::GetDxilOpFuncCallInst(CI);
GetMinShaderModelAndMask(opcode, bWithTranslation, major, minor, mask);
unsigned op = (unsigned)opcode;
if (DXIL::CompareVersions(valMajor, valMinor, 1, 8) < 0) {
// In prior validator versions, these ops excluded CS/MS/AS from mask.
// In 1.8, we now have a mechanism to indicate derivative use with an
// independent feature bit. This allows us to fix up the min shader model
// once all bits have been marged from the call graph to the entry point.
// Instructions: Sample=60, SampleBias=61, SampleCmp=64, CalculateLOD=81,
// DerivCoarseX=83, DerivCoarseY=84, DerivFineX=85, DerivFineY=86
if ((60 <= op && op <= 61) || op == 64 || op == 81 ||
(83 <= op && op <= 86)) {
mask &= ~(SFLAG(Compute) | SFLAG(Amplification) | SFLAG(Mesh));
return;
}
}
if (DXIL::CompareVersions(valMajor, valMinor, 1, 5) < 0) {
// validator 1.4 didn't exclude wave ops in mask
if (IsDxilOpWave(opcode))
mask = ((unsigned)1 << (unsigned)DXIL::ShaderKind::Mesh) - 1;
// validator 1.4 didn't have any additional rules applied:
return;
}
// Additional rules are applied manually here.
// Barrier requiring node or group limit shader kinds.
if (IsDxilOpBarrier(opcode)) {
// If BarrierByMemoryType, check if translatable, or set min to 6.8.
if (bWithTranslation && opcode == DXIL::OpCode::BarrierByMemoryType) {
if (TranslateToBarrierMode(CI) == DXIL::BarrierMode::Invalid) {
major = 6;
minor = 8;
}
}
if (BarrierRequiresNode(CI)) {
mask &= SFLAG(Library) | SFLAG(Node);
return;
} else if (BarrierRequiresGroup(CI)) {
mask &= SFLAG(Library) | SFLAG(Compute) | SFLAG(Amplification) |
SFLAG(Mesh) | SFLAG(Node);
return;
}
}
// 64-bit integer atomic ops require 6.6
else if (opcode == DXIL::OpCode::AtomicBinOp ||
opcode == DXIL::OpCode::AtomicCompareExchange) {
Type *pOverloadType = GetOverloadType(opcode, CI->getCalledFunction());
if (pOverloadType->isIntegerTy(64)) {
major = 6;
minor = 6;
}
}
// AnnotateHandle and CreateHandleFromBinding can be translated down to
// SM 6.0, but this wasn't set properly in validator version 6.6, so make it
// match when using that version.
else if (bWithTranslation &&
DXIL::CompareVersions(valMajor, valMinor, 1, 6) == 0 &&
(opcode == DXIL::OpCode::AnnotateHandle ||
opcode == DXIL::OpCode::CreateHandleFromBinding)) {
major = 6;
minor = 6;
}
}
#undef SFLAG
static Type *GetOrCreateStructType(LLVMContext &Ctx, ArrayRef<Type *> types,
StringRef Name, Module *pModule) {
if (StructType *ST = pModule->getTypeByName(Name)) {
// TODO: validate the exist type match types if needed.
return ST;
} else
return StructType::create(Ctx, types, Name);
}
//------------------------------------------------------------------------------
//
// OP methods.
//
OP::OP(LLVMContext &Ctx, Module *pModule)
: m_Ctx(Ctx), m_pModule(pModule),
m_LowPrecisionMode(DXIL::LowPrecisionMode::Undefined) {
memset(m_pResRetType, 0, sizeof(m_pResRetType));
memset(m_pCBufferRetType, 0, sizeof(m_pCBufferRetType));
memset(m_OpCodeClassCache, 0, sizeof(m_OpCodeClassCache));
static_assert(_countof(OP::m_OpCodeProps) == (size_t)OP::OpCode::NumOpCodes,
"forgot to update OP::m_OpCodeProps");
m_pHandleType = GetOrCreateStructType(m_Ctx, Type::getInt8PtrTy(m_Ctx),
"dx.types.Handle", pModule);
m_pNodeHandleType = GetOrCreateStructType(m_Ctx, Type::getInt8PtrTy(m_Ctx),
"dx.types.NodeHandle", pModule);
m_pNodeRecordHandleType = GetOrCreateStructType(
m_Ctx, Type::getInt8PtrTy(m_Ctx), "dx.types.NodeRecordHandle", pModule);
m_pResourcePropertiesType = GetOrCreateStructType(
m_Ctx, {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)},
"dx.types.ResourceProperties", pModule);
m_pNodePropertiesType = GetOrCreateStructType(
m_Ctx, {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)},
"dx.types.NodeInfo", pModule);
m_pNodeRecordPropertiesType = GetOrCreateStructType(
m_Ctx, {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)},
"dx.types.NodeRecordInfo", pModule);
m_pResourceBindingType =
GetOrCreateStructType(m_Ctx,
{Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx),
Type::getInt32Ty(m_Ctx), Type::getInt8Ty(m_Ctx)},
"dx.types.ResBind", pModule);
Type *DimsType[4] = {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx),
Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)};
m_pDimensionsType =
GetOrCreateStructType(m_Ctx, DimsType, "dx.types.Dimensions", pModule);
Type *SamplePosType[2] = {Type::getFloatTy(m_Ctx), Type::getFloatTy(m_Ctx)};
m_pSamplePosType = GetOrCreateStructType(m_Ctx, SamplePosType,
"dx.types.SamplePos", pModule);
Type *I32cTypes[2] = {Type::getInt32Ty(m_Ctx), Type::getInt1Ty(m_Ctx)};
m_pBinaryWithCarryType =
GetOrCreateStructType(m_Ctx, I32cTypes, "dx.types.i32c", pModule);
Type *TwoI32Types[2] = {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx)};
m_pBinaryWithTwoOutputsType =
GetOrCreateStructType(m_Ctx, TwoI32Types, "dx.types.twoi32", pModule);
Type *SplitDoubleTypes[2] = {Type::getInt32Ty(m_Ctx),
Type::getInt32Ty(m_Ctx)}; // Lo, Hi.
m_pSplitDoubleType = GetOrCreateStructType(m_Ctx, SplitDoubleTypes,
"dx.types.splitdouble", pModule);
Type *FourI32Types[4] = {Type::getInt32Ty(m_Ctx), Type::getInt32Ty(m_Ctx),
Type::getInt32Ty(m_Ctx),
Type::getInt32Ty(m_Ctx)}; // HiHi, HiLo, LoHi, LoLo
m_pFourI32Type =
GetOrCreateStructType(m_Ctx, FourI32Types, "dx.types.fouri32", pModule);
Type *FourI16Types[4] = {Type::getInt16Ty(m_Ctx), Type::getInt16Ty(m_Ctx),
Type::getInt16Ty(m_Ctx),
Type::getInt16Ty(m_Ctx)}; // HiHi, HiLo, LoHi, LoLo
m_pFourI16Type =
GetOrCreateStructType(m_Ctx, FourI16Types, "dx.types.fouri16", pModule);
}
void OP::RefreshCache() {
for (Function &F : m_pModule->functions()) {
if (OP::IsDxilOpFunc(&F) && !F.user_empty()) {
CallInst *CI = cast<CallInst>(*F.user_begin());
OpCode OpCode = OP::GetDxilOpFuncCallInst(CI);
Type *pOverloadType = OP::GetOverloadType(OpCode, &F);
GetOpFunc(OpCode, pOverloadType);
}
}
}
void OP::FixOverloadNames() {
// When merging code from multiple sources, such as with linking,
// type names that collide, but don't have the same type will be
// automically renamed with .0+ name disambiguation. However,
// DXIL intrinsic overloads will not be renamed to disambiguate them,
// since they exist in separate modules at the time.
// This leads to name collisions between different types when linking.
// Do this after loading into a shared context, and before copying
// code into a common module, to prevent this problem.
for (Function &F : m_pModule->functions()) {
if (F.isDeclaration() && OP::IsDxilOpFunc(&F) && !F.user_empty()) {
CallInst *CI = cast<CallInst>(*F.user_begin());
DXIL::OpCode opCode = OP::GetDxilOpFuncCallInst(CI);
llvm::Type *Ty = OP::GetOverloadType(opCode, &F);
if (!OP::IsOverloadLegal(opCode, Ty))
continue;
if (!isa<StructType>(Ty) && !isa<PointerType>(Ty))
continue;
std::string funcName;
if (OP::ConstructOverloadName(Ty, opCode, funcName)
.compare(F.getName()) != 0)
F.setName(funcName);
}
}
}
void OP::UpdateCache(OpCodeClass opClass, Type *Ty, llvm::Function *F) {
m_OpCodeClassCache[(unsigned)opClass].pOverloads[Ty] = F;
m_FunctionToOpClass[F] = opClass;
}
Function *OP::GetOpFunc(OpCode opCode, Type *pOverloadType) {
if (opCode == OpCode::NumOpCodes)
return nullptr;
if (!pOverloadType)
return nullptr;
// Illegal overloads are generated and eliminated by DXIL op constant
// evaluation for a number of cases where a double overload of an HL intrinsic
// that otherwise does not support double is used for literal values, when
// there is no constant evaluation for the intrinsic in CodeGen.
// Illegal overloads of DXIL intrinsics may survive through to final DXIL,
// but these will be caught by the validator, and this is not a regression.
OpCodeClass opClass = m_OpCodeProps[(unsigned)opCode].opCodeClass;
Function *&F =
m_OpCodeClassCache[(unsigned)opClass].pOverloads[pOverloadType];
if (F != nullptr) {
UpdateCache(opClass, pOverloadType, F);
return F;
}
vector<Type *> ArgTypes; // RetType is ArgTypes[0]
Type *pETy = pOverloadType;
Type *pRes = GetHandleType();
Type *pNodeHandle = GetNodeHandleType();
Type *pNodeRecordHandle = GetNodeRecordHandleType();
Type *pDim = GetDimensionsType();
Type *pPos = GetSamplePosType();
Type *pV = Type::getVoidTy(m_Ctx);
Type *pI1 = Type::getInt1Ty(m_Ctx);
Type *pI8 = Type::getInt8Ty(m_Ctx);
Type *pI16 = Type::getInt16Ty(m_Ctx);
Type *pI32 = Type::getInt32Ty(m_Ctx);
Type *pPI32 = Type::getInt32PtrTy(m_Ctx);
(void)(pPI32); // Currently unused.
Type *pI64 = Type::getInt64Ty(m_Ctx);
(void)(pI64); // Currently unused.
Type *pF16 = Type::getHalfTy(m_Ctx);
Type *pF32 = Type::getFloatTy(m_Ctx);
Type *pPF32 = Type::getFloatPtrTy(m_Ctx);
Type *pI32C = GetBinaryWithCarryType();
Type *p2I32 = GetBinaryWithTwoOutputsType();
Type *pF64 = Type::getDoubleTy(m_Ctx);
Type *pSDT = GetSplitDoubleType(); // Split double type.
Type *p4I32 = GetFourI32Type(); // 4 i32s in a struct.
Type *udt = pOverloadType;
Type *obj = pOverloadType;
Type *resProperty = GetResourcePropertiesType();
Type *resBind = GetResourceBindingType();
Type *nodeProperty = GetNodePropertiesType();
Type *nodeRecordProperty = GetNodeRecordPropertiesType();
#define A(_x) ArgTypes.emplace_back(_x)
#define RRT(_y) A(GetResRetType(_y))
#define CBRT(_y) A(GetCBufferRetType(_y))
#define VEC4(_y) A(GetVectorType(4, _y))
/* <py::lines('OPCODE-OLOAD-FUNCS')>hctdb_instrhelp.get_oloads_funcs()</py>*/
switch (opCode) { // return opCode
// OPCODE-OLOAD-FUNCS:BEGIN
// Temporary, indexable, input, output registers
case OpCode::TempRegLoad:
A(pETy);
A(pI32);
A(pI32);
break;
case OpCode::TempRegStore:
A(pV);
A(pI32);
A(pI32);
A(pETy);
break;
case OpCode::MinPrecXRegLoad:
A(pETy);
A(pI32);
A(pPF32);
A(pI32);
A(pI8);
break;
case OpCode::MinPrecXRegStore:
A(pV);
A(pI32);
A(pPF32);
A(pI32);
A(pI8);
A(pETy);
break;
case OpCode::LoadInput:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI32);
break;
case OpCode::StoreOutput:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pETy);
break;
// Unary float
case OpCode::FAbs:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Saturate:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::IsNaN:
A(pI1);
A(pI32);
A(pETy);
break;
case OpCode::IsInf:
A(pI1);
A(pI32);
A(pETy);
break;
case OpCode::IsFinite:
A(pI1);
A(pI32);
A(pETy);
break;
case OpCode::IsNormal:
A(pI1);
A(pI32);
A(pETy);
break;
case OpCode::Cos:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Sin:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Tan:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Acos:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Asin:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Atan:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Hcos:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Hsin:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Htan:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Exp:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Frc:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Log:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Sqrt:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Rsqrt:
A(pETy);
A(pI32);
A(pETy);
break;
// Unary float - rounding
case OpCode::Round_ne:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Round_ni:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Round_pi:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Round_z:
A(pETy);
A(pI32);
A(pETy);
break;
// Unary int
case OpCode::Bfrev:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::Countbits:
A(pI32);
A(pI32);
A(pETy);
break;
case OpCode::FirstbitLo:
A(pI32);
A(pI32);
A(pETy);
break;
// Unary uint
case OpCode::FirstbitHi:
A(pI32);
A(pI32);
A(pETy);
break;
// Unary int
case OpCode::FirstbitSHi:
A(pI32);
A(pI32);
A(pETy);
break;
// Binary float
case OpCode::FMax:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::FMin:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
// Binary int
case OpCode::IMax:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::IMin:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
// Binary uint
case OpCode::UMax:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::UMin:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
break;
// Binary int with two outputs
case OpCode::IMul:
A(p2I32);
A(pI32);
A(pETy);
A(pETy);
break;
// Binary uint with two outputs
case OpCode::UMul:
A(p2I32);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::UDiv:
A(p2I32);
A(pI32);
A(pETy);
A(pETy);
break;
// Binary uint with carry or borrow
case OpCode::UAddc:
A(pI32C);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::USubb:
A(pI32C);
A(pI32);
A(pETy);
A(pETy);
break;
// Tertiary float
case OpCode::FMad:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
case OpCode::Fma:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
// Tertiary int
case OpCode::IMad:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
// Tertiary uint
case OpCode::UMad:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
// Tertiary int
case OpCode::Msad:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
case OpCode::Ibfe:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
// Tertiary uint
case OpCode::Ubfe:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
break;
// Quaternary
case OpCode::Bfi:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
break;
// Dot
case OpCode::Dot2:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
break;
case OpCode::Dot3:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
break;
case OpCode::Dot4:
A(pETy);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
break;
// Resources
case OpCode::CreateHandle:
A(pRes);
A(pI32);
A(pI8);
A(pI32);
A(pI32);
A(pI1);
break;
case OpCode::CBufferLoad:
A(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
break;
case OpCode::CBufferLoadLegacy:
CBRT(pETy);
A(pI32);
A(pRes);
A(pI32);
break;
// Resources - sample
case OpCode::Sample:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
break;
case OpCode::SampleBias:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
break;
case OpCode::SampleLevel:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
break;
case OpCode::SampleGrad:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::SampleCmp:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
break;
case OpCode::SampleCmpLevelZero:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
break;
// Resources
case OpCode::TextureLoad:
RRT(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::TextureStore:
A(pV);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pI8);
break;
case OpCode::BufferLoad:
RRT(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
break;
case OpCode::BufferStore:
A(pV);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pI8);
break;
case OpCode::BufferUpdateCounter:
A(pI32);
A(pI32);
A(pRes);
A(pI8);
break;
case OpCode::CheckAccessFullyMapped:
A(pI1);
A(pI32);
A(pI32);
break;
case OpCode::GetDimensions:
A(pDim);
A(pI32);
A(pRes);
A(pI32);
break;
// Resources - gather
case OpCode::TextureGather:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::TextureGatherCmp:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
break;
// Resources - sample
case OpCode::Texture2DMSGetSamplePosition:
A(pPos);
A(pI32);
A(pRes);
A(pI32);
break;
case OpCode::RenderTargetGetSamplePosition:
A(pPos);
A(pI32);
A(pI32);
break;
case OpCode::RenderTargetGetSampleCount:
A(pI32);
A(pI32);
break;
// Synchronization
case OpCode::AtomicBinOp:
A(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pETy);
break;
case OpCode::AtomicCompareExchange:
A(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pETy);
A(pETy);
break;
case OpCode::Barrier:
A(pV);
A(pI32);
A(pI32);
break;
// Derivatives
case OpCode::CalculateLOD:
A(pF32);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pI1);
break;
// Pixel shader
case OpCode::Discard:
A(pV);
A(pI32);
A(pI1);
break;
// Derivatives
case OpCode::DerivCoarseX:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::DerivCoarseY:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::DerivFineX:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::DerivFineY:
A(pETy);
A(pI32);
A(pETy);
break;
// Pixel shader
case OpCode::EvalSnapped:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI32);
A(pI32);
break;
case OpCode::EvalSampleIndex:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI32);
break;
case OpCode::EvalCentroid:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::SampleIndex:
A(pI32);
A(pI32);
break;
case OpCode::Coverage:
A(pI32);
A(pI32);
break;
case OpCode::InnerCoverage:
A(pI32);
A(pI32);
break;
// Compute/Mesh/Amplification/Node shader
case OpCode::ThreadId:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::GroupId:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::ThreadIdInGroup:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::FlattenedThreadIdInGroup:
A(pI32);
A(pI32);
break;
// Geometry shader
case OpCode::EmitStream:
A(pV);
A(pI32);
A(pI8);
break;
case OpCode::CutStream:
A(pV);
A(pI32);
A(pI8);
break;
case OpCode::EmitThenCutStream:
A(pV);
A(pI32);
A(pI8);
break;
case OpCode::GSInstanceID:
A(pI32);
A(pI32);
break;
// Double precision
case OpCode::MakeDouble:
A(pF64);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::SplitDouble:
A(pSDT);
A(pI32);
A(pF64);
break;
// Domain and hull shader
case OpCode::LoadOutputControlPoint:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI32);
break;
case OpCode::LoadPatchConstant:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
// Domain shader
case OpCode::DomainLocation:
A(pF32);
A(pI32);
A(pI8);
break;
// Hull shader
case OpCode::StorePatchConstant:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pETy);
break;
case OpCode::OutputControlPointID:
A(pI32);
A(pI32);
break;
// Hull, Domain and Geometry shaders
case OpCode::PrimitiveID:
A(pI32);
A(pI32);
break;
// Other
case OpCode::CycleCounterLegacy:
A(p2I32);
A(pI32);
break;
// Wave
case OpCode::WaveIsFirstLane:
A(pI1);
A(pI32);
break;
case OpCode::WaveGetLaneIndex:
A(pI32);
A(pI32);
break;
case OpCode::WaveGetLaneCount:
A(pI32);
A(pI32);
break;
case OpCode::WaveAnyTrue:
A(pI1);
A(pI32);
A(pI1);
break;
case OpCode::WaveAllTrue:
A(pI1);
A(pI32);
A(pI1);
break;
case OpCode::WaveActiveAllEqual:
A(pI1);
A(pI32);
A(pETy);
break;
case OpCode::WaveActiveBallot:
A(p4I32);
A(pI32);
A(pI1);
break;
case OpCode::WaveReadLaneAt:
A(pETy);
A(pI32);
A(pETy);
A(pI32);
break;
case OpCode::WaveReadLaneFirst:
A(pETy);
A(pI32);
A(pETy);
break;
case OpCode::WaveActiveOp:
A(pETy);
A(pI32);
A(pETy);
A(pI8);
A(pI8);
break;
case OpCode::WaveActiveBit:
A(pETy);
A(pI32);
A(pETy);
A(pI8);
break;
case OpCode::WavePrefixOp:
A(pETy);
A(pI32);
A(pETy);
A(pI8);
A(pI8);
break;
// Quad Wave Ops
case OpCode::QuadReadLaneAt:
A(pETy);
A(pI32);
A(pETy);
A(pI32);
break;
case OpCode::QuadOp:
A(pETy);
A(pI32);
A(pETy);
A(pI8);
break;
// Bitcasts with different sizes
case OpCode::BitcastI16toF16:
A(pF16);
A(pI32);
A(pI16);
break;
case OpCode::BitcastF16toI16:
A(pI16);
A(pI32);
A(pF16);
break;
case OpCode::BitcastI32toF32:
A(pF32);
A(pI32);
A(pI32);
break;
case OpCode::BitcastF32toI32:
A(pI32);
A(pI32);
A(pF32);
break;
case OpCode::BitcastI64toF64:
A(pF64);
A(pI32);
A(pI64);
break;
case OpCode::BitcastF64toI64:
A(pI64);
A(pI32);
A(pF64);
break;
// Legacy floating-point
case OpCode::LegacyF32ToF16:
A(pI32);
A(pI32);
A(pF32);
break;
case OpCode::LegacyF16ToF32:
A(pF32);
A(pI32);
A(pI32);
break;
// Double precision
case OpCode::LegacyDoubleToFloat:
A(pF32);
A(pI32);
A(pF64);
break;
case OpCode::LegacyDoubleToSInt32:
A(pI32);
A(pI32);
A(pF64);
break;
case OpCode::LegacyDoubleToUInt32:
A(pI32);
A(pI32);
A(pF64);
break;
// Wave
case OpCode::WaveAllBitCount:
A(pI32);
A(pI32);
A(pI1);
break;
case OpCode::WavePrefixBitCount:
A(pI32);
A(pI32);
A(pI1);
break;
// Pixel shader
case OpCode::AttributeAtVertex:
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI8);
break;
// Graphics shader
case OpCode::ViewID:
A(pI32);
A(pI32);
break;
// Resources
case OpCode::RawBufferLoad:
RRT(pETy);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI8);
A(pI32);
break;
case OpCode::RawBufferStore:
A(pV);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pI8);
A(pI32);
break;
// Raytracing object space uint System Values
case OpCode::InstanceID:
A(pI32);
A(pI32);
break;
case OpCode::InstanceIndex:
A(pI32);
A(pI32);
break;
// Raytracing hit uint System Values
case OpCode::HitKind:
A(pI32);
A(pI32);
break;
// Raytracing uint System Values
case OpCode::RayFlags:
A(pI32);
A(pI32);
break;
// Ray Dispatch Arguments
case OpCode::DispatchRaysIndex:
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::DispatchRaysDimensions:
A(pI32);
A(pI32);
A(pI8);
break;
// Ray Vectors
case OpCode::WorldRayOrigin:
A(pF32);
A(pI32);
A(pI8);
break;
case OpCode::WorldRayDirection:
A(pF32);
A(pI32);
A(pI8);
break;
// Ray object space Vectors
case OpCode::ObjectRayOrigin:
A(pF32);
A(pI32);
A(pI8);
break;
case OpCode::ObjectRayDirection:
A(pF32);
A(pI32);
A(pI8);
break;
// Ray Transforms
case OpCode::ObjectToWorld:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::WorldToObject:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
// RayT
case OpCode::RayTMin:
A(pF32);
A(pI32);
break;
case OpCode::RayTCurrent:
A(pF32);
A(pI32);
break;
// AnyHit Terminals
case OpCode::IgnoreHit:
A(pV);
A(pI32);
break;
case OpCode::AcceptHitAndEndSearch:
A(pV);
A(pI32);
break;
// Indirect Shader Invocation
case OpCode::TraceRay:
A(pV);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(udt);
break;
case OpCode::ReportHit:
A(pI1);
A(pI32);
A(pF32);
A(pI32);
A(udt);
break;
case OpCode::CallShader:
A(pV);
A(pI32);
A(pI32);
A(udt);
break;
// Library create handle from resource struct (like HL intrinsic)
case OpCode::CreateHandleForLib:
A(pRes);
A(pI32);
A(obj);
break;
// Raytracing object space uint System Values
case OpCode::PrimitiveIndex:
A(pI32);
A(pI32);
break;
// Dot product with accumulate
case OpCode::Dot2AddHalf:
A(pETy);
A(pI32);
A(pETy);
A(pF16);
A(pF16);
A(pF16);
A(pF16);
break;
case OpCode::Dot4AddI8Packed:
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::Dot4AddU8Packed:
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
break;
// Wave
case OpCode::WaveMatch:
A(p4I32);
A(pI32);
A(pETy);
break;
case OpCode::WaveMultiPrefixOp:
A(pETy);
A(pI32);
A(pETy);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pI8);
break;
case OpCode::WaveMultiPrefixBitCount:
A(pI32);
A(pI32);
A(pI1);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
break;
// Mesh shader instructions
case OpCode::SetMeshOutputCounts:
A(pV);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::EmitIndices:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::GetMeshPayload:
A(pETy);
A(pI32);
break;
case OpCode::StoreVertexOutput:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pETy);
A(pI32);
break;
case OpCode::StorePrimitiveOutput:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
A(pETy);
A(pI32);
break;
// Amplification shader instructions
case OpCode::DispatchMesh:
A(pV);
A(pI32);
A(pI32);
A(pI32);
A(pI32);
A(pETy);
break;
// Sampler Feedback
case OpCode::WriteSamplerFeedback:
A(pV);
A(pI32);
A(pRes);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::WriteSamplerFeedbackBias:
A(pV);
A(pI32);
A(pRes);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::WriteSamplerFeedbackLevel:
A(pV);
A(pI32);
A(pRes);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::WriteSamplerFeedbackGrad:
A(pV);
A(pI32);
A(pRes);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
// Inline Ray Query
case OpCode::AllocateRayQuery:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_TraceRayInline:
A(pV);
A(pI32);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::RayQuery_Proceed:
A(pI1);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_Abort:
A(pV);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommitNonOpaqueTriangleHit:
A(pV);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommitProceduralPrimitiveHit:
A(pV);
A(pI32);
A(pI32);
A(pF32);
break;
case OpCode::RayQuery_CommittedStatus:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateType:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateObjectToWorld3x4:
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CandidateWorldToObject3x4:
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CommittedObjectToWorld3x4:
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CommittedWorldToObject3x4:
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CandidateProceduralPrimitiveNonOpaque:
A(pI1);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateTriangleFrontFace:
A(pI1);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedTriangleFrontFace:
A(pI1);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateTriangleBarycentrics:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CommittedTriangleBarycentrics:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_RayFlags:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_WorldRayOrigin:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_WorldRayDirection:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_RayTMin:
A(pF32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateTriangleRayT:
A(pF32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedRayT:
A(pF32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateInstanceIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateInstanceID:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateGeometryIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidatePrimitiveIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CandidateObjectRayOrigin:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CandidateObjectRayDirection:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CommittedInstanceIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedInstanceID:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedGeometryIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedPrimitiveIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedObjectRayOrigin:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
case OpCode::RayQuery_CommittedObjectRayDirection:
A(pF32);
A(pI32);
A(pI32);
A(pI8);
break;
// Raytracing object space uint System Values, raytracing tier 1.1
case OpCode::GeometryIndex:
A(pI32);
A(pI32);
break;
// Inline Ray Query
case OpCode::RayQuery_CandidateInstanceContributionToHitGroupIndex:
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::RayQuery_CommittedInstanceContributionToHitGroupIndex:
A(pI32);
A(pI32);
A(pI32);
break;
// Get handle from heap
case OpCode::AnnotateHandle:
A(pRes);
A(pI32);
A(pRes);
A(resProperty);
break;
case OpCode::CreateHandleFromBinding:
A(pRes);
A(pI32);
A(resBind);
A(pI32);
A(pI1);
break;
case OpCode::CreateHandleFromHeap:
A(pRes);
A(pI32);
A(pI32);
A(pI1);
A(pI1);
break;
// Unpacking intrinsics
case OpCode::Unpack4x8:
VEC4(pETy);
A(pI32);
A(pI8);
A(pI32);
break;
// Packing intrinsics
case OpCode::Pack4x8:
A(pI32);
A(pI32);
A(pI8);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
break;
// Helper Lanes
case OpCode::IsHelperLane:
A(pI1);
A(pI32);
break;
// Quad Wave Ops
case OpCode::QuadVote:
A(pI1);
A(pI32);
A(pI1);
A(pI8);
break;
// Resources - gather
case OpCode::TextureGatherRaw:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
break;
// Resources - sample
case OpCode::SampleCmpLevel:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
break;
// Resources
case OpCode::TextureStoreSample:
A(pV);
A(pI32);
A(pRes);
A(pI32);
A(pI32);
A(pI32);
A(pETy);
A(pETy);
A(pETy);
A(pETy);
A(pI8);
A(pI32);
break;
//
case OpCode::Reserved0:
A(pV);
A(pI32);
break;
case OpCode::Reserved1:
A(pV);
A(pI32);
break;
case OpCode::Reserved2:
A(pV);
A(pI32);
break;
case OpCode::Reserved3:
A(pV);
A(pI32);
break;
case OpCode::Reserved4:
A(pV);
A(pI32);
break;
case OpCode::Reserved5:
A(pV);
A(pI32);
break;
case OpCode::Reserved6:
A(pV);
A(pI32);
break;
case OpCode::Reserved7:
A(pV);
A(pI32);
break;
case OpCode::Reserved8:
A(pV);
A(pI32);
break;
case OpCode::Reserved9:
A(pV);
A(pI32);
break;
case OpCode::Reserved10:
A(pV);
A(pI32);
break;
case OpCode::Reserved11:
A(pV);
A(pI32);
break;
// Create/Annotate Node Handles
case OpCode::AllocateNodeOutputRecords:
A(pNodeRecordHandle);
A(pI32);
A(pNodeHandle);
A(pI32);
A(pI1);
break;
// Get Pointer to Node Record in Address Space 6
case OpCode::GetNodeRecordPtr:
A(pETy);
A(pI32);
A(pNodeRecordHandle);
A(pI32);
break;
// Work Graph intrinsics
case OpCode::IncrementOutputCount:
A(pV);
A(pI32);
A(pNodeHandle);
A(pI32);
A(pI1);
break;
case OpCode::OutputComplete:
A(pV);
A(pI32);
A(pNodeRecordHandle);
break;
case OpCode::GetInputRecordCount:
A(pI32);
A(pI32);
A(pNodeRecordHandle);
break;
case OpCode::FinishedCrossGroupSharing:
A(pI1);
A(pI32);
A(pNodeRecordHandle);
break;
// Synchronization
case OpCode::BarrierByMemoryType:
A(pV);
A(pI32);
A(pI32);
A(pI32);
break;
case OpCode::BarrierByMemoryHandle:
A(pV);
A(pI32);
A(pRes);
A(pI32);
break;
case OpCode::BarrierByNodeRecordHandle:
A(pV);
A(pI32);
A(pNodeRecordHandle);
A(pI32);
break;
// Create/Annotate Node Handles
case OpCode::CreateNodeOutputHandle:
A(pNodeHandle);
A(pI32);
A(pI32);
break;
case OpCode::IndexNodeHandle:
A(pNodeHandle);
A(pI32);
A(pNodeHandle);
A(pI32);
break;
case OpCode::AnnotateNodeHandle:
A(pNodeHandle);
A(pI32);
A(pNodeHandle);
A(nodeProperty);
break;
case OpCode::CreateNodeInputRecordHandle:
A(pNodeRecordHandle);
A(pI32);
A(pI32);
break;
case OpCode::AnnotateNodeRecordHandle:
A(pNodeRecordHandle);
A(pI32);
A(pNodeRecordHandle);
A(nodeRecordProperty);
break;
// Work Graph intrinsics
case OpCode::NodeOutputIsValid:
A(pI1);
A(pI32);
A(pNodeHandle);
break;
case OpCode::GetRemainingRecursionLevels:
A(pI32);
A(pI32);
break;
// Comparison Samples
case OpCode::SampleCmpGrad:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
break;
case OpCode::SampleCmpBias:
RRT(pETy);
A(pI32);
A(pRes);
A(pRes);
A(pF32);
A(pF32);
A(pF32);
A(pF32);
A(pI32);
A(pI32);
A(pI32);
A(pF32);
A(pF32);
A(pF32);
break;
// Extended Command Information
case OpCode::StartVertexLocation:
A(pI32);
A(pI32);
break;
case OpCode::StartInstanceLocation:
A(pI32);
A(pI32);
break;
// OPCODE-OLOAD-FUNCS:END
default:
DXASSERT(false, "otherwise unhandled case");
break;
}
#undef RRT
#undef A
FunctionType *pFT;
DXASSERT(ArgTypes.size() > 1, "otherwise forgot to initialize arguments");
pFT = FunctionType::get(
ArgTypes[0], ArrayRef<Type *>(&ArgTypes[1], ArgTypes.size() - 1), false);
std::string funcName;
ConstructOverloadName(pOverloadType, opCode, funcName);
// Try to find existing function with the same name in the module.
// This needs to happen after the switch statement that constructs arguments
// and return values to ensure that ResRetType is constructed in the
// RefreshCache case.
if (Function *existF = m_pModule->getFunction(funcName)) {
if (existF->getFunctionType() != pFT)
return nullptr;
F = existF;
UpdateCache(opClass, pOverloadType, F);
return F;
}
F = cast<Function>(m_pModule->getOrInsertFunction(funcName, pFT));
UpdateCache(opClass, pOverloadType, F);
F->setCallingConv(CallingConv::C);
F->addFnAttr(Attribute::NoUnwind);
if (m_OpCodeProps[(unsigned)opCode].FuncAttr != Attribute::None)
F->addFnAttr(m_OpCodeProps[(unsigned)opCode].FuncAttr);
return F;
}
const SmallMapVector<llvm::Type *, llvm::Function *, 8> &
OP::GetOpFuncList(OpCode opCode) const {
return m_OpCodeClassCache[(unsigned)m_OpCodeProps[(unsigned)opCode]
.opCodeClass]
.pOverloads;
}
bool OP::IsDxilOpUsed(OpCode opcode) const {
auto &FnList = GetOpFuncList(opcode);
for (auto &it : FnList) {
llvm::Function *F = it.second;
if (!F) {
continue;
}
if (!F->user_empty()) {
return true;
}
}
return false;
}
void OP::RemoveFunction(Function *F) {
if (OP::IsDxilOpFunc(F)) {
OpCodeClass opClass = m_FunctionToOpClass[F];
for (auto it : m_OpCodeClassCache[(unsigned)opClass].pOverloads) {
if (it.second == F) {
m_OpCodeClassCache[(unsigned)opClass].pOverloads.erase(it.first);
m_FunctionToOpClass.erase(F);
break;
}
}
}
}
bool OP::GetOpCodeClass(const Function *F, OP::OpCodeClass &opClass) {
auto iter = m_FunctionToOpClass.find(F);
if (iter == m_FunctionToOpClass.end()) {
// When no user, cannot get opcode.
DXASSERT(F->user_empty() || !IsDxilOpFunc(F),
"dxil function without an opcode class mapping?");
opClass = OP::OpCodeClass::NumOpClasses;
return false;
}
opClass = iter->second;
return true;
}
bool OP::UseMinPrecision() {
return m_LowPrecisionMode == DXIL::LowPrecisionMode::UseMinPrecision;
}
void OP::InitWithMinPrecision(bool bMinPrecision) {
DXIL::LowPrecisionMode mode =
bMinPrecision ? DXIL::LowPrecisionMode::UseMinPrecision
: DXIL::LowPrecisionMode::UseNativeLowPrecision;
DXASSERT((mode == m_LowPrecisionMode ||
m_LowPrecisionMode == DXIL::LowPrecisionMode::Undefined),
"LowPrecisionMode should only be set once.");
if (mode != m_LowPrecisionMode) {
m_LowPrecisionMode = mode;
// The following FixOverloadNames() and RefreshCache() calls interact with
// the type cache, which can only be correctly constructed once we know
// the min precision mode. That's why they are called here, rather than
// in the constructor.
// When loading a module into an existing context where types are merged,
// type names may change. When this happens, any intrinsics overloaded on
// UDT types will no longer have matching overload names.
// This causes RefreshCache() to assert.
// This fixes the function names to they match the expected types,
// preventing RefreshCache() from failing due to this issue.
FixOverloadNames();
// Try to find existing intrinsic function.
RefreshCache();
}
}
uint64_t OP::GetAllocSizeForType(llvm::Type *Ty) {
return m_pModule->getDataLayout().getTypeAllocSize(Ty);
}
llvm::Type *OP::GetOverloadType(OpCode opCode, llvm::Function *F) {
DXASSERT(F, "not work on nullptr");
Type *Ty = F->getReturnType();
FunctionType *FT = F->getFunctionType();
LLVMContext &Ctx = F->getContext();
// clang-format off
// Python lines need to be not formatted.
/* <py::lines('OPCODE-OLOAD-TYPES')>hctdb_instrhelp.get_funcs_oload_type()</py>*/
// clang-format on
switch (opCode) { // return OpCode
// OPCODE-OLOAD-TYPES:BEGIN
case OpCode::TempRegStore:
case OpCode::CallShader:
case OpCode::Pack4x8:
if (FT->getNumParams() <= 2)
return nullptr;
return FT->getParamType(2);
case OpCode::MinPrecXRegStore:
case OpCode::StoreOutput:
case OpCode::BufferStore:
case OpCode::StorePatchConstant:
case OpCode::RawBufferStore:
case OpCode::StoreVertexOutput:
case OpCode::StorePrimitiveOutput:
case OpCode::DispatchMesh:
if (FT->getNumParams() <= 4)
return nullptr;
return FT->getParamType(4);
case OpCode::IsNaN:
case OpCode::IsInf:
case OpCode::IsFinite:
case OpCode::IsNormal:
case OpCode::Countbits:
case OpCode::FirstbitLo:
case OpCode::FirstbitHi:
case OpCode::FirstbitSHi:
case OpCode::IMul:
case OpCode::UMul:
case OpCode::UDiv:
case OpCode::UAddc:
case OpCode::USubb:
case OpCode::WaveActiveAllEqual:
case OpCode::CreateHandleForLib:
case OpCode::WaveMatch:
if (FT->getNumParams() <= 1)
return nullptr;
return FT->getParamType(1);
case OpCode::TextureStore:
case OpCode::TextureStoreSample:
if (FT->getNumParams() <= 5)
return nullptr;
return FT->getParamType(5);
case OpCode::TraceRay:
if (FT->getNumParams() <= 15)
return nullptr;
return FT->getParamType(15);
case OpCode::ReportHit:
if (FT->getNumParams() <= 3)
return nullptr;
return FT->getParamType(3);
case OpCode::CreateHandle:
case OpCode::BufferUpdateCounter:
case OpCode::GetDimensions:
case OpCode::Texture2DMSGetSamplePosition:
case OpCode::RenderTargetGetSamplePosition:
case OpCode::RenderTargetGetSampleCount:
case OpCode::Barrier:
case OpCode::Discard:
case OpCode::EmitStream:
case OpCode::CutStream:
case OpCode::EmitThenCutStream:
case OpCode::CycleCounterLegacy:
case OpCode::WaveIsFirstLane:
case OpCode::WaveGetLaneIndex:
case OpCode::WaveGetLaneCount:
case OpCode::WaveAnyTrue:
case OpCode::WaveAllTrue:
case OpCode::WaveActiveBallot:
case OpCode::BitcastI16toF16:
case OpCode::BitcastF16toI16:
case OpCode::BitcastI32toF32:
case OpCode::BitcastF32toI32:
case OpCode::BitcastI64toF64:
case OpCode::BitcastF64toI64:
case OpCode::LegacyF32ToF16:
case OpCode::LegacyF16ToF32:
case OpCode::LegacyDoubleToFloat:
case OpCode::LegacyDoubleToSInt32:
case OpCode::LegacyDoubleToUInt32:
case OpCode::WaveAllBitCount:
case OpCode::WavePrefixBitCount:
case OpCode::IgnoreHit:
case OpCode::AcceptHitAndEndSearch:
case OpCode::WaveMultiPrefixBitCount:
case OpCode::SetMeshOutputCounts:
case OpCode::EmitIndices:
case OpCode::WriteSamplerFeedback:
case OpCode::WriteSamplerFeedbackBias:
case OpCode::WriteSamplerFeedbackLevel:
case OpCode::WriteSamplerFeedbackGrad:
case OpCode::AllocateRayQuery:
case OpCode::RayQuery_TraceRayInline:
case OpCode::RayQuery_Abort:
case OpCode::RayQuery_CommitNonOpaqueTriangleHit:
case OpCode::RayQuery_CommitProceduralPrimitiveHit:
case OpCode::AnnotateHandle:
case OpCode::CreateHandleFromBinding:
case OpCode::CreateHandleFromHeap:
case OpCode::Reserved0:
case OpCode::Reserved1:
case OpCode::Reserved2:
case OpCode::Reserved3:
case OpCode::Reserved4:
case OpCode::Reserved5:
case OpCode::Reserved6:
case OpCode::Reserved7:
case OpCode::Reserved8:
case OpCode::Reserved9:
case OpCode::Reserved10:
case OpCode::Reserved11:
case OpCode::AllocateNodeOutputRecords:
case OpCode::IncrementOutputCount:
case OpCode::OutputComplete:
case OpCode::GetInputRecordCount:
case OpCode::FinishedCrossGroupSharing:
case OpCode::BarrierByMemoryType:
case OpCode::BarrierByMemoryHandle:
case OpCode::BarrierByNodeRecordHandle:
case OpCode::CreateNodeOutputHandle:
case OpCode::IndexNodeHandle:
case OpCode::AnnotateNodeHandle:
case OpCode::CreateNodeInputRecordHandle:
case OpCode::AnnotateNodeRecordHandle:
case OpCode::NodeOutputIsValid:
case OpCode::GetRemainingRecursionLevels:
return Type::getVoidTy(Ctx);
case OpCode::CheckAccessFullyMapped:
case OpCode::SampleIndex:
case OpCode::Coverage:
case OpCode::InnerCoverage:
case OpCode::ThreadId:
case OpCode::GroupId:
case OpCode::ThreadIdInGroup:
case OpCode::FlattenedThreadIdInGroup:
case OpCode::GSInstanceID:
case OpCode::OutputControlPointID:
case OpCode::PrimitiveID:
case OpCode::ViewID:
case OpCode::InstanceID:
case OpCode::InstanceIndex:
case OpCode::HitKind:
case OpCode::RayFlags:
case OpCode::DispatchRaysIndex:
case OpCode::DispatchRaysDimensions:
case OpCode::PrimitiveIndex:
case OpCode::Dot4AddI8Packed:
case OpCode::Dot4AddU8Packed:
case OpCode::RayQuery_CommittedStatus:
case OpCode::RayQuery_CandidateType:
case OpCode::RayQuery_RayFlags:
case OpCode::RayQuery_CandidateInstanceIndex:
case OpCode::RayQuery_CandidateInstanceID:
case OpCode::RayQuery_CandidateGeometryIndex:
case OpCode::RayQuery_CandidatePrimitiveIndex:
case OpCode::RayQuery_CommittedInstanceIndex:
case OpCode::RayQuery_CommittedInstanceID:
case OpCode::RayQuery_CommittedGeometryIndex:
case OpCode::RayQuery_CommittedPrimitiveIndex:
case OpCode::GeometryIndex:
case OpCode::RayQuery_CandidateInstanceContributionToHitGroupIndex:
case OpCode::RayQuery_CommittedInstanceContributionToHitGroupIndex:
case OpCode::StartVertexLocation:
case OpCode::StartInstanceLocation:
return IntegerType::get(Ctx, 32);
case OpCode::CalculateLOD:
case OpCode::DomainLocation:
case OpCode::WorldRayOrigin:
case OpCode::WorldRayDirection:
case OpCode::ObjectRayOrigin:
case OpCode::ObjectRayDirection:
case OpCode::ObjectToWorld:
case OpCode::WorldToObject:
case OpCode::RayTMin:
case OpCode::RayTCurrent:
case OpCode::RayQuery_CandidateObjectToWorld3x4:
case OpCode::RayQuery_CandidateWorldToObject3x4:
case OpCode::RayQuery_CommittedObjectToWorld3x4:
case OpCode::RayQuery_CommittedWorldToObject3x4:
case OpCode::RayQuery_CandidateTriangleBarycentrics:
case OpCode::RayQuery_CommittedTriangleBarycentrics:
case OpCode::RayQuery_WorldRayOrigin:
case OpCode::RayQuery_WorldRayDirection:
case OpCode::RayQuery_RayTMin:
case OpCode::RayQuery_CandidateTriangleRayT:
case OpCode::RayQuery_CommittedRayT:
case OpCode::RayQuery_CandidateObjectRayOrigin:
case OpCode::RayQuery_CandidateObjectRayDirection:
case OpCode::RayQuery_CommittedObjectRayOrigin:
case OpCode::RayQuery_CommittedObjectRayDirection:
return Type::getFloatTy(Ctx);
case OpCode::MakeDouble:
case OpCode::SplitDouble:
return Type::getDoubleTy(Ctx);
case OpCode::RayQuery_Proceed:
case OpCode::RayQuery_CandidateProceduralPrimitiveNonOpaque:
case OpCode::RayQuery_CandidateTriangleFrontFace:
case OpCode::RayQuery_CommittedTriangleFrontFace:
case OpCode::IsHelperLane:
case OpCode::QuadVote:
return IntegerType::get(Ctx, 1);
case OpCode::CBufferLoadLegacy:
case OpCode::Sample:
case OpCode::SampleBias:
case OpCode::SampleLevel:
case OpCode::SampleGrad:
case OpCode::SampleCmp:
case OpCode::SampleCmpLevelZero:
case OpCode::TextureLoad:
case OpCode::BufferLoad:
case OpCode::TextureGather:
case OpCode::TextureGatherCmp:
case OpCode::RawBufferLoad:
case OpCode::Unpack4x8:
case OpCode::TextureGatherRaw:
case OpCode::SampleCmpLevel:
case OpCode::SampleCmpGrad:
case OpCode::SampleCmpBias: {
StructType *ST = cast<StructType>(Ty);
return ST->getElementType(0);
}
// OPCODE-OLOAD-TYPES:END
default:
return Ty;
}
}
Type *OP::GetHandleType() const { return m_pHandleType; }
Type *OP::GetNodeHandleType() const { return m_pNodeHandleType; }
Type *OP::GetNodeRecordHandleType() const { return m_pNodeRecordHandleType; }
Type *OP::GetResourcePropertiesType() const {
return m_pResourcePropertiesType;
}
Type *OP::GetNodePropertiesType() const { return m_pNodePropertiesType; }
Type *OP::GetNodeRecordPropertiesType() const {
return m_pNodeRecordPropertiesType;
}
Type *OP::GetResourceBindingType() const { return m_pResourceBindingType; }
Type *OP::GetDimensionsType() const { return m_pDimensionsType; }
Type *OP::GetSamplePosType() const { return m_pSamplePosType; }
Type *OP::GetBinaryWithCarryType() const { return m_pBinaryWithCarryType; }
Type *OP::GetBinaryWithTwoOutputsType() const {
return m_pBinaryWithTwoOutputsType;
}
Type *OP::GetSplitDoubleType() const { return m_pSplitDoubleType; }
Type *OP::GetFourI32Type() const { return m_pFourI32Type; }
Type *OP::GetFourI16Type() const { return m_pFourI16Type; }
bool OP::IsResRetType(llvm::Type *Ty) {
for (Type *ResTy : m_pResRetType) {
if (Ty == ResTy)
return true;
}
return false;
}
Type *OP::GetResRetType(Type *pOverloadType) {
unsigned TypeSlot = GetTypeSlot(pOverloadType);
if (m_pResRetType[TypeSlot] == nullptr) {
string TypeName("dx.types.ResRet.");
TypeName += GetOverloadTypeName(TypeSlot);
Type *FieldTypes[5] = {pOverloadType, pOverloadType, pOverloadType,
pOverloadType, Type::getInt32Ty(m_Ctx)};
m_pResRetType[TypeSlot] =
GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule);
}
return m_pResRetType[TypeSlot];
}
Type *OP::GetCBufferRetType(Type *pOverloadType) {
unsigned TypeSlot = GetTypeSlot(pOverloadType);
if (m_pCBufferRetType[TypeSlot] == nullptr) {
DXASSERT(m_LowPrecisionMode != DXIL::LowPrecisionMode::Undefined,
"m_LowPrecisionMode must be set before constructing type.");
string TypeName("dx.types.CBufRet.");
TypeName += GetOverloadTypeName(TypeSlot);
Type *i64Ty = Type::getInt64Ty(pOverloadType->getContext());
Type *i16Ty = Type::getInt16Ty(pOverloadType->getContext());
if (pOverloadType->isDoubleTy() || pOverloadType == i64Ty) {
Type *FieldTypes[2] = {pOverloadType, pOverloadType};
m_pCBufferRetType[TypeSlot] =
GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule);
} else if (!UseMinPrecision() &&
(pOverloadType->isHalfTy() || pOverloadType == i16Ty)) {
TypeName += ".8"; // dx.types.CBufRet.fp16.8 for buffer of 8 halves
Type *FieldTypes[8] = {
pOverloadType, pOverloadType, pOverloadType, pOverloadType,
pOverloadType, pOverloadType, pOverloadType, pOverloadType,
};
m_pCBufferRetType[TypeSlot] =
GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule);
} else {
Type *FieldTypes[4] = {pOverloadType, pOverloadType, pOverloadType,
pOverloadType};
m_pCBufferRetType[TypeSlot] =
GetOrCreateStructType(m_Ctx, FieldTypes, TypeName, m_pModule);
}
}
return m_pCBufferRetType[TypeSlot];
}
Type *OP::GetVectorType(unsigned numElements, Type *pOverloadType) {
if (numElements == 4) {
if (pOverloadType == Type::getInt32Ty(pOverloadType->getContext())) {
return m_pFourI32Type;
} else if (pOverloadType == Type::getInt16Ty(pOverloadType->getContext())) {
return m_pFourI16Type;
}
}
DXASSERT(false, "unexpected overload type");
return nullptr;
}
//------------------------------------------------------------------------------
//
// LLVM utility methods.
//
Constant *OP::GetI1Const(bool v) {
return Constant::getIntegerValue(IntegerType::get(m_Ctx, 1), APInt(1, v));
}
Constant *OP::GetI8Const(char v) {
return Constant::getIntegerValue(IntegerType::get(m_Ctx, 8), APInt(8, v));
}
Constant *OP::GetU8Const(unsigned char v) { return GetI8Const((char)v); }
Constant *OP::GetI16Const(int v) {
return Constant::getIntegerValue(IntegerType::get(m_Ctx, 16), APInt(16, v));
}
Constant *OP::GetU16Const(unsigned v) { return GetI16Const((int)v); }
Constant *OP::GetI32Const(int v) {
return Constant::getIntegerValue(IntegerType::get(m_Ctx, 32), APInt(32, v));
}
Constant *OP::GetU32Const(unsigned v) { return GetI32Const((int)v); }
Constant *OP::GetU64Const(unsigned long long v) {
return Constant::getIntegerValue(IntegerType::get(m_Ctx, 64), APInt(64, v));
}
Constant *OP::GetFloatConst(float v) {
return ConstantFP::get(m_Ctx, APFloat(v));
}
Constant *OP::GetDoubleConst(double v) {
return ConstantFP::get(m_Ctx, APFloat(v));
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilResourceBase.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilResourceBase.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilResourceBase.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/Constant.h"
namespace hlsl {
//------------------------------------------------------------------------------
//
// ResourceBase methods.
//
DxilResourceBase::DxilResourceBase(Class C)
: m_Class(C), m_Kind(Kind::Invalid), m_ID(UINT_MAX), m_SpaceID(0),
m_LowerBound(0), m_RangeSize(0), m_pSymbol(nullptr), m_pHandle(nullptr),
m_pHLSLTy(nullptr) {}
DxilResourceBase::Class DxilResourceBase::GetClass() const { return m_Class; }
DxilResourceBase::Kind DxilResourceBase::GetKind() const { return m_Kind; }
void DxilResourceBase::SetKind(DxilResourceBase::Kind ResourceKind) {
DXASSERT(ResourceKind > Kind::Invalid && ResourceKind < Kind::NumEntries,
"otherwise the caller passed wrong resource type");
m_Kind = ResourceKind;
}
unsigned DxilResourceBase::GetID() const { return m_ID; }
unsigned DxilResourceBase::GetSpaceID() const { return m_SpaceID; }
unsigned DxilResourceBase::GetLowerBound() const { return m_LowerBound; }
unsigned DxilResourceBase::GetUpperBound() const {
return m_RangeSize != UINT_MAX ? m_LowerBound + m_RangeSize - 1 : UINT_MAX;
}
unsigned DxilResourceBase::GetRangeSize() const { return m_RangeSize; }
llvm::Constant *DxilResourceBase::GetGlobalSymbol() const { return m_pSymbol; }
const std::string &DxilResourceBase::GetGlobalName() const { return m_Name; }
llvm::Value *DxilResourceBase::GetHandle() const { return m_pHandle; }
// If m_pHLSLTy is nullptr, HLSL type is the type of m_pSymbol.
// In sm6.6, type of m_pSymbol will be mutated to handleTy, m_pHLSLTy will save
// the original HLSL type.
llvm::Type *DxilResourceBase::GetHLSLType() const {
return m_pHLSLTy == nullptr ? m_pSymbol->getType() : m_pHLSLTy;
}
bool DxilResourceBase::IsAllocated() const { return m_LowerBound != UINT_MAX; }
bool DxilResourceBase::IsUnbounded() const { return m_RangeSize == UINT_MAX; }
void DxilResourceBase::SetClass(Class C) { m_Class = C; }
void DxilResourceBase::SetID(unsigned ID) { m_ID = ID; }
void DxilResourceBase::SetSpaceID(unsigned SpaceID) { m_SpaceID = SpaceID; }
void DxilResourceBase::SetLowerBound(unsigned LB) { m_LowerBound = LB; }
void DxilResourceBase::SetRangeSize(unsigned RangeSize) {
m_RangeSize = RangeSize;
}
void DxilResourceBase::SetGlobalSymbol(llvm::Constant *pGV) { m_pSymbol = pGV; }
void DxilResourceBase::SetGlobalName(const std::string &Name) { m_Name = Name; }
void DxilResourceBase::SetHandle(llvm::Value *pHandle) { m_pHandle = pHandle; }
void DxilResourceBase::SetHLSLType(llvm::Type *pTy) { m_pHLSLTy = pTy; }
static const char *s_ResourceClassNames[] = {"texture", "UAV", "cbuffer",
"sampler"};
static_assert(_countof(s_ResourceClassNames) ==
(unsigned)DxilResourceBase::Class::Invalid,
"Resource class names array must be updated when new resource "
"class enums are added.");
const char *DxilResourceBase::GetResClassName() const {
return s_ResourceClassNames[(unsigned)m_Class];
}
static const char *s_ResourceIDPrefixes[] = {"T", "U", "CB", "S"};
static_assert(_countof(s_ResourceIDPrefixes) ==
(unsigned)DxilResourceBase::Class::Invalid,
"Resource id prefixes array must be updated when new resource "
"class enums are added.");
const char *DxilResourceBase::GetResIDPrefix() const {
return s_ResourceIDPrefixes[(unsigned)m_Class];
}
static const char *s_ResourceBindPrefixes[] = {"t", "u", "cb", "s"};
static_assert(_countof(s_ResourceBindPrefixes) ==
(unsigned)DxilResourceBase::Class::Invalid,
"Resource bind prefixes array must be updated when new resource "
"class enums are added.");
const char *DxilResourceBase::GetResBindPrefix() const {
return s_ResourceBindPrefixes[(unsigned)m_Class];
}
static const char *s_ResourceDimNames[] = {
"invalid", "1d", "2d", "2dMS", "3d",
"cube", "1darray", "2darray", "2darrayMS", "cubearray",
"buf", "rawbuf", "structbuf", "cbuffer", "sampler",
"tbuffer", "ras", "fbtex2d", "fbtex2darray",
};
static_assert(_countof(s_ResourceDimNames) ==
(unsigned)DxilResourceBase::Kind::NumEntries,
"Resource dim names array must be updated when new resource kind "
"enums are added.");
const char *DxilResourceBase::GetResDimName() const {
return s_ResourceDimNames[(unsigned)m_Kind];
}
static const char *s_ResourceKindNames[] = {
"invalid",
"Texture1D",
"Texture2D",
"Texture2DMS",
"Texture3D",
"TextureCube",
"Texture1DArray",
"Texture2DArray",
"Texture2DMSArray",
"TextureCubeArray",
"TypedBuffer",
"RawBuffer",
"StructuredBuffer",
"CBuffer",
"Sampler",
"TBuffer",
"RTAccelerationStructure",
"FeedbackTexture2D",
"FeedbackTexture2DArray",
};
static_assert(_countof(s_ResourceKindNames) ==
(unsigned)DxilResourceBase::Kind::NumEntries,
"Resource kind names array must be updated when new resource "
"kind enums are added.");
const char *DxilResourceBase::GetResKindName() const {
return GetResourceKindName(m_Kind);
}
const char *GetResourceKindName(DXIL::ResourceKind K) {
return s_ResourceKindNames[(unsigned)K];
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilShaderFlags.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilShaderFlags.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilShaderFlags.h"
#include "dxc/DXIL/DxilEntryProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResource.h"
#include "dxc/DXIL/DxilResourceBinding.h"
#include "dxc/DXIL/DxilResourceProperties.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/Casting.h"
using namespace hlsl;
using namespace llvm;
ShaderFlags::ShaderFlags()
: m_bDisableOptimizations(false), m_bDisableMathRefactoring(false),
m_bEnableDoublePrecision(false), m_bForceEarlyDepthStencil(false),
m_bEnableRawAndStructuredBuffers(false), m_bLowPrecisionPresent(false),
m_bEnableDoubleExtensions(false), m_bEnableMSAD(false),
m_bAllResourcesBound(false), m_bViewportAndRTArrayIndex(false),
m_bInnerCoverage(false), m_bStencilRef(false), m_bTiledResources(false),
m_bUAVLoadAdditionalFormats(false), m_bLevel9ComparisonFiltering(false),
m_b64UAVs(false), m_UAVsAtEveryStage(false),
m_bCSRawAndStructuredViaShader4X(false), m_bROVS(false),
m_bWaveOps(false), m_bInt64Ops(false), m_bViewID(false),
m_bBarycentrics(false), m_bUseNativeLowPrecision(false),
m_bShadingRate(false), m_bRaytracingTier1_1(false),
m_bSamplerFeedback(false), m_bAtomicInt64OnTypedResource(false),
m_bAtomicInt64OnGroupShared(false),
m_bDerivativesInMeshAndAmpShaders(false),
m_bResourceDescriptorHeapIndexing(false),
m_bSamplerDescriptorHeapIndexing(false),
m_bAtomicInt64OnHeapResource(false), m_bResMayNotAlias(false),
m_bAdvancedTextureOps(false), m_bWriteableMSAATextures(false),
m_bReserved(false), m_bSampleCmpGradientOrBias(false),
m_bExtendedCommandInfo(false), m_bUsesDerivatives(false),
m_bRequiresGroup(false), m_align1(0) {
// Silence unused field warnings
(void)m_align1;
}
uint64_t ShaderFlags::GetFeatureInfo() const {
uint64_t Flags = 0;
Flags |= m_bEnableDoublePrecision ? hlsl::DXIL::ShaderFeatureInfo_Doubles : 0;
Flags |= m_bLowPrecisionPresent && !m_bUseNativeLowPrecision
? hlsl::DXIL::ShaderFeatureInfo_MinimumPrecision
: 0;
Flags |= m_bLowPrecisionPresent && m_bUseNativeLowPrecision
? hlsl::DXIL::ShaderFeatureInfo_NativeLowPrecision
: 0;
Flags |= m_bEnableDoubleExtensions
? hlsl::DXIL::ShaderFeatureInfo_11_1_DoubleExtensions
: 0;
Flags |= m_bWaveOps ? hlsl::DXIL::ShaderFeatureInfo_WaveOps : 0;
Flags |= m_bInt64Ops ? hlsl::DXIL::ShaderFeatureInfo_Int64Ops : 0;
Flags |= m_bROVS ? hlsl::DXIL::ShaderFeatureInfo_ROVs : 0;
Flags |=
m_bViewportAndRTArrayIndex
? hlsl::DXIL::
ShaderFeatureInfo_ViewportAndRTArrayIndexFromAnyShaderFeedingRasterizer
: 0;
Flags |= m_bInnerCoverage ? hlsl::DXIL::ShaderFeatureInfo_InnerCoverage : 0;
Flags |= m_bStencilRef ? hlsl::DXIL::ShaderFeatureInfo_StencilRef : 0;
Flags |= m_bTiledResources ? hlsl::DXIL::ShaderFeatureInfo_TiledResources : 0;
Flags |=
m_bEnableMSAD ? hlsl::DXIL::ShaderFeatureInfo_11_1_ShaderExtensions : 0;
Flags |=
m_bCSRawAndStructuredViaShader4X
? hlsl::DXIL::
ShaderFeatureInfo_ComputeShadersPlusRawAndStructuredBuffersViaShader4X
: 0;
Flags |=
m_UAVsAtEveryStage ? hlsl::DXIL::ShaderFeatureInfo_UAVsAtEveryStage : 0;
Flags |= m_b64UAVs ? hlsl::DXIL::ShaderFeatureInfo_64UAVs : 0;
Flags |= m_bLevel9ComparisonFiltering
? hlsl::DXIL::ShaderFeatureInfo_LEVEL9ComparisonFiltering
: 0;
Flags |= m_bUAVLoadAdditionalFormats
? hlsl::DXIL::ShaderFeatureInfo_TypedUAVLoadAdditionalFormats
: 0;
Flags |= m_bViewID ? hlsl::DXIL::ShaderFeatureInfo_ViewID : 0;
Flags |= m_bBarycentrics ? hlsl::DXIL::ShaderFeatureInfo_Barycentrics : 0;
Flags |= m_bShadingRate ? hlsl::DXIL::ShaderFeatureInfo_ShadingRate : 0;
Flags |= m_bRaytracingTier1_1
? hlsl::DXIL::ShaderFeatureInfo_Raytracing_Tier_1_1
: 0;
Flags |=
m_bSamplerFeedback ? hlsl::DXIL::ShaderFeatureInfo_SamplerFeedback : 0;
Flags |= m_bAtomicInt64OnTypedResource
? hlsl::DXIL::ShaderFeatureInfo_AtomicInt64OnTypedResource
: 0;
Flags |= m_bAtomicInt64OnGroupShared
? hlsl::DXIL::ShaderFeatureInfo_AtomicInt64OnGroupShared
: 0;
Flags |= m_bDerivativesInMeshAndAmpShaders
? hlsl::DXIL::ShaderFeatureInfo_DerivativesInMeshAndAmpShaders
: 0;
Flags |= m_bResourceDescriptorHeapIndexing
? hlsl::DXIL::ShaderFeatureInfo_ResourceDescriptorHeapIndexing
: 0;
Flags |= m_bSamplerDescriptorHeapIndexing
? hlsl::DXIL::ShaderFeatureInfo_SamplerDescriptorHeapIndexing
: 0;
Flags |= m_bAtomicInt64OnHeapResource
? hlsl::DXIL::ShaderFeatureInfo_AtomicInt64OnHeapResource
: 0;
Flags |= m_bAdvancedTextureOps
? hlsl::DXIL::ShaderFeatureInfo_AdvancedTextureOps
: 0;
Flags |= m_bWriteableMSAATextures
? hlsl::DXIL::ShaderFeatureInfo_WriteableMSAATextures
: 0;
Flags |= m_bSampleCmpGradientOrBias
? hlsl::DXIL::ShaderFeatureInfo_SampleCmpGradientOrBias
: 0;
Flags |= m_bExtendedCommandInfo
? hlsl::DXIL::ShaderFeatureInfo_ExtendedCommandInfo
: 0;
// Per-function flags
Flags |= m_bUsesDerivatives ? hlsl::DXIL::OptFeatureInfo_UsesDerivatives : 0;
Flags |= m_bRequiresGroup ? hlsl::DXIL::OptFeatureInfo_RequiresGroup : 0;
return Flags;
}
uint64_t ShaderFlags::GetShaderFlagsRaw() const {
union Cast {
Cast(const ShaderFlags &flags) { shaderFlags = flags; }
ShaderFlags shaderFlags;
uint64_t rawData;
};
static_assert(sizeof(uint64_t) == sizeof(ShaderFlags),
"size must match to make sure no undefined bits when cast");
Cast rawCast(*this);
return rawCast.rawData;
}
void ShaderFlags::SetShaderFlagsRaw(uint64_t data) {
union Cast {
Cast(uint64_t data) { rawData = data; }
ShaderFlags shaderFlags;
uint64_t rawData;
};
Cast rawCast(data);
*this = rawCast.shaderFlags;
}
uint64_t ShaderFlags::GetShaderFlagsRawForCollection() {
// This should be all the flags that can be set by
// DxilModule::CollectShaderFlags.
ShaderFlags Flags;
Flags.SetEnableDoublePrecision(true);
Flags.SetInt64Ops(true);
Flags.SetLowPrecisionPresent(true);
Flags.SetEnableDoubleExtensions(true);
Flags.SetWaveOps(true);
Flags.SetTiledResources(true);
Flags.SetEnableMSAD(true);
Flags.SetUAVLoadAdditionalFormats(true);
Flags.SetStencilRef(true);
Flags.SetInnerCoverage(true);
Flags.SetViewportAndRTArrayIndex(true);
Flags.Set64UAVs(true);
Flags.SetUAVsAtEveryStage(true);
Flags.SetEnableRawAndStructuredBuffers(true);
Flags.SetCSRawAndStructuredViaShader4X(true);
Flags.SetViewID(true);
Flags.SetBarycentrics(true);
Flags.SetShadingRate(true);
Flags.SetRaytracingTier1_1(true);
Flags.SetSamplerFeedback(true);
Flags.SetAtomicInt64OnTypedResource(true);
Flags.SetAtomicInt64OnGroupShared(true);
Flags.SetDerivativesInMeshAndAmpShaders(true);
Flags.SetResourceDescriptorHeapIndexing(true);
Flags.SetSamplerDescriptorHeapIndexing(true);
Flags.SetAtomicInt64OnHeapResource(true);
Flags.SetResMayNotAlias(true);
Flags.SetAdvancedTextureOps(true);
Flags.SetWriteableMSAATextures(true);
Flags.SetSampleCmpGradientOrBias(true);
Flags.SetExtendedCommandInfo(true);
Flags.SetUsesDerivatives(true);
Flags.SetRequiresGroup(true);
return Flags.GetShaderFlagsRaw();
}
unsigned ShaderFlags::GetGlobalFlags() const {
unsigned Flags = 0;
Flags |= m_bDisableOptimizations ? DXIL::kDisableOptimizations : 0;
Flags |= m_bDisableMathRefactoring ? DXIL::kDisableMathRefactoring : 0;
Flags |= m_bEnableDoublePrecision ? DXIL::kEnableDoublePrecision : 0;
Flags |= m_bForceEarlyDepthStencil ? DXIL::kForceEarlyDepthStencil : 0;
Flags |= m_bEnableRawAndStructuredBuffers
? DXIL::kEnableRawAndStructuredBuffers
: 0;
Flags |= m_bLowPrecisionPresent && !m_bUseNativeLowPrecision
? DXIL::kEnableMinPrecision
: 0;
Flags |= m_bEnableDoubleExtensions ? DXIL::kEnableDoubleExtensions : 0;
Flags |= m_bEnableMSAD ? DXIL::kEnableMSAD : 0;
Flags |= m_bAllResourcesBound ? DXIL::kAllResourcesBound : 0;
return Flags;
}
// Given a CreateHandle call, returns arbitrary ConstantInt rangeID
// Note: HLSL is currently assuming that rangeID is a constant value, but this
// code is assuming that it can be either constant, phi node, or select
// instruction
static ConstantInt *GetArbitraryConstantRangeID(CallInst *handleCall) {
Value *rangeID =
handleCall->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
ConstantInt *ConstantRangeID = dyn_cast<ConstantInt>(rangeID);
while (ConstantRangeID == nullptr) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(rangeID)) {
ConstantRangeID = CI;
} else if (PHINode *PN = dyn_cast<PHINode>(rangeID)) {
rangeID = PN->getIncomingValue(0);
} else if (SelectInst *SI = dyn_cast<SelectInst>(rangeID)) {
rangeID = SI->getTrueValue();
} else {
return nullptr;
}
}
return ConstantRangeID;
}
// Given a handle type, find an arbitrary call instructions to create handle
static CallInst *FindCallToCreateHandle(Value *handleType) {
Value *curVal = handleType;
CallInst *CI = dyn_cast<CallInst>(handleType);
while (CI == nullptr) {
if (PHINode *PN = dyn_cast<PHINode>(curVal)) {
curVal = PN->getIncomingValue(0);
} else if (SelectInst *SI = dyn_cast<SelectInst>(curVal)) {
curVal = SI->getTrueValue();
} else {
return nullptr;
}
CI = dyn_cast<CallInst>(curVal);
}
return CI;
}
DxilResourceProperties
GetResourcePropertyFromHandleCall(const hlsl::DxilModule *M,
CallInst *handleCall) {
DxilResourceProperties RP;
ConstantInt *HandleOpCodeConst = cast<ConstantInt>(
handleCall->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
DXIL::OpCode handleOp =
static_cast<DXIL::OpCode>(HandleOpCodeConst->getLimitedValue());
if (handleOp == DXIL::OpCode::CreateHandle) {
if (ConstantInt *resClassArg =
dyn_cast<ConstantInt>(handleCall->getArgOperand(
DXIL::OperandIndex::kCreateHandleResClassOpIdx))) {
DXIL::ResourceClass resClass =
static_cast<DXIL::ResourceClass>(resClassArg->getLimitedValue());
ConstantInt *rangeID = GetArbitraryConstantRangeID(handleCall);
if (rangeID) {
DxilResource resource;
if (resClass == DXIL::ResourceClass::UAV)
resource = M->GetUAV(rangeID->getLimitedValue());
else if (resClass == DXIL::ResourceClass::SRV)
resource = M->GetSRV(rangeID->getLimitedValue());
RP = resource_helper::loadPropsFromResourceBase(&resource);
}
}
} else if (handleOp == DXIL::OpCode::CreateHandleForLib) {
// If library handle, find DxilResource by checking the name
if (LoadInst *LI = dyn_cast<LoadInst>(handleCall->getArgOperand(
DXIL::OperandIndex::kCreateHandleForLibResOpIdx))) {
Value *resType = LI->getOperand(0);
for (auto &&res : M->GetUAVs()) {
if (res->GetGlobalSymbol() == resType) {
RP = resource_helper::loadPropsFromResourceBase(res.get());
}
}
}
} else if (handleOp == DXIL::OpCode::AnnotateHandle) {
DxilInst_AnnotateHandle annotateHandle(cast<Instruction>(handleCall));
RP = resource_helper::loadPropsFromAnnotateHandle(annotateHandle,
*M->GetShaderModel());
}
return RP;
}
struct ResourceKey {
uint8_t Class;
uint32_t Space;
uint32_t LowerBound;
uint32_t UpperBound;
};
struct ResKeyEq {
bool operator()(const ResourceKey &k1, const ResourceKey &k2) const {
return k1.Class == k2.Class && k1.Space == k2.Space &&
k1.LowerBound == k2.LowerBound && k1.UpperBound == k2.UpperBound;
}
};
struct ResKeyHash {
std::size_t operator()(const ResourceKey &k) const {
return std::hash<uint32_t>()(k.LowerBound) ^
(std::hash<uint32_t>()(k.UpperBound) << 1) ^
(std::hash<uint32_t>()(k.Space) << 2) ^
(std::hash<uint8_t>()(k.Class) << 3);
}
};
// Limited to retrieving handles created by CreateHandleFromBinding and
// CreateHandleForLib. returns null otherwise map should contain resources
// indexed by space, class, lower, and upper bounds
DxilResource *GetResourceFromAnnotateHandle(
const hlsl::DxilModule *M, CallInst *handleCall,
std::unordered_map<ResourceKey, DxilResource *, ResKeyHash, ResKeyEq>
resMap) {
DxilResource *resource = nullptr;
ConstantInt *HandleOpCodeConst = cast<ConstantInt>(
handleCall->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
DXIL::OpCode handleOp =
static_cast<DXIL::OpCode>(HandleOpCodeConst->getLimitedValue());
if (handleOp == DXIL::OpCode::AnnotateHandle) {
DxilInst_AnnotateHandle annotateHandle(cast<Instruction>(handleCall));
CallInst *createCall = cast<CallInst>(annotateHandle.get_res());
ConstantInt *HandleOpCodeConst = cast<ConstantInt>(
createCall->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
DXIL::OpCode handleOp =
static_cast<DXIL::OpCode>(HandleOpCodeConst->getLimitedValue());
if (handleOp == DXIL::OpCode::CreateHandleFromBinding) {
DxilInst_CreateHandleFromBinding fromBind(createCall);
DxilResourceBinding B = resource_helper::loadBindingFromConstant(
*cast<Constant>(fromBind.get_bind()));
ResourceKey key = {B.resourceClass, B.spaceID, B.rangeLowerBound,
B.rangeUpperBound};
resource = resMap[key];
} else if (handleOp == DXIL::OpCode::CreateHandleForLib) {
// If library handle, find DxilResource by checking the name
if (LoadInst *LI = dyn_cast<LoadInst>(createCall->getArgOperand(
DXIL::OperandIndex::kCreateHandleForLibResOpIdx))) {
Value *resType = LI->getOperand(0);
for (auto &&res : M->GetUAVs()) {
if (res->GetGlobalSymbol() == resType) {
return resource = res.get();
}
}
}
}
}
return resource;
}
static bool hasNonConstantSampleOffsets(const CallInst *CI) {
return (!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureSampleOffset0OpIdx)) ||
!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureSampleOffset1OpIdx)) ||
!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureSampleOffset2OpIdx)));
}
static bool hasSampleClamp(const CallInst *CI) {
Value *Clamp = CI->getArgOperand(CI->getNumArgOperands() - 1);
if (auto *Imm = dyn_cast<ConstantFP>(Clamp))
return !Imm->getValueAPF().isZero();
return !isa<UndefValue>(Clamp);
}
ShaderFlags ShaderFlags::CollectShaderFlags(const Function *F,
const hlsl::DxilModule *M) {
// NOTE: This function is meant to compute shader flags for a single function,
// potentially not knowing the final shader stage for the entry that may call
// this function.
// As such, do not depend on the shader model in the module, except for
// compatibility purposes. Doing so will fail to encode flags properly for
// libraries. The real, final shader flags will be adjusted after walking
// called functions and combining flags.
// For example, the use of derivatives impacts an optional flag when used from
// a mesh or amplification shader. It also impacts the minimum shader model
// for a compute shader. We do not make assumptions about that context here.
// Instead, we simply set a new UsesDerivatives flag to indicate that
// derivatives are used, then rely on AdjustMinimumShaderModelAndFlags to set
// the final flags correctly once we've merged all called functions.
// Place module-level detection in DxilModule::CollectShaderFlagsForModule.
ShaderFlags flag;
// Module level options
flag.SetUseNativeLowPrecision(!M->GetUseMinPrecision());
flag.SetDisableOptimizations(M->GetDisableOptimization());
flag.SetAllResourcesBound(M->GetAllResourcesBound());
bool hasDouble = false;
// ddiv dfma drcp d2i d2u i2d u2d.
// fma has dxil op. Others should check IR instruction div/cast.
bool hasDoubleExtension = false;
bool has64Int = false;
bool has16 = false;
bool hasWaveOps = false;
bool hasLodClamp = false;
bool hasCheckAccessFully = false;
bool hasMSAD = false;
bool hasStencilRef = false;
bool hasInnerCoverage = false;
bool hasViewID = false;
bool hasMulticomponentUAVLoads = false;
bool hasViewportOrRTArrayIndex = false;
bool hasShadingRate = false;
bool hasBarycentrics = false;
bool hasSamplerFeedback = false;
bool hasRaytracingTier1_1 = false;
bool hasAtomicInt64OnTypedResource = false;
bool hasAtomicInt64OnGroupShared = false;
bool hasDerivativesInMeshAndAmpShaders = false;
bool hasResourceDescriptorHeapIndexing = false;
bool hasSamplerDescriptorHeapIndexing = false;
bool hasAtomicInt64OnHeapResource = false;
bool hasUAVsGlobally = M->GetUAVs().size() > 0;
bool hasAdvancedTextureOps = false;
bool hasSampleCmpGradientOrBias = false;
bool hasExtendedCommandInfo = false;
// UsesDerivatives is used to indicate any derivative use per-function, before
// flags are combined from called functions. Later, the flags are adjusted for
// each entry point function in AdjustMinimumShaderModelAndFlags. This will
// set DerivativesInMeshAndAmpShaders if the entry point function or shader
// model is mesh or amplification shader.
bool hasDerivatives = false;
// RequiresGroup is used to indicate any group shared memory use per-function,
// before flags are combined from called functions. Later, this will allow
// enforcing of the thread launch node shader case which has no visible group.
bool requiresGroup = false;
// Try to maintain compatibility with a v1.0 validator if that's what we have.
uint32_t valMajor, valMinor;
M->GetValidatorVersion(valMajor, valMinor);
bool hasMulticomponentUAVLoadsBackCompat = valMajor == 1 && valMinor == 0;
bool hasViewportOrRTArrayIndexBackCombat = valMajor == 1 && valMinor < 4;
bool hasBarycentricsBackCompat = valMajor == 1 && valMinor < 6;
// Setting additional flag for downlevel shader model may cause some driver to
// fail shader create due to an unrecognized flag.
uint32_t dxilMajor, dxilMinor;
M->GetDxilVersion(dxilMajor, dxilMinor);
bool canSetResMayNotAlias =
DXIL::CompareVersions(dxilMajor, dxilMinor, 1, 7) >= 0;
// Use of LodClamp requires tiled resources, but a bug in validator 1.7 and
// lower didn't recognize this. So, if validator version < 1.8, don't set
// tiled resources flag based on LodClamp.
bool canSetTiledResourcesBasedOnLodClamp =
DXIL::CompareVersions(valMajor, valMinor, 1, 8) >= 0;
// Used to determine whether to set ResMayNotAlias flag.
// Prior to validator version 1.8, we based this on global presence of UAVs.
// Now, we base it on the use of UAVs in the function.
bool hasUAVs = DXIL::CompareVersions(valMajor, valMinor, 1, 8) < 0
? hasUAVsGlobally
: false;
Type *int16Ty = Type::getInt16Ty(F->getContext());
Type *int64Ty = Type::getInt64Ty(F->getContext());
// Before validator version 1.8, we set the WriteableMSAATextures flag based
// on the presence of RWTexture2DMS[Array] resources in the module.
bool setWriteableMSAATextures_1_7 =
DXIL::CompareVersions(valMajor, valMinor, 1, 8) < 0;
bool hasWriteableMSAATextures_1_7 = false;
bool hasWriteableMSAATextures = false;
// Set up resource to binding handle map for 64-bit atomics usage
std::unordered_map<ResourceKey, DxilResource *, ResKeyHash, ResKeyEq> resMap;
for (auto &res : M->GetUAVs()) {
ResourceKey key = {(uint8_t)res->GetClass(), res->GetSpaceID(),
res->GetLowerBound(), res->GetUpperBound()};
resMap.insert({key, res.get()});
// The flag was set for this function if any RWTexture2DMS[Array] resources
// existed in the module. Now, for compatibility, we need to track this
// flag so we can set it if validator version is < 1.8.
if (res->GetKind() == DXIL::ResourceKind::Texture2DMS ||
res->GetKind() == DXIL::ResourceKind::Texture2DMSArray)
hasWriteableMSAATextures_1_7 = true;
}
auto checkUsedResourceProps = [&](DxilResourceProperties RP) {
if (hasUAVs && hasWriteableMSAATextures)
return;
if (RP.isUAV()) {
hasUAVs = true;
if (RP.getResourceKind() == DXIL::ResourceKind::Texture2DMS ||
RP.getResourceKind() == DXIL::ResourceKind::Texture2DMSArray)
hasWriteableMSAATextures = true;
}
};
auto checkUsedHandle = [&](Value *resHandle) {
if (hasUAVs && hasWriteableMSAATextures)
return;
CallInst *handleCall = FindCallToCreateHandle(resHandle);
DxilResourceProperties RP =
GetResourcePropertyFromHandleCall(M, handleCall);
checkUsedResourceProps(RP);
};
for (const BasicBlock &BB : F->getBasicBlockList()) {
for (const Instruction &I : BB.getInstList()) {
// Skip none dxil function call.
if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
continue;
}
Type *Ty = I.getType();
bool isDouble = Ty->isDoubleTy();
bool isHalf = Ty->isHalfTy();
bool isInt16 = Ty == int16Ty;
bool isInt64 = Ty == int64Ty;
requiresGroup |= Ty->isPointerTy() &&
Ty->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
if (isa<ExtractElementInst>(&I) || isa<InsertElementInst>(&I))
continue;
for (Value *operand : I.operands()) {
Type *Ty = operand->getType();
isDouble |= Ty->isDoubleTy();
isHalf |= Ty->isHalfTy();
isInt16 |= Ty == int16Ty;
isInt64 |= Ty == int64Ty;
requiresGroup |= Ty->isPointerTy() &&
Ty->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
}
if (isDouble) {
hasDouble = true;
switch (I.getOpcode()) {
case Instruction::FDiv:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPToUI:
case Instruction::FPToSI:
hasDoubleExtension = true;
break;
}
}
if (isInt64) {
has64Int = true;
switch (I.getOpcode()) {
case Instruction::AtomicCmpXchg:
case Instruction::AtomicRMW:
hasAtomicInt64OnGroupShared = true;
break;
}
}
has16 |= isHalf;
has16 |= isInt16;
if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
continue;
DXIL::OpCode dxilOp = hlsl::OP::getOpCode(CI);
if (dxilOp == DXIL::OpCode::NumOpCodes)
continue;
if (hlsl::OP::IsDxilOpWave(dxilOp))
hasWaveOps = true;
switch (dxilOp) {
case DXIL::OpCode::CheckAccessFullyMapped:
hasCheckAccessFully = true;
break;
case DXIL::OpCode::Msad:
hasMSAD = true;
break;
case DXIL::OpCode::TextureLoad:
if (!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureLoadOffset0OpIdx)) ||
!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureLoadOffset1OpIdx)) ||
!isa<Constant>(CI->getArgOperand(
DXIL::OperandIndex::kTextureLoadOffset2OpIdx)))
hasAdvancedTextureOps = true;
LLVM_FALLTHROUGH;
case DXIL::OpCode::BufferLoad: {
if (hasMulticomponentUAVLoads)
continue;
// This is the old-style computation (overestimating requirements).
Value *resHandle =
CI->getArgOperand(DXIL::OperandIndex::kBufferLoadHandleOpIdx);
CallInst *handleCall = FindCallToCreateHandle(resHandle);
// Check if this is a library handle or general create handle
if (handleCall) {
DxilResourceProperties RP =
GetResourcePropertyFromHandleCall(M, handleCall);
if (RP.isUAV()) {
// Validator 1.0 assumes that all uav load is multi component
// load.
if (hasMulticomponentUAVLoadsBackCompat) {
hasMulticomponentUAVLoads = true;
continue;
} else {
if (DXIL::IsTyped(RP.getResourceKind()) &&
RP.Typed.CompCount > 1)
hasMulticomponentUAVLoads = true;
}
}
}
} break;
case DXIL::OpCode::Fma:
hasDoubleExtension |= isDouble;
break;
case DXIL::OpCode::InnerCoverage:
hasInnerCoverage = true;
break;
case DXIL::OpCode::ViewID:
hasViewID = true;
break;
case DXIL::OpCode::AllocateRayQuery:
case DXIL::OpCode::GeometryIndex:
hasRaytracingTier1_1 = true;
break;
case DXIL::OpCode::AttributeAtVertex:
hasBarycentrics = true;
break;
case DXIL::OpCode::AtomicBinOp:
case DXIL::OpCode::AtomicCompareExchange:
if (isInt64) {
Value *resHandle =
CI->getArgOperand(DXIL::OperandIndex::kAtomicBinOpHandleOpIdx);
CallInst *handleCall = FindCallToCreateHandle(resHandle);
DxilResourceProperties RP =
GetResourcePropertyFromHandleCall(M, handleCall);
if (DXIL::IsTyped(RP.getResourceKind()))
hasAtomicInt64OnTypedResource = true;
// set uses 64-bit flag if relevant
if (DxilResource *res =
GetResourceFromAnnotateHandle(M, handleCall, resMap)) {
res->SetHasAtomic64Use(true);
} else {
// Assuming CreateHandleFromHeap, which indicates a descriptor
hasAtomicInt64OnHeapResource = true;
}
}
break;
case DXIL::OpCode::SampleLevel:
case DXIL::OpCode::SampleCmpLevelZero:
hasAdvancedTextureOps |= hasNonConstantSampleOffsets(CI);
break;
case DXIL::OpCode::SampleGrad:
case DXIL::OpCode::SampleCmpGrad:
hasAdvancedTextureOps |= hasNonConstantSampleOffsets(CI);
hasLodClamp |= hasSampleClamp(CI);
hasSampleCmpGradientOrBias = dxilOp == DXIL::OpCode::SampleCmpGrad;
break;
case DXIL::OpCode::Sample:
case DXIL::OpCode::SampleBias:
case DXIL::OpCode::SampleCmp:
case DXIL::OpCode::SampleCmpBias:
hasAdvancedTextureOps |= hasNonConstantSampleOffsets(CI);
hasLodClamp |= hasSampleClamp(CI);
hasSampleCmpGradientOrBias = dxilOp == DXIL::OpCode::SampleCmpBias;
LLVM_FALLTHROUGH;
case DXIL::OpCode::DerivFineX:
case DXIL::OpCode::DerivFineY:
case DXIL::OpCode::DerivCoarseX:
case DXIL::OpCode::DerivCoarseY:
case DXIL::OpCode::CalculateLOD: {
hasDerivatives = true;
} break;
case DXIL::OpCode::CreateHandleFromHeap: {
ConstantInt *isSamplerVal = dyn_cast<ConstantInt>(CI->getArgOperand(
DXIL::OperandIndex::kCreateHandleFromHeapSamplerHeapOpIdx));
if (isSamplerVal->getLimitedValue()) {
hasSamplerDescriptorHeapIndexing = true;
} else {
hasResourceDescriptorHeapIndexing = true;
if (!hasUAVs) {
// If not already marked, check if UAV.
DxilResourceProperties RP = GetResourcePropertyFromHandleCall(
M, const_cast<CallInst *>(CI));
if (RP.isUAV())
hasUAVs = true;
}
}
} break;
case DXIL::OpCode::CreateHandle:
case DXIL::OpCode::CreateHandleForLib:
case DXIL::OpCode::AnnotateHandle:
checkUsedHandle(const_cast<CallInst *>(CI));
break;
case DXIL::OpCode::TextureStoreSample:
hasWriteableMSAATextures_1_7 = true;
hasWriteableMSAATextures = true;
LLVM_FALLTHROUGH;
case DXIL::OpCode::SampleCmpLevel:
case DXIL::OpCode::TextureGatherRaw:
hasAdvancedTextureOps = true;
break;
case DXIL::OpCode::StartVertexLocation:
case DXIL::OpCode::StartInstanceLocation:
hasExtendedCommandInfo = true;
break;
case DXIL::OpCode::Barrier:
case DXIL::OpCode::BarrierByMemoryType:
case DXIL::OpCode::BarrierByMemoryHandle:
case DXIL::OpCode::BarrierByNodeRecordHandle:
if (OP::BarrierRequiresGroup(CI))
requiresGroup = true;
break;
default:
// Normal opcodes.
break;
}
}
}
}
// If this function is a shader, add flags based on signatures
if (M->HasDxilEntryProps(F)) {
const DxilEntryProps &entryProps = M->GetDxilEntryProps(F);
// Val ver < 1.4 has a bug where input case was always clobbered by the
// output check. The only case where it made a difference such that an
// incorrect flag would be set was for the HS and DS input cases.
// It was also checking PS input and output, but PS output could not have
// the semantic, and since it was clobbering the result, it would always
// clear it. Since this flag should not be set for PS at all,
// it produced the correct result for PS by accident.
bool checkInputRTArrayIndex = entryProps.props.IsGS();
if (!hasViewportOrRTArrayIndexBackCombat)
checkInputRTArrayIndex |=
entryProps.props.IsDS() || entryProps.props.IsHS();
bool checkOutputRTArrayIndex = entryProps.props.IsVS() ||
entryProps.props.IsDS() ||
entryProps.props.IsHS();
for (auto &&E : entryProps.sig.InputSignature.GetElements()) {
switch (E->GetKind()) {
case Semantic::Kind::ViewPortArrayIndex:
case Semantic::Kind::RenderTargetArrayIndex:
if (checkInputRTArrayIndex)
hasViewportOrRTArrayIndex = true;
break;
case Semantic::Kind::ShadingRate:
hasShadingRate = true;
break;
case Semantic::Kind::Barycentrics:
hasBarycentrics = true;
break;
default:
break;
}
}
for (auto &&E : entryProps.sig.OutputSignature.GetElements()) {
switch (E->GetKind()) {
case Semantic::Kind::ViewPortArrayIndex:
case Semantic::Kind::RenderTargetArrayIndex:
if (checkOutputRTArrayIndex)
hasViewportOrRTArrayIndex = true;
break;
case Semantic::Kind::StencilRef:
if (entryProps.props.IsPS())
hasStencilRef = true;
break;
case Semantic::Kind::InnerCoverage:
if (entryProps.props.IsPS())
hasInnerCoverage = true;
break;
case Semantic::Kind::ShadingRate:
hasShadingRate = true;
break;
default:
break;
}
}
// If we know this function is MS or AS, go ahead and set this flag now.
if (hasDerivatives &&
(entryProps.props.IsMS() || entryProps.props.IsAS())) {
hasDerivativesInMeshAndAmpShaders = true;
}
}
if (hasDerivatives && DXIL::CompareVersions(valMajor, valMinor, 1, 8) < 0) {
// Before validator version 1.8, UsesDerivatives flag was not set, and we
// set the DerivativesInMeshAndAmpShaders only if the shader model in the
// module is mesh or amplification.
hasDerivatives = false;
const ShaderModel *SM = M->GetShaderModel();
if (!(SM->IsMS() || SM->IsAS()))
hasDerivativesInMeshAndAmpShaders = false;
}
if (requiresGroup && DXIL::CompareVersions(valMajor, valMinor, 1, 8) < 0) {
// Before validator version 1.8, RequiresGroup flag did not exist.
requiresGroup = false;
}
flag.SetEnableDoublePrecision(hasDouble);
flag.SetStencilRef(hasStencilRef);
flag.SetInnerCoverage(hasInnerCoverage);
flag.SetInt64Ops(has64Int);
flag.SetLowPrecisionPresent(has16);
flag.SetEnableDoubleExtensions(hasDoubleExtension);
flag.SetWaveOps(hasWaveOps);
flag.SetTiledResources(hasCheckAccessFully ||
(canSetTiledResourcesBasedOnLodClamp && hasLodClamp));
flag.SetEnableMSAD(hasMSAD);
flag.SetUAVLoadAdditionalFormats(hasMulticomponentUAVLoads);
flag.SetViewID(hasViewID);
flag.SetViewportAndRTArrayIndex(hasViewportOrRTArrayIndex);
flag.SetShadingRate(hasShadingRate);
flag.SetBarycentrics(hasBarycentricsBackCompat ? false : hasBarycentrics);
flag.SetSamplerFeedback(hasSamplerFeedback);
flag.SetRaytracingTier1_1(hasRaytracingTier1_1);
flag.SetAtomicInt64OnTypedResource(hasAtomicInt64OnTypedResource);
flag.SetAtomicInt64OnGroupShared(hasAtomicInt64OnGroupShared);
flag.SetDerivativesInMeshAndAmpShaders(hasDerivativesInMeshAndAmpShaders);
flag.SetResourceDescriptorHeapIndexing(hasResourceDescriptorHeapIndexing);
flag.SetSamplerDescriptorHeapIndexing(hasSamplerDescriptorHeapIndexing);
flag.SetAtomicInt64OnHeapResource(hasAtomicInt64OnHeapResource);
flag.SetAdvancedTextureOps(hasAdvancedTextureOps);
flag.SetWriteableMSAATextures(setWriteableMSAATextures_1_7
? hasWriteableMSAATextures_1_7
: hasWriteableMSAATextures);
// Only bother setting the flag when there are UAVs.
flag.SetResMayNotAlias(canSetResMayNotAlias && hasUAVs &&
!M->GetResMayAlias());
flag.SetSampleCmpGradientOrBias(hasSampleCmpGradientOrBias);
flag.SetExtendedCommandInfo(hasExtendedCommandInfo);
flag.SetUsesDerivatives(hasDerivatives);
flag.SetRequiresGroup(requiresGroup);
return flag;
}
void ShaderFlags::CombineShaderFlags(const ShaderFlags &other) {
SetShaderFlagsRaw(GetShaderFlagsRaw() | other.GetShaderFlagsRaw());
}
void ShaderFlags::ClearLocalFlags() {
SetUsesDerivatives(false);
SetRequiresGroup(false);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DXIL/DxilResource.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilResource.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilResource.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilResourceBase.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DerivedTypes.h"
using namespace llvm;
namespace hlsl {
//------------------------------------------------------------------------------
//
// Resource methods.
//
DxilResource::DxilResource()
: DxilResourceBase(DxilResourceBase::Class::Invalid), m_SampleCount(0),
m_ElementStride(0), m_SamplerFeedbackType((DXIL::SamplerFeedbackType)0),
m_bGloballyCoherent(false), m_bHasCounter(false), m_bROV(false),
m_bHasAtomic64Use(false) {}
CompType DxilResource::GetCompType() const { return m_CompType; }
void DxilResource::SetCompType(const CompType CT) {
// Translate packed types to u32
switch (CT.GetKind()) {
case CompType::Kind::PackedS8x32:
case CompType::Kind::PackedU8x32:
m_CompType = CompType::getU32();
break;
default:
m_CompType = CT;
break;
}
}
Type *DxilResource::GetRetType() const {
Type *Ty = GetHLSLType()->getPointerElementType();
// For resource array, use element type.
while (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
// Get the struct buffer type like this %class.StructuredBuffer = type {
// %struct.mat }.
StructType *ST = cast<StructType>(Ty);
// Get the struct type inside struct buffer.
return ST->getElementType(0);
}
unsigned DxilResource::GetSampleCount() const { return m_SampleCount; }
void DxilResource::SetSampleCount(unsigned SampleCount) {
m_SampleCount = SampleCount;
}
unsigned DxilResource::GetElementStride() const { return m_ElementStride; }
void DxilResource::SetElementStride(unsigned ElemStride) {
m_ElementStride = ElemStride;
}
unsigned DxilResource::GetBaseAlignLog2() const { return m_baseAlignLog2; }
void DxilResource::SetBaseAlignLog2(unsigned baseAlignLog2) {
m_baseAlignLog2 = baseAlignLog2;
}
DXIL::SamplerFeedbackType DxilResource::GetSamplerFeedbackType() const {
return m_SamplerFeedbackType;
}
void DxilResource::SetSamplerFeedbackType(DXIL::SamplerFeedbackType Value) {
m_SamplerFeedbackType = Value;
}
bool DxilResource::IsGloballyCoherent() const { return m_bGloballyCoherent; }
void DxilResource::SetGloballyCoherent(bool b) { m_bGloballyCoherent = b; }
bool DxilResource::HasCounter() const { return m_bHasCounter; }
void DxilResource::SetHasCounter(bool b) { m_bHasCounter = b; }
bool DxilResource::IsRO() const {
return GetClass() == DxilResourceBase::Class::SRV;
}
bool DxilResource::IsRW() const {
return GetClass() == DxilResourceBase::Class::UAV;
}
void DxilResource::SetRW(bool bRW) {
SetClass(bRW ? DxilResourceBase::Class::UAV : DxilResourceBase::Class::SRV);
}
bool DxilResource::IsROV() const { return m_bROV; }
void DxilResource::SetROV(bool bROV) { m_bROV = bROV; }
bool DxilResource::IsAnyTexture() const { return IsAnyTexture(GetKind()); }
bool DxilResource::IsAnyTexture(Kind ResourceKind) {
return DXIL::IsAnyTexture(ResourceKind);
}
bool DxilResource::IsAnyArrayTexture() const {
return IsAnyArrayTexture(GetKind());
}
bool DxilResource::IsAnyArrayTexture(Kind ResourceKind) {
return DXIL::IsAnyArrayTexture(ResourceKind);
}
bool DxilResource::IsAnyTextureCube() const {
return IsAnyTextureCube(GetKind());
}
bool DxilResource::IsAnyTextureCube(Kind ResourceKind) {
return DXIL::IsAnyTextureCube(ResourceKind);
}
bool DxilResource::IsArrayKind() const { return IsArrayKind(GetKind()); }
bool DxilResource::IsArrayKind(Kind ResourceKind) {
return DXIL::IsArrayKind(ResourceKind);
}
bool DxilResource::IsStructuredBuffer() const {
return GetKind() == Kind::StructuredBuffer;
}
bool DxilResource::IsTypedBuffer() const {
return GetKind() == Kind::TypedBuffer;
}
bool DxilResource::IsRawBuffer() const { return GetKind() == Kind::RawBuffer; }
bool DxilResource::IsTBuffer() const { return GetKind() == Kind::TBuffer; }
bool DxilResource::IsFeedbackTexture() const {
return IsFeedbackTexture(GetKind());
}
bool DxilResource::IsFeedbackTexture(Kind ResourceKind) {
return DXIL::IsFeedbackTexture(ResourceKind);
}
bool DxilResource::HasAtomic64Use() const { return m_bHasAtomic64Use; }
void DxilResource::SetHasAtomic64Use(bool b) { m_bHasAtomic64Use = b; }
unsigned DxilResource::GetNumCoords(Kind ResourceKind) {
const unsigned CoordSizeTab[] = {
0, // Invalid = 0,
1, // Texture1D,
2, // Texture2D,
2, // Texture2DMS,
3, // Texture3D,
3, // TextureCube,
2, // Texture1DArray,
3, // Texture2DArray,
3, // Texture2DMSArray,
4, // TextureCubeArray,
1, // TypedBuffer,
1, // RawBuffer,
2, // StructuredBuffer,
0, // CBuffer,
0, // Sampler,
1, // TBuffer,
0, // RaytracingAccelerationStructure,
2, // FeedbackTexture2D,
3, // FeedbackTexture2DArray,
};
static_assert(_countof(CoordSizeTab) == (unsigned)Kind::NumEntries,
"check helper array size");
DXASSERT(ResourceKind > Kind::Invalid && ResourceKind < Kind::NumEntries,
"otherwise the caller passed wrong resource type");
return CoordSizeTab[(unsigned)ResourceKind];
}
unsigned DxilResource::GetNumDimensions(Kind ResourceKind) {
const unsigned NumDimTab[] = {
0, // Invalid = 0,
1, // Texture1D,
2, // Texture2D,
2, // Texture2DMS,
3, // Texture3D,
2, // TextureCube,
1, // Texture1DArray,
2, // Texture2DArray,
2, // Texture2DMSArray,
3, // TextureCubeArray,
1, // TypedBuffer,
1, // RawBuffer,
2, // StructuredBuffer,
0, // CBuffer,
0, // Sampler,
1, // TBuffer,
0, // RaytracingAccelerationStructure,
2, // FeedbackTexture2D,
2, // FeedbackTexture2DArray,
};
static_assert(_countof(NumDimTab) == (unsigned)Kind::NumEntries,
"check helper array size");
DXASSERT(ResourceKind > Kind::Invalid && ResourceKind < Kind::NumEntries,
"otherwise the caller passed wrong resource type");
return NumDimTab[(unsigned)ResourceKind];
}
unsigned DxilResource::GetNumDimensionsForCalcLOD(Kind ResourceKind) {
const unsigned NumDimTab[] = {
0, // Invalid = 0,
1, // Texture1D,
2, // Texture2D,
2, // Texture2DMS,
3, // Texture3D,
3, // TextureCube,
1, // Texture1DArray,
2, // Texture2DArray,
2, // Texture2DMSArray,
3, // TextureCubeArray,
1, // TypedBuffer,
1, // RawBuffer,
2, // StructuredBuffer,
0, // CBuffer,
0, // Sampler,
1, // TBuffer,
0, // RaytracingAccelerationStructure,
2, // FeedbackTexture2D,
2, // FeedbackTexture2DArray,
};
static_assert(_countof(NumDimTab) == (unsigned)Kind::NumEntries,
"check helper array size");
DXASSERT(ResourceKind > Kind::Invalid && ResourceKind < Kind::NumEntries,
"otherwise the caller passed wrong resource type");
return NumDimTab[(unsigned)ResourceKind];
}
unsigned DxilResource::GetNumOffsets(Kind ResourceKind) {
const unsigned OffsetSizeTab[] = {
0, // Invalid = 0,
1, // Texture1D,
2, // Texture2D,
2, // Texture2DMS,
3, // Texture3D,
0, // TextureCube,
1, // Texture1DArray,
2, // Texture2DArray,
2, // Texture2DMSArray,
0, // TextureCubeArray,
0, // TypedBuffer,
0, // RawBuffer,
0, // StructuredBuffer,
0, // CBuffer,
0, // Sampler,
1, // TBuffer,
0, // RaytracingAccelerationStructure,
2, // FeedbackTexture2D,
2, // FeedbackTexture2DArray,
};
static_assert(_countof(OffsetSizeTab) == (unsigned)Kind::NumEntries,
"check helper array size");
DXASSERT(ResourceKind > Kind::Invalid && ResourceKind < Kind::NumEntries,
"otherwise the caller passed wrong resource type");
return OffsetSizeTab[(unsigned)ResourceKind];
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/PassPrinters/CMakeLists.txt | add_llvm_library(LLVMPassPrinters
PassPrinters.cpp
ADDITIONAL_HEADER_DIRS
)
add_dependencies(LLVMPassPrinters intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/PassPrinters/LLVMBuild.txt | ;===- ./lib/Passes/LLVMBuild.txt -------------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = PassPrinters
parent = Libraries
required_libraries = Passes Analysis Core IPA IPO InstCombine Scalar Support TransformUtils Vectorize
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/PassPrinters/PassPrinters.cpp | //===- PassPrinters.cpp - Utilities to print analysis info for passes -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Utilities to print analysis info for various kinds of passes.
///
//===----------------------------------------------------------------------===//
#include "llvm/PassPrinters/PassPrinters.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include <string>
// //
///////////////////////////////////////////////////////////////////////////////
using namespace llvm;
namespace {
struct FunctionPassPrinter : public FunctionPass {
const PassInfo *PassToPrint;
raw_ostream &Out;
static char ID;
std::string PassName;
bool QuietPass;
FunctionPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: FunctionPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "FunctionPass Printer: " + PassToPrintName;
}
bool runOnFunction(Function &F) override {
if (!QuietPass)
Out << "Printing analysis '" << PassToPrint->getPassName()
<< "' for function '" << F.getName() << "':\n";
// Get and print pass...
getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, F.getParent());
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char FunctionPassPrinter::ID = 0;
struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
static char ID;
const PassInfo *PassToPrint;
raw_ostream &Out;
std::string PassName;
bool QuietPass;
CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: CallGraphSCCPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
}
bool runOnSCC(CallGraphSCC &SCC) override {
if (!QuietPass)
Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
// Get and print pass...
for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
Function *F = (*I)->getFunction();
if (F)
getAnalysisID<Pass>(PassToPrint->getTypeInfo())
.print(Out, F->getParent());
}
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char CallGraphSCCPassPrinter::ID = 0;
struct ModulePassPrinter : public ModulePass {
static char ID;
const PassInfo *PassToPrint;
raw_ostream &Out;
std::string PassName;
bool QuietPass;
ModulePassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: ModulePass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "ModulePass Printer: " + PassToPrintName;
}
bool runOnModule(Module &M) override {
if (!QuietPass)
Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
// Get and print pass...
getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char ModulePassPrinter::ID = 0;
struct LoopPassPrinter : public LoopPass {
static char ID;
const PassInfo *PassToPrint;
raw_ostream &Out;
std::string PassName;
bool QuietPass;
LoopPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: LoopPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "LoopPass Printer: " + PassToPrintName;
}
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
if (!QuietPass)
Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
// Get and print pass...
getAnalysisID<Pass>(PassToPrint->getTypeInfo())
.print(Out, L->getHeader()->getParent()->getParent());
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char LoopPassPrinter::ID = 0;
struct RegionPassPrinter : public RegionPass {
static char ID;
const PassInfo *PassToPrint;
raw_ostream &Out;
std::string PassName;
bool QuietPass;
RegionPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: RegionPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "RegionPass Printer: " + PassToPrintName;
}
bool runOnRegion(Region *R, RGPassManager &RGM) override {
if (!QuietPass) {
Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
<< "region: '" << R->getNameStr() << "' in function '"
<< R->getEntry()->getParent()->getName() << "':\n";
}
// Get and print pass...
getAnalysisID<Pass>(PassToPrint->getTypeInfo())
.print(Out, R->getEntry()->getParent()->getParent());
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char RegionPassPrinter::ID = 0;
struct BasicBlockPassPrinter : public BasicBlockPass {
const PassInfo *PassToPrint;
raw_ostream &Out;
static char ID;
std::string PassName;
bool QuietPass;
BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
: BasicBlockPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
std::string PassToPrintName = PassToPrint->getPassName();
PassName = "BasicBlockPass Printer: " + PassToPrintName;
}
bool runOnBasicBlock(BasicBlock &BB) override {
if (!QuietPass)
Out << "Printing Analysis info for BasicBlock '" << BB.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n";
// Get and print pass...
getAnalysisID<Pass>(PassToPrint->getTypeInfo())
.print(Out, BB.getParent()->getParent());
return false;
}
StringRef getPassName() const override { return PassName.c_str(); }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(PassToPrint->getTypeInfo());
AU.setPreservesAll();
}
};
char BasicBlockPassPrinter::ID = 0;
} // namespace
FunctionPass *llvm::createFunctionPassPrinter(const PassInfo *PI,
raw_ostream &OS, bool Quiet) {
return new FunctionPassPrinter(PI, OS, Quiet);
}
CallGraphSCCPass *llvm::createCallGraphPassPrinter(const PassInfo *PI,
raw_ostream &OS,
bool Quiet) {
return new CallGraphSCCPassPrinter(PI, OS, Quiet);
}
ModulePass *llvm::createModulePassPrinter(const PassInfo *PI, raw_ostream &OS,
bool Quiet) {
return new ModulePassPrinter(PI, OS, Quiet);
}
LoopPass *llvm::createLoopPassPrinter(const PassInfo *PI, raw_ostream &OS,
bool Quiet) {
return new LoopPassPrinter(PI, OS, Quiet);
}
RegionPass *llvm::createRegionPassPrinter(const PassInfo *PI, raw_ostream &OS,
bool Quiet) {
return new RegionPassPrinter(PI, OS, Quiet);
}
BasicBlockPass *llvm::createBasicBlockPassPrinter(const PassInfo *PI,
raw_ostream &OS, bool Quiet) {
return new BasicBlockPassPrinter(PI, OS, Quiet);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/TableGenBackend.cpp | //===- TableGenBackend.cpp - Utilities for TableGen Backends ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides useful services for TableGen backends...
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/TableGenBackend.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
const size_t MAX_LINE_LEN = 80U;
static void printLine(raw_ostream &OS, const Twine &Prefix, char Fill,
StringRef Suffix) {
size_t Pos = (size_t)OS.tell();
assert((Prefix.str().size() + Suffix.size() <= MAX_LINE_LEN) &&
"header line exceeds max limit");
OS << Prefix;
for (size_t i = (size_t)OS.tell() - Pos, e = MAX_LINE_LEN - Suffix.size();
i < e; ++i)
OS << Fill;
OS << Suffix << '\n';
}
void llvm::emitSourceFileHeader(StringRef Desc, raw_ostream &OS) {
printLine(OS, "/*===- TableGen'erated file ", '-', "*- C++ -*-===*\\");
StringRef Prefix("|* ");
StringRef Suffix(" *|");
printLine(OS, Prefix, ' ', Suffix);
size_t PSLen = Prefix.size() + Suffix.size();
assert(PSLen < MAX_LINE_LEN);
size_t Pos = 0U;
do {
size_t Length = std::min(Desc.size() - Pos, MAX_LINE_LEN - PSLen);
printLine(OS, Prefix + Desc.substr(Pos, Length), ' ', Suffix);
Pos += Length;
} while (Pos < Desc.size());
printLine(OS, Prefix, ' ', Suffix);
printLine(OS, Prefix + "Automatically generated file, do not edit!", ' ',
Suffix);
printLine(OS, Prefix, ' ', Suffix);
printLine(OS, "\\*===", '-', "===*/");
OS << '\n';
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/TGParser.cpp | //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implement the Parser for TableGen.
//
//===----------------------------------------------------------------------===//
#include "TGParser.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/TableGen/Record.h"
#include <algorithm>
#include <sstream>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Support Code for the Semantic Actions.
//===----------------------------------------------------------------------===//
namespace llvm {
struct SubClassReference {
SMRange RefRange;
Record *Rec;
std::vector<Init*> TemplateArgs;
SubClassReference() : Rec(nullptr) {}
bool isInvalid() const { return Rec == nullptr; }
};
struct SubMultiClassReference {
SMRange RefRange;
MultiClass *MC;
std::vector<Init*> TemplateArgs;
SubMultiClassReference() : MC(nullptr) {}
bool isInvalid() const { return MC == nullptr; }
void dump() const;
};
void SubMultiClassReference::dump() const {
errs() << "Multiclass:\n";
MC->dump();
errs() << "Template args:\n";
for (Init *TA : TemplateArgs)
TA->dump();
}
} // end namespace llvm
bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
if (!CurRec)
CurRec = &CurMultiClass->Rec;
if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
// The value already exists in the class, treat this as a set.
if (ERV->setValue(RV.getValue()))
return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
RV.getType()->getAsString() + "' is incompatible with " +
"previous definition of type '" +
ERV->getType()->getAsString() + "'");
} else {
CurRec->addValue(RV);
}
return false;
}
/// SetValue -
/// Return true on error, false on success.
bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
const std::vector<unsigned> &BitList, Init *V) {
if (!V) return false;
if (!CurRec) CurRec = &CurMultiClass->Rec;
RecordVal *RV = CurRec->getValue(ValName);
if (!RV)
return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
"' unknown!");
// Do not allow assignments like 'X = X'. This will just cause infinite loops
// in the resolution machinery.
if (BitList.empty())
if (VarInit *VI = dyn_cast<VarInit>(V))
if (VI->getNameInit() == ValName)
return false;
// If we are assigning to a subset of the bits in the value... then we must be
// assigning to a field of BitsRecTy, which must have a BitsInit
// initializer.
//
if (!BitList.empty()) {
BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
if (!CurVal)
return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
"' is not a bits type");
// Convert the incoming value to a bits type of the appropriate size...
Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
if (!BI)
return Error(Loc, "Initializer is not compatible with bit range");
// We should have a BitsInit type now.
BitsInit *BInit = cast<BitsInit>(BI);
SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
// Loop over bits, assigning values as appropriate.
for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
unsigned Bit = BitList[i];
if (NewBits[Bit])
return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
ValName->getAsUnquotedString() + "' more than once");
NewBits[Bit] = BInit->getBit(i);
}
for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
if (!NewBits[i])
NewBits[i] = CurVal->getBit(i);
V = BitsInit::get(NewBits);
}
if (RV->setValue(V)) {
std::string InitType = "";
if (BitsInit *BI = dyn_cast<BitsInit>(V))
InitType = (Twine("' of type bit initializer with length ") +
Twine(BI->getNumBits())).str();
return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
"' of type '" + RV->getType()->getAsString() +
"' is incompatible with initializer '" + V->getAsString() +
InitType + "'");
}
return false;
}
/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
/// args as SubClass's template arguments.
bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
Record *SC = SubClass.Rec;
// Add all of the values in the subclass into the current class.
for (const RecordVal &Val : SC->getValues())
if (AddValue(CurRec, SubClass.RefRange.Start, Val))
return true;
const std::vector<Init *> &TArgs = SC->getTemplateArgs();
// Ensure that an appropriate number of template arguments are specified.
if (TArgs.size() < SubClass.TemplateArgs.size())
return Error(SubClass.RefRange.Start,
"More template args specified than expected");
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
if (i < SubClass.TemplateArgs.size()) {
// If a value is specified for this template arg, set it now.
if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
std::vector<unsigned>(), SubClass.TemplateArgs[i]))
return true;
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
return Error(SubClass.RefRange.Start,
"Value not specified for template argument #" +
Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
") of subclass '" + SC->getNameInitAsString() + "'!");
}
}
// Since everything went well, we can now set the "superclass" list for the
// current record.
ArrayRef<Record *> SCs = SC->getSuperClasses();
ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
if (CurRec->isSubClassOf(SCs[i]))
return Error(SubClass.RefRange.Start,
"Already subclass of '" + SCs[i]->getName() + "'!\n");
CurRec->addSuperClass(SCs[i], SCRanges[i]);
}
if (CurRec->isSubClassOf(SC))
return Error(SubClass.RefRange.Start,
"Already subclass of '" + SC->getName() + "'!\n");
CurRec->addSuperClass(SC, SubClass.RefRange);
return false;
}
/// AddSubMultiClass - Add SubMultiClass as a subclass to
/// CurMC, resolving its template args as SubMultiClass's
/// template arguments.
bool TGParser::AddSubMultiClass(MultiClass *CurMC,
SubMultiClassReference &SubMultiClass) {
MultiClass *SMC = SubMultiClass.MC;
Record *CurRec = &CurMC->Rec;
// Add all of the values in the subclass into the current class.
for (const auto &SMCVal : SMC->Rec.getValues())
if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
return true;
unsigned newDefStart = CurMC->DefPrototypes.size();
// Add all of the defs in the subclass into the current multiclass.
for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
// Clone the def and add it to the current multiclass
auto NewDef = make_unique<Record>(*R);
// Add all of the values in the superclass into the current def.
for (const auto &MCVal : CurRec->getValues())
if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
return true;
CurMC->DefPrototypes.push_back(std::move(NewDef));
}
const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
// Ensure that an appropriate number of template arguments are
// specified.
if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
return Error(SubMultiClass.RefRange.Start,
"More template args specified than expected");
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
if (i < SubMultiClass.TemplateArgs.size()) {
// If a value is specified for this template arg, set it in the
// superclass now.
if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
std::vector<unsigned>(),
SubMultiClass.TemplateArgs[i]))
return true;
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
// Now remove it.
CurRec->removeValue(SMCTArgs[i]);
// If a value is specified for this template arg, set it in the
// new defs now.
for (const auto &Def :
makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
std::vector<unsigned>(),
SubMultiClass.TemplateArgs[i]))
return true;
// Resolve it next.
Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
// Now remove it
Def->removeValue(SMCTArgs[i]);
}
} else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
return Error(SubMultiClass.RefRange.Start,
"Value not specified for template argument #" +
Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
}
}
return false;
}
/// ProcessForeachDefs - Given a record, apply all of the variable
/// values in all surrounding foreach loops, creating new records for
/// each combination of values.
bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
if (Loops.empty())
return false;
// We want to instantiate a new copy of CurRec for each combination
// of nested loop iterator values. We don't want top instantiate
// any copies until we have values for each loop iterator.
IterSet IterVals;
return ProcessForeachDefs(CurRec, Loc, IterVals);
}
/// ProcessForeachDefs - Given a record, a loop and a loop iterator,
/// apply each of the variable values in this loop and then process
/// subloops.
bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
// Recursively build a tuple of iterator values.
if (IterVals.size() != Loops.size()) {
assert(IterVals.size() < Loops.size());
ForeachLoop &CurLoop = Loops[IterVals.size()];
ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
if (!List) {
Error(Loc, "Loop list is not a list");
return true;
}
// Process each value.
for (unsigned i = 0; i < List->size(); ++i) {
Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
if (ProcessForeachDefs(CurRec, Loc, IterVals))
return true;
IterVals.pop_back();
}
return false;
}
// This is the bottom of the recursion. We have all of the iterator values
// for this point in the iteration space. Instantiate a new record to
// reflect this combination of values.
auto IterRec = make_unique<Record>(*CurRec);
// Set the iterator values now.
for (IterRecord &IR : IterVals) {
VarInit *IterVar = IR.IterVar;
TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue);
if (!IVal)
return Error(Loc, "foreach iterator value is untyped");
IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
if (SetValue(IterRec.get(), Loc, IterVar->getName(),
std::vector<unsigned>(), IVal))
return Error(Loc, "when instantiating this def");
// Resolve it next.
IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
// Remove it.
IterRec->removeValue(IterVar->getName());
}
if (Records.getDef(IterRec->getNameInitAsString())) {
// If this record is anonymous, it's no problem, just generate a new name
if (!IterRec->isAnonymous())
return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
IterRec->setName(GetNewAnonymousName());
}
Record *IterRecSave = IterRec.get(); // Keep a copy before release.
Records.addDef(std::move(IterRec));
IterRecSave->resolveReferences();
return false;
}
//===----------------------------------------------------------------------===//
// Parser Code
//===----------------------------------------------------------------------===//
/// isObjectStart - Return true if this is a valid first token for an Object.
static bool isObjectStart(tgtok::TokKind K) {
return K == tgtok::Class || K == tgtok::Def ||
K == tgtok::Defm || K == tgtok::Let ||
K == tgtok::MultiClass || K == tgtok::Foreach;
}
/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
/// an identifier.
std::string TGParser::GetNewAnonymousName() {
return "anonymous_" + utostr(AnonCounter++);
}
/// ParseObjectName - If an object name is specified, return it. Otherwise,
/// return 0.
/// ObjectName ::= Value [ '#' Value ]*
/// ObjectName ::= /*empty*/
///
Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
switch (Lex.getCode()) {
case tgtok::colon:
case tgtok::semi:
case tgtok::l_brace:
// These are all of the tokens that can begin an object body.
// Some of these can also begin values but we disallow those cases
// because they are unlikely to be useful.
return nullptr;
default:
break;
}
Record *CurRec = nullptr;
if (CurMultiClass)
CurRec = &CurMultiClass->Rec;
RecTy *Type = nullptr;
if (CurRec) {
const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
if (!CurRecName) {
TokError("Record name is not typed!");
return nullptr;
}
Type = CurRecName->getType();
}
return ParseValue(CurRec, Type, ParseNameMode);
}
/// ParseClassID - Parse and resolve a reference to a class name. This returns
/// null on error.
///
/// ClassID ::= ID
///
Record *TGParser::ParseClassID() {
if (Lex.getCode() != tgtok::Id) {
TokError("expected name for ClassID");
return nullptr;
}
Record *Result = Records.getClass(Lex.getCurStrVal());
if (!Result)
TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
Lex.Lex();
return Result;
}
/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
/// This returns null on error.
///
/// MultiClassID ::= ID
///
MultiClass *TGParser::ParseMultiClassID() {
if (Lex.getCode() != tgtok::Id) {
TokError("expected name for MultiClassID");
return nullptr;
}
MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
if (!Result)
TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
Lex.Lex();
return Result;
}
/// ParseSubClassReference - Parse a reference to a subclass or to a templated
/// subclass. This returns a SubClassRefTy with a null Record* on error.
///
/// SubClassRef ::= ClassID
/// SubClassRef ::= ClassID '<' ValueList '>'
///
SubClassReference TGParser::
ParseSubClassReference(Record *CurRec, bool isDefm) {
SubClassReference Result;
Result.RefRange.Start = Lex.getLoc();
if (isDefm) {
if (MultiClass *MC = ParseMultiClassID())
Result.Rec = &MC->Rec;
} else {
Result.Rec = ParseClassID();
}
if (!Result.Rec) return Result;
// If there is no template arg list, we're done.
if (Lex.getCode() != tgtok::less) {
Result.RefRange.End = Lex.getLoc();
return Result;
}
Lex.Lex(); // Eat the '<'
if (Lex.getCode() == tgtok::greater) {
TokError("subclass reference requires a non-empty list of template values");
Result.Rec = nullptr;
return Result;
}
Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
if (Result.TemplateArgs.empty()) {
Result.Rec = nullptr; // Error parsing value list.
return Result;
}
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' in template value list");
Result.Rec = nullptr;
return Result;
}
Lex.Lex();
Result.RefRange.End = Lex.getLoc();
return Result;
}
/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
/// templated submulticlass. This returns a SubMultiClassRefTy with a null
/// Record* on error.
///
/// SubMultiClassRef ::= MultiClassID
/// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
///
SubMultiClassReference TGParser::
ParseSubMultiClassReference(MultiClass *CurMC) {
SubMultiClassReference Result;
Result.RefRange.Start = Lex.getLoc();
Result.MC = ParseMultiClassID();
if (!Result.MC) return Result;
// If there is no template arg list, we're done.
if (Lex.getCode() != tgtok::less) {
Result.RefRange.End = Lex.getLoc();
return Result;
}
Lex.Lex(); // Eat the '<'
if (Lex.getCode() == tgtok::greater) {
TokError("subclass reference requires a non-empty list of template values");
Result.MC = nullptr;
return Result;
}
Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
if (Result.TemplateArgs.empty()) {
Result.MC = nullptr; // Error parsing value list.
return Result;
}
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' in template value list");
Result.MC = nullptr;
return Result;
}
Lex.Lex();
Result.RefRange.End = Lex.getLoc();
return Result;
}
/// ParseRangePiece - Parse a bit/value range.
/// RangePiece ::= INTVAL
/// RangePiece ::= INTVAL '-' INTVAL
/// RangePiece ::= INTVAL INTVAL
bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
if (Lex.getCode() != tgtok::IntVal) {
TokError("expected integer or bitrange");
return true;
}
int64_t Start = Lex.getCurIntVal();
int64_t End;
if (Start < 0)
return TokError("invalid range, cannot be negative");
switch (Lex.Lex()) { // eat first character.
default:
Ranges.push_back(Start);
return false;
case tgtok::minus:
if (Lex.Lex() != tgtok::IntVal) {
TokError("expected integer value as end of range");
return true;
}
End = Lex.getCurIntVal();
break;
case tgtok::IntVal:
End = -Lex.getCurIntVal();
break;
}
if (End < 0)
return TokError("invalid range, cannot be negative");
Lex.Lex();
// Add to the range.
if (Start < End)
for (; Start <= End; ++Start)
Ranges.push_back(Start);
else
for (; Start >= End; --Start)
Ranges.push_back(Start);
return false;
}
/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
///
/// RangeList ::= RangePiece (',' RangePiece)*
///
std::vector<unsigned> TGParser::ParseRangeList() {
std::vector<unsigned> Result;
// Parse the first piece.
if (ParseRangePiece(Result))
return std::vector<unsigned>();
while (Lex.getCode() == tgtok::comma) {
Lex.Lex(); // Eat the comma.
// Parse the next range piece.
if (ParseRangePiece(Result))
return std::vector<unsigned>();
}
return Result;
}
/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
/// OptionalRangeList ::= '<' RangeList '>'
/// OptionalRangeList ::= /*empty*/
bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
if (Lex.getCode() != tgtok::less)
return false;
SMLoc StartLoc = Lex.getLoc();
Lex.Lex(); // eat the '<'
// Parse the range list.
Ranges = ParseRangeList();
if (Ranges.empty()) return true;
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' at end of range list");
return Error(StartLoc, "to match this '<'");
}
Lex.Lex(); // eat the '>'.
return false;
}
/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
/// OptionalBitList ::= '{' RangeList '}'
/// OptionalBitList ::= /*empty*/
bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
if (Lex.getCode() != tgtok::l_brace)
return false;
SMLoc StartLoc = Lex.getLoc();
Lex.Lex(); // eat the '{'
// Parse the range list.
Ranges = ParseRangeList();
if (Ranges.empty()) return true;
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of bit list");
return Error(StartLoc, "to match this '{'");
}
Lex.Lex(); // eat the '}'.
return false;
}
/// ParseType - Parse and return a tblgen type. This returns null on error.
///
/// Type ::= STRING // string type
/// Type ::= CODE // code type
/// Type ::= BIT // bit type
/// Type ::= BITS '<' INTVAL '>' // bits<x> type
/// Type ::= INT // int type
/// Type ::= LIST '<' Type '>' // list<x> type
/// Type ::= DAG // dag type
/// Type ::= ClassID // Record Type
///
RecTy *TGParser::ParseType() {
switch (Lex.getCode()) {
default: TokError("Unknown token when expecting a type"); return nullptr;
case tgtok::String: Lex.Lex(); return StringRecTy::get();
case tgtok::Code: Lex.Lex(); return StringRecTy::get();
case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
case tgtok::Int: Lex.Lex(); return IntRecTy::get();
case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
case tgtok::Id:
if (Record *R = ParseClassID()) return RecordRecTy::get(R);
return nullptr;
case tgtok::Bits: {
if (Lex.Lex() != tgtok::less) { // Eat 'bits'
TokError("expected '<' after bits type");
return nullptr;
}
if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
TokError("expected integer in bits<n> type");
return nullptr;
}
uint64_t Val = Lex.getCurIntVal();
if (Lex.Lex() != tgtok::greater) { // Eat count.
TokError("expected '>' at end of bits<n> type");
return nullptr;
}
Lex.Lex(); // Eat '>'
return BitsRecTy::get(Val);
}
case tgtok::List: {
if (Lex.Lex() != tgtok::less) { // Eat 'bits'
TokError("expected '<' after list type");
return nullptr;
}
Lex.Lex(); // Eat '<'
RecTy *SubType = ParseType();
if (!SubType) return nullptr;
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' at end of list<ty> type");
return nullptr;
}
Lex.Lex(); // Eat '>'
return ListRecTy::get(SubType);
}
}
}
/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
/// has already been read.
Init *TGParser::ParseIDValue(Record *CurRec,
const std::string &Name, SMLoc NameLoc,
IDParseMode Mode) {
if (CurRec) {
if (const RecordVal *RV = CurRec->getValue(Name))
return VarInit::get(Name, RV->getType());
Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
if (CurMultiClass)
TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
"::");
if (CurRec->isTemplateArg(TemplateArgName)) {
const RecordVal *RV = CurRec->getValue(TemplateArgName);
assert(RV && "Template arg doesn't exist??");
return VarInit::get(TemplateArgName, RV->getType());
}
}
if (CurMultiClass) {
Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
"::");
if (CurMultiClass->Rec.isTemplateArg(MCName)) {
const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
assert(RV && "Template arg doesn't exist??");
return VarInit::get(MCName, RV->getType());
}
}
// If this is in a foreach loop, make sure it's not a loop iterator
for (const auto &L : Loops) {
VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
if (IterVar && IterVar->getName() == Name)
return IterVar;
}
if (Mode == ParseNameMode)
return StringInit::get(Name);
if (Record *D = Records.getDef(Name))
return DefInit::get(D);
if (Mode == ParseValueMode) {
Error(NameLoc, "Variable not defined: '" + Name + "'");
return nullptr;
}
return StringInit::get(Name);
}
/// ParseOperation - Parse an operator. This returns null on error.
///
/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
///
Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
switch (Lex.getCode()) {
default:
TokError("unknown operation");
return nullptr;
case tgtok::XHead:
case tgtok::XTail:
case tgtok::XEmpty:
case tgtok::XCast: { // Value ::= !unop '(' Value ')'
UnOpInit::UnaryOp Code;
RecTy *Type = nullptr;
switch (Lex.getCode()) {
default: llvm_unreachable("Unhandled code!");
case tgtok::XCast:
Lex.Lex(); // eat the operation
Code = UnOpInit::CAST;
Type = ParseOperatorType();
if (!Type) {
TokError("did not get type for unary operator");
return nullptr;
}
break;
case tgtok::XHead:
Lex.Lex(); // eat the operation
Code = UnOpInit::HEAD;
break;
case tgtok::XTail:
Lex.Lex(); // eat the operation
Code = UnOpInit::TAIL;
break;
case tgtok::XEmpty:
Lex.Lex(); // eat the operation
Code = UnOpInit::EMPTY;
Type = IntRecTy::get();
break;
}
if (Lex.getCode() != tgtok::l_paren) {
TokError("expected '(' after unary operator");
return nullptr;
}
Lex.Lex(); // eat the '('
Init *LHS = ParseValue(CurRec);
if (!LHS) return nullptr;
if (Code == UnOpInit::HEAD ||
Code == UnOpInit::TAIL ||
Code == UnOpInit::EMPTY) {
ListInit *LHSl = dyn_cast<ListInit>(LHS);
StringInit *LHSs = dyn_cast<StringInit>(LHS);
TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
if (!LHSl && !LHSs && !LHSt) {
TokError("expected list or string type argument in unary operator");
return nullptr;
}
if (LHSt) {
ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
if (!LType && !SType) {
TokError("expected list or string type argument in unary operator");
return nullptr;
}
}
if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
if (!LHSl && !LHSt) {
TokError("expected list type argument in unary operator");
return nullptr;
}
if (LHSl && LHSl->empty()) {
TokError("empty list argument in unary operator");
return nullptr;
}
if (LHSl) {
Init *Item = LHSl->getElement(0);
TypedInit *Itemt = dyn_cast<TypedInit>(Item);
if (!Itemt) {
TokError("untyped list element in unary operator");
return nullptr;
}
Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
: ListRecTy::get(Itemt->getType());
} else {
assert(LHSt && "expected list type argument in unary operator");
ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
if (!LType) {
TokError("expected list type argument in unary operator");
return nullptr;
}
Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
}
}
}
if (Lex.getCode() != tgtok::r_paren) {
TokError("expected ')' in unary operator");
return nullptr;
}
Lex.Lex(); // eat the ')'
return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
}
case tgtok::XConcat:
case tgtok::XADD:
case tgtok::XAND:
case tgtok::XSRA:
case tgtok::XSRL:
case tgtok::XSHL:
case tgtok::XEq:
case tgtok::XListConcat:
case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
tgtok::TokKind OpTok = Lex.getCode();
SMLoc OpLoc = Lex.getLoc();
Lex.Lex(); // eat the operation
BinOpInit::BinaryOp Code;
RecTy *Type = nullptr;
switch (OpTok) {
default: llvm_unreachable("Unhandled code!");
case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
case tgtok::XListConcat:
Code = BinOpInit::LISTCONCAT;
// We don't know the list type until we parse the first argument
break;
case tgtok::XStrConcat:
Code = BinOpInit::STRCONCAT;
Type = StringRecTy::get();
break;
}
if (Lex.getCode() != tgtok::l_paren) {
TokError("expected '(' after binary operator");
return nullptr;
}
Lex.Lex(); // eat the '('
SmallVector<Init*, 2> InitList;
InitList.push_back(ParseValue(CurRec));
if (!InitList.back()) return nullptr;
while (Lex.getCode() == tgtok::comma) {
Lex.Lex(); // eat the ','
InitList.push_back(ParseValue(CurRec));
if (!InitList.back()) return nullptr;
}
if (Lex.getCode() != tgtok::r_paren) {
TokError("expected ')' in operator");
return nullptr;
}
Lex.Lex(); // eat the ')'
// If we are doing !listconcat, we should know the type by now
if (OpTok == tgtok::XListConcat) {
if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
Type = Arg0->getType();
else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
Type = Arg0->getType();
else {
InitList[0]->dump();
Error(OpLoc, "expected a list");
return nullptr;
}
}
// We allow multiple operands to associative operators like !strconcat as
// shorthand for nesting them.
if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
while (InitList.size() > 2) {
Init *RHS = InitList.pop_back_val();
RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
->Fold(CurRec, CurMultiClass);
InitList.back() = RHS;
}
}
if (InitList.size() == 2)
return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
->Fold(CurRec, CurMultiClass);
Error(OpLoc, "expected two operands to operator");
return nullptr;
}
case tgtok::XIf:
case tgtok::XForEach:
case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
TernOpInit::TernaryOp Code;
RecTy *Type = nullptr;
tgtok::TokKind LexCode = Lex.getCode();
Lex.Lex(); // eat the operation
switch (LexCode) {
default: llvm_unreachable("Unhandled code!");
case tgtok::XIf:
Code = TernOpInit::IF;
break;
case tgtok::XForEach:
Code = TernOpInit::FOREACH;
break;
case tgtok::XSubst:
Code = TernOpInit::SUBST;
break;
}
if (Lex.getCode() != tgtok::l_paren) {
TokError("expected '(' after ternary operator");
return nullptr;
}
Lex.Lex(); // eat the '('
Init *LHS = ParseValue(CurRec);
if (!LHS) return nullptr;
if (Lex.getCode() != tgtok::comma) {
TokError("expected ',' in ternary operator");
return nullptr;
}
Lex.Lex(); // eat the ','
Init *MHS = ParseValue(CurRec, ItemType);
if (!MHS)
return nullptr;
if (Lex.getCode() != tgtok::comma) {
TokError("expected ',' in ternary operator");
return nullptr;
}
Lex.Lex(); // eat the ','
Init *RHS = ParseValue(CurRec, ItemType);
if (!RHS)
return nullptr;
if (Lex.getCode() != tgtok::r_paren) {
TokError("expected ')' in binary operator");
return nullptr;
}
Lex.Lex(); // eat the ')'
switch (LexCode) {
default: llvm_unreachable("Unhandled code!");
case tgtok::XIf: {
RecTy *MHSTy = nullptr;
RecTy *RHSTy = nullptr;
if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
MHSTy = MHSt->getType();
if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
MHSTy = BitsRecTy::get(MHSbits->getNumBits());
if (isa<BitInit>(MHS))
MHSTy = BitRecTy::get();
if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
RHSTy = RHSt->getType();
if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
RHSTy = BitsRecTy::get(RHSbits->getNumBits());
if (isa<BitInit>(RHS))
RHSTy = BitRecTy::get();
// For UnsetInit, it's typed from the other hand.
if (isa<UnsetInit>(MHS))
MHSTy = RHSTy;
if (isa<UnsetInit>(RHS))
RHSTy = MHSTy;
if (!MHSTy || !RHSTy) {
TokError("could not get type for !if");
return nullptr;
}
if (MHSTy->typeIsConvertibleTo(RHSTy)) {
Type = RHSTy;
} else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
Type = MHSTy;
} else {
TokError("inconsistent types for !if");
return nullptr;
}
break;
}
case tgtok::XForEach: {
TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
if (!MHSt) {
TokError("could not get type for !foreach");
return nullptr;
}
Type = MHSt->getType();
break;
}
case tgtok::XSubst: {
TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
if (!RHSt) {
TokError("could not get type for !subst");
return nullptr;
}
Type = RHSt->getType();
break;
}
}
return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
CurMultiClass);
}
}
}
/// ParseOperatorType - Parse a type for an operator. This returns
/// null on error.
///
/// OperatorType ::= '<' Type '>'
///
RecTy *TGParser::ParseOperatorType() {
RecTy *Type = nullptr;
if (Lex.getCode() != tgtok::less) {
TokError("expected type name for operator");
return nullptr;
}
Lex.Lex(); // eat the <
Type = ParseType();
if (!Type) {
TokError("expected type name for operator");
return nullptr;
}
if (Lex.getCode() != tgtok::greater) {
TokError("expected type name for operator");
return nullptr;
}
Lex.Lex(); // eat the >
return Type;
}
/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
///
/// SimpleValue ::= IDValue
/// SimpleValue ::= INTVAL
/// SimpleValue ::= STRVAL+
/// SimpleValue ::= CODEFRAGMENT
/// SimpleValue ::= '?'
/// SimpleValue ::= '{' ValueList '}'
/// SimpleValue ::= ID '<' ValueListNE '>'
/// SimpleValue ::= '[' ValueList ']'
/// SimpleValue ::= '(' IDValue DagArgList ')'
/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
/// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
/// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
///
Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
IDParseMode Mode) {
Init *R = nullptr;
switch (Lex.getCode()) {
default: TokError("Unknown token when parsing a value"); break;
case tgtok::paste:
// This is a leading paste operation. This is deprecated but
// still exists in some .td files. Ignore it.
Lex.Lex(); // Skip '#'.
return ParseSimpleValue(CurRec, ItemType, Mode);
case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
case tgtok::BinaryIntVal: {
auto BinaryVal = Lex.getCurBinaryIntVal();
SmallVector<Init*, 16> Bits(BinaryVal.second);
for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
R = BitsInit::get(Bits);
Lex.Lex();
break;
}
case tgtok::StrVal: {
std::string Val = Lex.getCurStrVal();
Lex.Lex();
// Handle multiple consecutive concatenated strings.
while (Lex.getCode() == tgtok::StrVal) {
Val += Lex.getCurStrVal();
Lex.Lex();
}
R = StringInit::get(Val);
break;
}
case tgtok::CodeFragment:
R = StringInit::get(Lex.getCurStrVal());
Lex.Lex();
break;
case tgtok::question:
R = UnsetInit::get();
Lex.Lex();
break;
case tgtok::Id: {
SMLoc NameLoc = Lex.getLoc();
std::string Name = Lex.getCurStrVal();
if (Lex.Lex() != tgtok::less) // consume the Id.
return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
// Value ::= ID '<' ValueListNE '>'
if (Lex.Lex() == tgtok::greater) {
TokError("expected non-empty value list");
return nullptr;
}
// This is a CLASS<initvalslist> expression. This is supposed to synthesize
// a new anonymous definition, deriving from CLASS<initvalslist> with no
// body.
Record *Class = Records.getClass(Name);
if (!Class) {
Error(NameLoc, "Expected a class name, got '" + Name + "'");
return nullptr;
}
std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
if (ValueList.empty()) return nullptr;
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' at end of value list");
return nullptr;
}
Lex.Lex(); // eat the '>'
SMLoc EndLoc = Lex.getLoc();
// Create the new record, set it as CurRec temporarily.
auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
Records, /*IsAnonymous=*/true);
Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
SubClassReference SCRef;
SCRef.RefRange = SMRange(NameLoc, EndLoc);
SCRef.Rec = Class;
SCRef.TemplateArgs = ValueList;
// Add info about the subclass to NewRec.
if (AddSubClass(NewRec, SCRef))
return nullptr;
if (!CurMultiClass) {
NewRec->resolveReferences();
Records.addDef(std::move(NewRecOwner));
} else {
// This needs to get resolved once the multiclass template arguments are
// known before any use.
NewRec->setResolveFirst(true);
// Otherwise, we're inside a multiclass, add it to the multiclass.
CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
// Copy the template arguments for the multiclass into the def.
for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
assert(RV && "Template arg doesn't exist?");
NewRec->addValue(*RV);
}
// We can't return the prototype def here, instead return:
// !cast<ItemType>(!strconcat(NAME, AnonName)).
const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
assert(MCNameRV && "multiclass record must have a NAME");
return UnOpInit::get(UnOpInit::CAST,
BinOpInit::get(BinOpInit::STRCONCAT,
VarInit::get(MCNameRV->getName(),
MCNameRV->getType()),
NewRec->getNameInit(),
StringRecTy::get()),
Class->getDefInit()->getType());
}
// The result of the expression is a reference to the new record.
return DefInit::get(NewRec);
}
case tgtok::l_brace: { // Value ::= '{' ValueList '}'
SMLoc BraceLoc = Lex.getLoc();
Lex.Lex(); // eat the '{'
std::vector<Init*> Vals;
if (Lex.getCode() != tgtok::r_brace) {
Vals = ParseValueList(CurRec);
if (Vals.empty()) return nullptr;
}
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of bit list value");
return nullptr;
}
Lex.Lex(); // eat the '}'
SmallVector<Init *, 16> NewBits;
// As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
// first. We'll first read everything in to a vector, then we can reverse
// it to get the bits in the correct order for the BitsInit value.
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
// FIXME: The following two loops would not be duplicated
// if the API was a little more orthogonal.
// bits<n> values are allowed to initialize n bits.
if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
NewBits.push_back(BI->getBit((e - i) - 1));
continue;
}
// bits<n> can also come from variable initializers.
if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
NewBits.push_back(VI->getBit((e - i) - 1));
continue;
}
// Fallthrough to try convert this to a bit.
}
// All other values must be convertible to just a single bit.
Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
if (!Bit) {
Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
") is not convertable to a bit");
return nullptr;
}
NewBits.push_back(Bit);
}
std::reverse(NewBits.begin(), NewBits.end());
return BitsInit::get(NewBits);
}
case tgtok::l_square: { // Value ::= '[' ValueList ']'
Lex.Lex(); // eat the '['
std::vector<Init*> Vals;
RecTy *DeducedEltTy = nullptr;
ListRecTy *GivenListTy = nullptr;
if (ItemType) {
ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
if (!ListType) {
TokError(Twine("Type mismatch for list, expected list type, got ") +
ItemType->getAsString());
return nullptr;
}
GivenListTy = ListType;
}
if (Lex.getCode() != tgtok::r_square) {
Vals = ParseValueList(CurRec, nullptr,
GivenListTy ? GivenListTy->getElementType() : nullptr);
if (Vals.empty()) return nullptr;
}
if (Lex.getCode() != tgtok::r_square) {
TokError("expected ']' at end of list value");
return nullptr;
}
Lex.Lex(); // eat the ']'
RecTy *GivenEltTy = nullptr;
if (Lex.getCode() == tgtok::less) {
// Optional list element type
Lex.Lex(); // eat the '<'
GivenEltTy = ParseType();
if (!GivenEltTy) {
// Couldn't parse element type
return nullptr;
}
if (Lex.getCode() != tgtok::greater) {
TokError("expected '>' at end of list element type");
return nullptr;
}
Lex.Lex(); // eat the '>'
}
// Check elements
RecTy *EltTy = nullptr;
for (Init *V : Vals) {
TypedInit *TArg = dyn_cast<TypedInit>(V);
if (!TArg) {
TokError("Untyped list element");
return nullptr;
}
if (EltTy) {
EltTy = resolveTypes(EltTy, TArg->getType());
if (!EltTy) {
TokError("Incompatible types in list elements");
return nullptr;
}
} else {
EltTy = TArg->getType();
}
}
if (GivenEltTy) {
if (EltTy) {
// Verify consistency
if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
TokError("Incompatible types in list elements");
return nullptr;
}
}
EltTy = GivenEltTy;
}
if (!EltTy) {
if (!ItemType) {
TokError("No type for list");
return nullptr;
}
DeducedEltTy = GivenListTy->getElementType();
} else {
// Make sure the deduced type is compatible with the given type
if (GivenListTy) {
if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
TokError("Element type mismatch for list");
return nullptr;
}
}
DeducedEltTy = EltTy;
}
return ListInit::get(Vals, DeducedEltTy);
}
case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
Lex.Lex(); // eat the '('
if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
TokError("expected identifier in dag init");
return nullptr;
}
Init *Operator = ParseValue(CurRec);
if (!Operator) return nullptr;
// If the operator name is present, parse it.
std::string OperatorName;
if (Lex.getCode() == tgtok::colon) {
if (Lex.Lex() != tgtok::VarName) { // eat the ':'
TokError("expected variable name in dag operator");
return nullptr;
}
OperatorName = Lex.getCurStrVal();
Lex.Lex(); // eat the VarName.
}
std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
if (Lex.getCode() != tgtok::r_paren) {
DagArgs = ParseDagArgList(CurRec);
if (DagArgs.empty()) return nullptr;
}
if (Lex.getCode() != tgtok::r_paren) {
TokError("expected ')' in dag init");
return nullptr;
}
Lex.Lex(); // eat the ')'
return DagInit::get(Operator, OperatorName, DagArgs);
}
case tgtok::XHead:
case tgtok::XTail:
case tgtok::XEmpty:
case tgtok::XCast: // Value ::= !unop '(' Value ')'
case tgtok::XConcat:
case tgtok::XADD:
case tgtok::XAND:
case tgtok::XSRA:
case tgtok::XSRL:
case tgtok::XSHL:
case tgtok::XEq:
case tgtok::XListConcat:
case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
case tgtok::XIf:
case tgtok::XForEach:
case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
return ParseOperation(CurRec, ItemType);
}
}
return R;
}
/// ParseValue - Parse a tblgen value. This returns null on error.
///
/// Value ::= SimpleValue ValueSuffix*
/// ValueSuffix ::= '{' BitList '}'
/// ValueSuffix ::= '[' BitList ']'
/// ValueSuffix ::= '.' ID
///
Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
if (!Result) return nullptr;
// Parse the suffixes now if present.
while (1) {
switch (Lex.getCode()) {
default: return Result;
case tgtok::l_brace: {
if (Mode == ParseNameMode || Mode == ParseForeachMode)
// This is the beginning of the object body.
return Result;
SMLoc CurlyLoc = Lex.getLoc();
Lex.Lex(); // eat the '{'
std::vector<unsigned> Ranges = ParseRangeList();
if (Ranges.empty()) return nullptr;
// Reverse the bitlist.
std::reverse(Ranges.begin(), Ranges.end());
Result = Result->convertInitializerBitRange(Ranges);
if (!Result) {
Error(CurlyLoc, "Invalid bit range for value");
return nullptr;
}
// Eat the '}'.
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of bit range list");
return nullptr;
}
Lex.Lex();
break;
}
case tgtok::l_square: {
SMLoc SquareLoc = Lex.getLoc();
Lex.Lex(); // eat the '['
std::vector<unsigned> Ranges = ParseRangeList();
if (Ranges.empty()) return nullptr;
Result = Result->convertInitListSlice(Ranges);
if (!Result) {
Error(SquareLoc, "Invalid range for list slice");
return nullptr;
}
// Eat the ']'.
if (Lex.getCode() != tgtok::r_square) {
TokError("expected ']' at end of list slice");
return nullptr;
}
Lex.Lex();
break;
}
case tgtok::period:
if (Lex.Lex() != tgtok::Id) { // eat the .
TokError("expected field identifier after '.'");
return nullptr;
}
if (!Result->getFieldType(Lex.getCurStrVal())) {
TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
Result->getAsString() + "'");
return nullptr;
}
Result = FieldInit::get(Result, Lex.getCurStrVal());
Lex.Lex(); // eat field name
break;
case tgtok::paste:
SMLoc PasteLoc = Lex.getLoc();
// Create a !strconcat() operation, first casting each operand to
// a string if necessary.
TypedInit *LHS = dyn_cast<TypedInit>(Result);
if (!LHS) {
Error(PasteLoc, "LHS of paste is not typed!");
return nullptr;
}
if (LHS->getType() != StringRecTy::get()) {
LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
}
TypedInit *RHS = nullptr;
Lex.Lex(); // Eat the '#'.
switch (Lex.getCode()) {
case tgtok::colon:
case tgtok::semi:
case tgtok::l_brace:
// These are all of the tokens that can begin an object body.
// Some of these can also begin values but we disallow those cases
// because they are unlikely to be useful.
// Trailing paste, concat with an empty string.
RHS = StringInit::get("");
break;
default:
Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
RHS = dyn_cast<TypedInit>(RHSResult);
if (!RHS) {
Error(PasteLoc, "RHS of paste is not typed!");
return nullptr;
}
if (RHS->getType() != StringRecTy::get()) {
RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
}
break;
}
Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
StringRecTy::get())->Fold(CurRec, CurMultiClass);
break;
}
}
}
/// ParseDagArgList - Parse the argument list for a dag literal expression.
///
/// DagArg ::= Value (':' VARNAME)?
/// DagArg ::= VARNAME
/// DagArgList ::= DagArg
/// DagArgList ::= DagArgList ',' DagArg
std::vector<std::pair<llvm::Init*, std::string> >
TGParser::ParseDagArgList(Record *CurRec) {
std::vector<std::pair<llvm::Init*, std::string> > Result;
while (1) {
// DagArg ::= VARNAME
if (Lex.getCode() == tgtok::VarName) {
// A missing value is treated like '?'.
Result.emplace_back(UnsetInit::get(), Lex.getCurStrVal());
Lex.Lex();
} else {
// DagArg ::= Value (':' VARNAME)?
Init *Val = ParseValue(CurRec);
if (!Val)
return std::vector<std::pair<llvm::Init*, std::string> >();
// If the variable name is present, add it.
std::string VarName;
if (Lex.getCode() == tgtok::colon) {
if (Lex.Lex() != tgtok::VarName) { // eat the ':'
TokError("expected variable name in dag literal");
return std::vector<std::pair<llvm::Init*, std::string> >();
}
VarName = Lex.getCurStrVal();
Lex.Lex(); // eat the VarName.
}
Result.push_back(std::make_pair(Val, VarName));
}
if (Lex.getCode() != tgtok::comma) break;
Lex.Lex(); // eat the ','
}
return Result;
}
/// ParseValueList - Parse a comma separated list of values, returning them as a
/// vector. Note that this always expects to be able to parse at least one
/// value. It returns an empty list if this is not possible.
///
/// ValueList ::= Value (',' Value)
///
std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
RecTy *EltTy) {
std::vector<Init*> Result;
RecTy *ItemType = EltTy;
unsigned int ArgN = 0;
if (ArgsRec && !EltTy) {
const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
if (TArgs.empty()) {
TokError("template argument provided to non-template class");
return std::vector<Init*>();
}
const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
if (!RV) {
errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
<< ")\n";
}
assert(RV && "Template argument record not found??");
ItemType = RV->getType();
++ArgN;
}
Result.push_back(ParseValue(CurRec, ItemType));
if (!Result.back()) return std::vector<Init*>();
while (Lex.getCode() == tgtok::comma) {
Lex.Lex(); // Eat the comma
if (ArgsRec && !EltTy) {
const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
if (ArgN >= TArgs.size()) {
TokError("too many template arguments");
return std::vector<Init*>();
}
const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
assert(RV && "Template argument record not found??");
ItemType = RV->getType();
++ArgN;
}
Result.push_back(ParseValue(CurRec, ItemType));
if (!Result.back()) return std::vector<Init*>();
}
return Result;
}
/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
/// empty string on error. This can happen in a number of different context's,
/// including within a def or in the template args for a def (which which case
/// CurRec will be non-null) and within the template args for a multiclass (in
/// which case CurRec will be null, but CurMultiClass will be set). This can
/// also happen within a def that is within a multiclass, which will set both
/// CurRec and CurMultiClass.
///
/// Declaration ::= FIELD? Type ID ('=' Value)?
///
Init *TGParser::ParseDeclaration(Record *CurRec,
bool ParsingTemplateArgs) {
// Read the field prefix if present.
bool HasField = Lex.getCode() == tgtok::Field;
if (HasField) Lex.Lex();
RecTy *Type = ParseType();
if (!Type) return nullptr;
if (Lex.getCode() != tgtok::Id) {
TokError("Expected identifier in declaration");
return nullptr;
}
SMLoc IdLoc = Lex.getLoc();
Init *DeclName = StringInit::get(Lex.getCurStrVal());
Lex.Lex();
if (ParsingTemplateArgs) {
if (CurRec)
DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
else
assert(CurMultiClass);
if (CurMultiClass)
DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
"::");
}
// Add the value.
if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
return nullptr;
// If a value is present, parse it.
if (Lex.getCode() == tgtok::equal) {
Lex.Lex();
SMLoc ValLoc = Lex.getLoc();
Init *Val = ParseValue(CurRec, Type);
if (!Val ||
SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
// Return the name, even if an error is thrown. This is so that we can
// continue to make some progress, even without the value having been
// initialized.
return DeclName;
}
return DeclName;
}
/// ParseForeachDeclaration - Read a foreach declaration, returning
/// the name of the declared object or a NULL Init on error. Return
/// the name of the parsed initializer list through ForeachListName.
///
/// ForeachDeclaration ::= ID '=' '[' ValueList ']'
/// ForeachDeclaration ::= ID '=' '{' RangeList '}'
/// ForeachDeclaration ::= ID '=' RangePiece
///
VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
if (Lex.getCode() != tgtok::Id) {
TokError("Expected identifier in foreach declaration");
return nullptr;
}
Init *DeclName = StringInit::get(Lex.getCurStrVal());
Lex.Lex();
// If a value is present, parse it.
if (Lex.getCode() != tgtok::equal) {
TokError("Expected '=' in foreach declaration");
return nullptr;
}
Lex.Lex(); // Eat the '='
RecTy *IterType = nullptr;
std::vector<unsigned> Ranges;
switch (Lex.getCode()) {
default: TokError("Unknown token when expecting a range list"); return nullptr;
case tgtok::l_square: { // '[' ValueList ']'
Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
ForeachListValue = dyn_cast<ListInit>(List);
if (!ForeachListValue) {
TokError("Expected a Value list");
return nullptr;
}
RecTy *ValueType = ForeachListValue->getType();
ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
if (!ListType) {
TokError("Value list is not of list type");
return nullptr;
}
IterType = ListType->getElementType();
break;
}
case tgtok::IntVal: { // RangePiece.
if (ParseRangePiece(Ranges))
return nullptr;
break;
}
case tgtok::l_brace: { // '{' RangeList '}'
Lex.Lex(); // eat the '{'
Ranges = ParseRangeList();
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of bit range list");
return nullptr;
}
Lex.Lex();
break;
}
}
if (!Ranges.empty()) {
assert(!IterType && "Type already initialized?");
IterType = IntRecTy::get();
std::vector<Init*> Values;
for (unsigned R : Ranges)
Values.push_back(IntInit::get(R));
ForeachListValue = ListInit::get(Values, IterType);
}
if (!IterType)
return nullptr;
return VarInit::get(DeclName, IterType);
}
/// ParseTemplateArgList - Read a template argument list, which is a non-empty
/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
/// template args for a def, which may or may not be in a multiclass. If null,
/// these are the template args for a multiclass.
///
/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
///
bool TGParser::ParseTemplateArgList(Record *CurRec) {
assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
Lex.Lex(); // eat the '<'
Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
// Read the first declaration.
Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
if (!TemplArg)
return true;
TheRecToAddTo->addTemplateArg(TemplArg);
while (Lex.getCode() == tgtok::comma) {
Lex.Lex(); // eat the ','
// Read the following declarations.
TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
if (!TemplArg)
return true;
TheRecToAddTo->addTemplateArg(TemplArg);
}
if (Lex.getCode() != tgtok::greater)
return TokError("expected '>' at end of template argument list");
Lex.Lex(); // eat the '>'.
return false;
}
/// ParseBodyItem - Parse a single item at within the body of a def or class.
///
/// BodyItem ::= Declaration ';'
/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
bool TGParser::ParseBodyItem(Record *CurRec) {
if (Lex.getCode() != tgtok::Let) {
if (!ParseDeclaration(CurRec, false))
return true;
if (Lex.getCode() != tgtok::semi)
return TokError("expected ';' after declaration");
Lex.Lex();
return false;
}
// LET ID OptionalRangeList '=' Value ';'
if (Lex.Lex() != tgtok::Id)
return TokError("expected field identifier after let");
SMLoc IdLoc = Lex.getLoc();
std::string FieldName = Lex.getCurStrVal();
Lex.Lex(); // eat the field name.
std::vector<unsigned> BitList;
if (ParseOptionalBitList(BitList))
return true;
std::reverse(BitList.begin(), BitList.end());
if (Lex.getCode() != tgtok::equal)
return TokError("expected '=' in let expression");
Lex.Lex(); // eat the '='.
RecordVal *Field = CurRec->getValue(FieldName);
if (!Field)
return TokError("Value '" + FieldName + "' unknown!");
RecTy *Type = Field->getType();
Init *Val = ParseValue(CurRec, Type);
if (!Val) return true;
if (Lex.getCode() != tgtok::semi)
return TokError("expected ';' after let expression");
Lex.Lex();
return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
}
/// ParseBody - Read the body of a class or def. Return true on error, false on
/// success.
///
/// Body ::= ';'
/// Body ::= '{' BodyList '}'
/// BodyList BodyItem*
///
bool TGParser::ParseBody(Record *CurRec) {
// If this is a null definition, just eat the semi and return.
if (Lex.getCode() == tgtok::semi) {
Lex.Lex();
return false;
}
if (Lex.getCode() != tgtok::l_brace)
return TokError("Expected ';' or '{' to start body");
// Eat the '{'.
Lex.Lex();
while (Lex.getCode() != tgtok::r_brace)
if (ParseBodyItem(CurRec))
return true;
// Eat the '}'.
Lex.Lex();
return false;
}
/// \brief Apply the current let bindings to \a CurRec.
/// \returns true on error, false otherwise.
bool TGParser::ApplyLetStack(Record *CurRec) {
for (std::vector<LetRecord> &LetInfo : LetStack)
for (LetRecord &LR : LetInfo)
if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
return true;
return false;
}
/// ParseObjectBody - Parse the body of a def or class. This consists of an
/// optional ClassList followed by a Body. CurRec is the current def or class
/// that is being parsed.
///
/// ObjectBody ::= BaseClassList Body
/// BaseClassList ::= /*empty*/
/// BaseClassList ::= ':' BaseClassListNE
/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
///
bool TGParser::ParseObjectBody(Record *CurRec) {
// If there is a baseclass list, read it.
if (Lex.getCode() == tgtok::colon) {
Lex.Lex();
// Read all of the subclasses.
SubClassReference SubClass = ParseSubClassReference(CurRec, false);
while (1) {
// Check for error.
if (!SubClass.Rec) return true;
// Add it.
if (AddSubClass(CurRec, SubClass))
return true;
if (Lex.getCode() != tgtok::comma) break;
Lex.Lex(); // eat ','.
SubClass = ParseSubClassReference(CurRec, false);
}
}
if (ApplyLetStack(CurRec))
return true;
return ParseBody(CurRec);
}
/// ParseDef - Parse and return a top level or multiclass def, return the record
/// corresponding to it. This returns null on error.
///
/// DefInst ::= DEF ObjectName ObjectBody
///
bool TGParser::ParseDef(MultiClass *CurMultiClass) {
SMLoc DefLoc = Lex.getLoc();
assert(Lex.getCode() == tgtok::Def && "Unknown tok");
Lex.Lex(); // Eat the 'def' token.
// Parse ObjectName and make a record for it.
std::unique_ptr<Record> CurRecOwner;
Init *Name = ParseObjectName(CurMultiClass);
if (Name)
CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
else
CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
Records, /*IsAnonymous=*/true);
Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
if (!CurMultiClass && Loops.empty()) {
// Top-level def definition.
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getNameInitAsString()))
return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
"' already defined");
Records.addDef(std::move(CurRecOwner));
if (ParseObjectBody(CurRec))
return true;
} else if (CurMultiClass) {
// Parse the body before adding this prototype to the DefPrototypes vector.
// That way implicit definitions will be added to the DefPrototypes vector
// before this object, instantiated prior to defs derived from this object,
// and this available for indirect name resolution when defs derived from
// this object are instantiated.
if (ParseObjectBody(CurRec))
return true;
// Otherwise, a def inside a multiclass, add it to the multiclass.
for (const auto &Proto : CurMultiClass->DefPrototypes)
if (Proto->getNameInit() == CurRec->getNameInit())
return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
"' already defined in this multiclass!");
CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
} else if (ParseObjectBody(CurRec)) {
return true;
}
if (!CurMultiClass) // Def's in multiclasses aren't really defs.
// See Record::setName(). This resolve step will see any new name
// for the def that might have been created when resolving
// inheritance, values and arguments above.
CurRec->resolveReferences();
// If ObjectBody has template arguments, it's an error.
assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
if (CurMultiClass) {
// Copy the template arguments for the multiclass into the def.
for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
assert(RV && "Template arg doesn't exist?");
CurRec->addValue(*RV);
}
}
if (ProcessForeachDefs(CurRec, DefLoc))
return Error(DefLoc, "Could not process loops for def" +
CurRec->getNameInitAsString());
return false;
}
/// ParseForeach - Parse a for statement. Return the record corresponding
/// to it. This returns true on error.
///
/// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
/// Foreach ::= FOREACH Declaration IN Object
///
bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
Lex.Lex(); // Eat the 'for' token.
// Make a temporary object to record items associated with the for
// loop.
ListInit *ListValue = nullptr;
VarInit *IterName = ParseForeachDeclaration(ListValue);
if (!IterName)
return TokError("expected declaration in for");
if (Lex.getCode() != tgtok::In)
return TokError("Unknown tok");
Lex.Lex(); // Eat the in
// Create a loop object and remember it.
Loops.push_back(ForeachLoop(IterName, ListValue));
if (Lex.getCode() != tgtok::l_brace) {
// FOREACH Declaration IN Object
if (ParseObject(CurMultiClass))
return true;
} else {
SMLoc BraceLoc = Lex.getLoc();
// Otherwise, this is a group foreach.
Lex.Lex(); // eat the '{'.
// Parse the object list.
if (ParseObjectList(CurMultiClass))
return true;
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of foreach command");
return Error(BraceLoc, "to match this '{'");
}
Lex.Lex(); // Eat the }
}
// We've processed everything in this loop.
Loops.pop_back();
return false;
}
/// ParseClass - Parse a tblgen class definition.
///
/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
///
bool TGParser::ParseClass() {
assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
Lex.Lex();
if (Lex.getCode() != tgtok::Id)
return TokError("expected class name after 'class' keyword");
Record *CurRec = Records.getClass(Lex.getCurStrVal());
if (CurRec) {
// If the body was previously defined, this is an error.
if (CurRec->getValues().size() > 1 || // Account for NAME.
!CurRec->getSuperClasses().empty() ||
!CurRec->getTemplateArgs().empty())
return TokError("Class '" + CurRec->getNameInitAsString() +
"' already defined");
} else {
// If this is the first reference to this class, create and add it.
auto NewRec =
llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
CurRec = NewRec.get();
Records.addClass(std::move(NewRec));
}
Lex.Lex(); // eat the name.
// If there are template args, parse them.
if (Lex.getCode() == tgtok::less)
if (ParseTemplateArgList(CurRec))
return true;
// Finally, parse the object body.
return ParseObjectBody(CurRec);
}
/// ParseLetList - Parse a non-empty list of assignment expressions into a list
/// of LetRecords.
///
/// LetList ::= LetItem (',' LetItem)*
/// LetItem ::= ID OptionalRangeList '=' Value
///
std::vector<LetRecord> TGParser::ParseLetList() {
std::vector<LetRecord> Result;
while (1) {
if (Lex.getCode() != tgtok::Id) {
TokError("expected identifier in let definition");
return std::vector<LetRecord>();
}
std::string Name = Lex.getCurStrVal();
SMLoc NameLoc = Lex.getLoc();
Lex.Lex(); // Eat the identifier.
// Check for an optional RangeList.
std::vector<unsigned> Bits;
if (ParseOptionalRangeList(Bits))
return std::vector<LetRecord>();
std::reverse(Bits.begin(), Bits.end());
if (Lex.getCode() != tgtok::equal) {
TokError("expected '=' in let expression");
return std::vector<LetRecord>();
}
Lex.Lex(); // eat the '='.
Init *Val = ParseValue(nullptr);
if (!Val) return std::vector<LetRecord>();
// Now that we have everything, add the record.
Result.emplace_back(std::move(Name), std::move(Bits), Val, NameLoc);
if (Lex.getCode() != tgtok::comma)
return Result;
Lex.Lex(); // eat the comma.
}
}
/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
/// different related productions. This works inside multiclasses too.
///
/// Object ::= LET LetList IN '{' ObjectList '}'
/// Object ::= LET LetList IN Object
///
bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
assert(Lex.getCode() == tgtok::Let && "Unexpected token");
Lex.Lex();
// Add this entry to the let stack.
std::vector<LetRecord> LetInfo = ParseLetList();
if (LetInfo.empty()) return true;
LetStack.push_back(std::move(LetInfo));
if (Lex.getCode() != tgtok::In)
return TokError("expected 'in' at end of top-level 'let'");
Lex.Lex();
// If this is a scalar let, just handle it now
if (Lex.getCode() != tgtok::l_brace) {
// LET LetList IN Object
if (ParseObject(CurMultiClass))
return true;
} else { // Object ::= LETCommand '{' ObjectList '}'
SMLoc BraceLoc = Lex.getLoc();
// Otherwise, this is a group let.
Lex.Lex(); // eat the '{'.
// Parse the object list.
if (ParseObjectList(CurMultiClass))
return true;
if (Lex.getCode() != tgtok::r_brace) {
TokError("expected '}' at end of top level let command");
return Error(BraceLoc, "to match this '{'");
}
Lex.Lex();
}
// Outside this let scope, this let block is not active.
LetStack.pop_back();
return false;
}
/// ParseMultiClass - Parse a multiclass definition.
///
/// MultiClassInst ::= MULTICLASS ID TemplateArgList?
/// ':' BaseMultiClassList '{' MultiClassObject+ '}'
/// MultiClassObject ::= DefInst
/// MultiClassObject ::= MultiClassInst
/// MultiClassObject ::= DefMInst
/// MultiClassObject ::= LETCommand '{' ObjectList '}'
/// MultiClassObject ::= LETCommand Object
///
bool TGParser::ParseMultiClass() {
assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
Lex.Lex(); // Eat the multiclass token.
if (Lex.getCode() != tgtok::Id)
return TokError("expected identifier after multiclass for name");
std::string Name = Lex.getCurStrVal();
auto Result =
MultiClasses.insert(std::make_pair(Name,
llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
if (!Result.second)
return TokError("multiclass '" + Name + "' already defined");
CurMultiClass = Result.first->second.get();
Lex.Lex(); // Eat the identifier.
// If there are template args, parse them.
if (Lex.getCode() == tgtok::less)
if (ParseTemplateArgList(nullptr))
return true;
bool inherits = false;
// If there are submulticlasses, parse them.
if (Lex.getCode() == tgtok::colon) {
inherits = true;
Lex.Lex();
// Read all of the submulticlasses.
SubMultiClassReference SubMultiClass =
ParseSubMultiClassReference(CurMultiClass);
while (1) {
// Check for error.
if (!SubMultiClass.MC) return true;
// Add it.
if (AddSubMultiClass(CurMultiClass, SubMultiClass))
return true;
if (Lex.getCode() != tgtok::comma) break;
Lex.Lex(); // eat ','.
SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
}
}
if (Lex.getCode() != tgtok::l_brace) {
if (!inherits)
return TokError("expected '{' in multiclass definition");
if (Lex.getCode() != tgtok::semi)
return TokError("expected ';' in multiclass definition");
Lex.Lex(); // eat the ';'.
} else {
if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
return TokError("multiclass must contain at least one def");
while (Lex.getCode() != tgtok::r_brace) {
switch (Lex.getCode()) {
default:
return TokError("expected 'let', 'def' or 'defm' in multiclass body");
case tgtok::Let:
case tgtok::Def:
case tgtok::Defm:
case tgtok::Foreach:
if (ParseObject(CurMultiClass))
return true;
break;
}
}
Lex.Lex(); // eat the '}'.
}
CurMultiClass = nullptr;
return false;
}
Record *TGParser::
InstantiateMulticlassDef(MultiClass &MC,
Record *DefProto,
Init *&DefmPrefix,
SMRange DefmPrefixRange,
const std::vector<Init *> &TArgs,
std::vector<Init *> &TemplateVals) {
// We need to preserve DefProto so it can be reused for later
// instantiations, so create a new Record to inherit from it.
// Add in the defm name. If the defm prefix is empty, give each
// instantiated def a unique name. Otherwise, if "#NAME#" exists in the
// name, substitute the prefix for #NAME#. Otherwise, use the defm name
// as a prefix.
bool IsAnonymous = false;
if (!DefmPrefix) {
DefmPrefix = StringInit::get(GetNewAnonymousName());
IsAnonymous = true;
}
Init *DefName = DefProto->getNameInit();
StringInit *DefNameString = dyn_cast<StringInit>(DefName);
if (DefNameString) {
// We have a fully expanded string so there are no operators to
// resolve. We should concatenate the given prefix and name.
DefName =
BinOpInit::get(BinOpInit::STRCONCAT,
UnOpInit::get(UnOpInit::CAST, DefmPrefix,
StringRecTy::get())->Fold(DefProto, &MC),
DefName, StringRecTy::get())->Fold(DefProto, &MC);
}
// Make a trail of SMLocs from the multiclass instantiations.
SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
SubClassReference Ref;
Ref.RefRange = DefmPrefixRange;
Ref.Rec = DefProto;
AddSubClass(CurRec.get(), Ref);
// Set the value for NAME. We don't resolve references to it 'til later,
// though, so that uses in nested multiclass names don't get
// confused.
if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
std::vector<unsigned>(), DefmPrefix)) {
Error(DefmPrefixRange.Start, "Could not resolve " +
CurRec->getNameInitAsString() + ":NAME to '" +
DefmPrefix->getAsUnquotedString() + "'");
return nullptr;
}
// If the DefNameString didn't resolve, we probably have a reference to
// NAME and need to replace it. We need to do at least this much greedily,
// otherwise nested multiclasses will end up with incorrect NAME expansions.
if (!DefNameString) {
RecordVal *DefNameRV = CurRec->getValue("NAME");
CurRec->resolveReferencesTo(DefNameRV);
}
if (!CurMultiClass) {
// Now that we're at the top level, resolve all NAME references
// in the resultant defs that weren't in the def names themselves.
RecordVal *DefNameRV = CurRec->getValue("NAME");
CurRec->resolveReferencesTo(DefNameRV);
// Check if the name is a complex pattern.
// If so, resolve it.
DefName = CurRec->getNameInit();
DefNameString = dyn_cast<StringInit>(DefName);
// OK the pattern is more complex than simply using NAME.
// Let's use the heavy weaponery.
if (!DefNameString) {
ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
Lex.getLoc(), TArgs, TemplateVals,
false/*Delete args*/);
DefName = CurRec->getNameInit();
DefNameString = dyn_cast<StringInit>(DefName);
if (!DefNameString)
DefName = DefName->convertInitializerTo(StringRecTy::get());
// We ran out of options here...
DefNameString = dyn_cast<StringInit>(DefName);
if (!DefNameString) {
PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
DefName->getAsUnquotedString() + " is not a string.");
return nullptr;
}
CurRec->setName(DefName);
}
// Now that NAME references are resolved and we're at the top level of
// any multiclass expansions, add the record to the RecordKeeper. If we are
// currently in a multiclass, it means this defm appears inside a
// multiclass and its name won't be fully resolvable until we see
// the top-level defm. Therefore, we don't add this to the
// RecordKeeper at this point. If we did we could get duplicate
// defs as more than one probably refers to NAME or some other
// common internal placeholder.
// Ensure redefinition doesn't happen.
if (Records.getDef(CurRec->getNameInitAsString())) {
Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
"' already defined, instantiating defm with subdef '" +
DefProto->getNameInitAsString() + "'");
return nullptr;
}
Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
Records.addDef(std::move(CurRec));
return CurRecSave;
}
// FIXME This is bad but the ownership transfer to caller is pretty messy.
// The unique_ptr in this function at least protects the exits above.
return CurRec.release();
}
bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
Record *CurRec,
SMLoc DefmPrefixLoc,
SMLoc SubClassLoc,
const std::vector<Init *> &TArgs,
std::vector<Init *> &TemplateVals,
bool DeleteArgs) {
// Loop over all of the template arguments, setting them to the specified
// value or leaving them as the default if necessary.
for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
// Check if a value is specified for this temp-arg.
if (i < TemplateVals.size()) {
// Set it now.
if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
TemplateVals[i]))
return true;
// Resolve it next.
CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
if (DeleteArgs)
// Now remove it.
CurRec->removeValue(TArgs[i]);
} else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
return Error(SubClassLoc, "value not specified for template argument #" +
Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
") of multiclassclass '" + MC.Rec.getNameInitAsString() +
"'");
}
}
return false;
}
bool TGParser::ResolveMulticlassDef(MultiClass &MC,
Record *CurRec,
Record *DefProto,
SMLoc DefmPrefixLoc) {
// If the mdef is inside a 'let' expression, add to each def.
if (ApplyLetStack(CurRec))
return Error(DefmPrefixLoc, "when instantiating this defm");
// Don't create a top level definition for defm inside multiclasses,
// instead, only update the prototypes and bind the template args
// with the new created definition.
if (!CurMultiClass)
return false;
for (const auto &Proto : CurMultiClass->DefPrototypes)
if (Proto->getNameInit() == CurRec->getNameInit())
return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
"' already defined in this multiclass!");
CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
// Copy the template arguments for the multiclass into the new def.
for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
assert(RV && "Template arg doesn't exist?");
CurRec->addValue(*RV);
}
return false;
}
/// ParseDefm - Parse the instantiation of a multiclass.
///
/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
///
bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
SMLoc DefmLoc = Lex.getLoc();
Init *DefmPrefix = nullptr;
if (Lex.Lex() == tgtok::Id) { // eat the defm.
DefmPrefix = ParseObjectName(CurMultiClass);
}
SMLoc DefmPrefixEndLoc = Lex.getLoc();
if (Lex.getCode() != tgtok::colon)
return TokError("expected ':' after defm identifier");
// Keep track of the new generated record definitions.
std::vector<Record*> NewRecDefs;
// This record also inherits from a regular class (non-multiclass)?
bool InheritFromClass = false;
// eat the colon.
Lex.Lex();
SMLoc SubClassLoc = Lex.getLoc();
SubClassReference Ref = ParseSubClassReference(nullptr, true);
while (1) {
if (!Ref.Rec) return true;
// To instantiate a multiclass, we need to first get the multiclass, then
// instantiate each def contained in the multiclass with the SubClassRef
// template parameters.
MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
assert(MC && "Didn't lookup multiclass correctly?");
std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
// Verify that the correct number of template arguments were specified.
const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
if (TArgs.size() < TemplateVals.size())
return Error(SubClassLoc,
"more template args specified than multiclass expects");
// Loop over all the def's in the multiclass, instantiating each one.
for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
// The record name construction goes as follow:
// - If the def name is a string, prepend the prefix.
// - If the def name is a more complex pattern, use that pattern.
// As a result, the record is instanciated before resolving
// arguments, as it would make its name a string.
Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
SMRange(DefmLoc,
DefmPrefixEndLoc),
TArgs, TemplateVals);
if (!CurRec)
return true;
// Now that the record is instanciated, we can resolve arguments.
if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
TArgs, TemplateVals, true/*Delete args*/))
return Error(SubClassLoc, "could not instantiate def");
if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
return Error(SubClassLoc, "could not instantiate def");
// Defs that can be used by other definitions should be fully resolved
// before any use.
if (DefProto->isResolveFirst() && !CurMultiClass) {
CurRec->resolveReferences();
CurRec->setResolveFirst(false);
}
NewRecDefs.push_back(CurRec);
}
if (Lex.getCode() != tgtok::comma) break;
Lex.Lex(); // eat ','.
if (Lex.getCode() != tgtok::Id)
return TokError("expected identifier");
SubClassLoc = Lex.getLoc();
// A defm can inherit from regular classes (non-multiclass) as
// long as they come in the end of the inheritance list.
InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
if (InheritFromClass)
break;
Ref = ParseSubClassReference(nullptr, true);
}
if (InheritFromClass) {
// Process all the classes to inherit as if they were part of a
// regular 'def' and inherit all record values.
SubClassReference SubClass = ParseSubClassReference(nullptr, false);
while (1) {
// Check for error.
if (!SubClass.Rec) return true;
// Get the expanded definition prototypes and teach them about
// the record values the current class to inherit has
for (Record *CurRec : NewRecDefs) {
// Add it.
if (AddSubClass(CurRec, SubClass))
return true;
if (ApplyLetStack(CurRec))
return true;
}
if (Lex.getCode() != tgtok::comma) break;
Lex.Lex(); // eat ','.
SubClass = ParseSubClassReference(nullptr, false);
}
}
if (!CurMultiClass)
for (Record *CurRec : NewRecDefs)
// See Record::setName(). This resolve step will see any new
// name for the def that might have been created when resolving
// inheritance, values and arguments above.
CurRec->resolveReferences();
if (Lex.getCode() != tgtok::semi)
return TokError("expected ';' at end of defm");
Lex.Lex();
return false;
}
/// ParseObject
/// Object ::= ClassInst
/// Object ::= DefInst
/// Object ::= MultiClassInst
/// Object ::= DefMInst
/// Object ::= LETCommand '{' ObjectList '}'
/// Object ::= LETCommand Object
bool TGParser::ParseObject(MultiClass *MC) {
switch (Lex.getCode()) {
default:
return TokError("Expected class, def, defm, multiclass or let definition");
case tgtok::Let: return ParseTopLevelLet(MC);
case tgtok::Def: return ParseDef(MC);
case tgtok::Foreach: return ParseForeach(MC);
case tgtok::Defm: return ParseDefm(MC);
case tgtok::Class: return ParseClass();
case tgtok::MultiClass: return ParseMultiClass();
}
}
/// ParseObjectList
/// ObjectList :== Object*
bool TGParser::ParseObjectList(MultiClass *MC) {
while (isObjectStart(Lex.getCode())) {
if (ParseObject(MC))
return true;
}
return false;
}
bool TGParser::ParseFile() {
Lex.Lex(); // Prime the lexer.
if (ParseObjectList()) return true;
// If we have unread input at the end of the file, report it.
if (Lex.getCode() == tgtok::Eof)
return false;
return TokError("Unexpected input at top level");
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/Error.cpp | //===- Error.cpp - tblgen error handling helper routines --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains error handling helper routines to pretty-print diagnostic
// messages from tblgen.
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/Error.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
namespace llvm {
SourceMgr SrcMgr;
unsigned ErrorsPrinted = 0;
static void PrintMessage(ArrayRef<SMLoc> Loc, SourceMgr::DiagKind Kind,
const Twine &Msg) {
// Count the total number of errors printed.
// This is used to exit with an error code if there were any errors.
if (Kind == SourceMgr::DK_Error)
++ErrorsPrinted;
SMLoc NullLoc;
if (Loc.empty())
Loc = NullLoc;
SrcMgr.PrintMessage(Loc.front(), Kind, Msg);
for (unsigned i = 1; i < Loc.size(); ++i)
SrcMgr.PrintMessage(Loc[i], SourceMgr::DK_Note,
"instantiated from multiclass");
}
void PrintWarning(ArrayRef<SMLoc> WarningLoc, const Twine &Msg) {
PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
}
void PrintWarning(const char *Loc, const Twine &Msg) {
SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Warning, Msg);
}
void PrintWarning(const Twine &Msg) {
errs() << "warning:" << Msg << "\n";
}
void PrintError(ArrayRef<SMLoc> ErrorLoc, const Twine &Msg) {
PrintMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
}
void PrintError(const char *Loc, const Twine &Msg) {
SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
}
void PrintError(const Twine &Msg) {
errs() << "error:" << Msg << "\n";
}
void PrintFatalError(const Twine &Msg) {
PrintError(Msg);
// The following call runs the file cleanup handlers.
sys::RunInterruptHandlers();
std::exit(1);
}
void PrintFatalError(ArrayRef<SMLoc> ErrorLoc, const Twine &Msg) {
PrintError(ErrorLoc, Msg);
// The following call runs the file cleanup handlers.
sys::RunInterruptHandlers();
std::exit(1);
}
} // end namespace llvm
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/CMakeLists.txt | add_llvm_library(LLVMTableGen
Error.cpp
Main.cpp
Record.cpp
SetTheory.cpp
StringMatcher.cpp
TableGenBackend.cpp
TGLexer.cpp
TGParser.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/TableGen
)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/Record.cpp | //===- Record.cpp - Record implementation ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implement the tablegen record classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/Record.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/TableGen/Error.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// std::string wrapper for DenseMap purposes
//===----------------------------------------------------------------------===//
namespace llvm {
/// TableGenStringKey - This is a wrapper for std::string suitable for
/// using as a key to a DenseMap. Because there isn't a particularly
/// good way to indicate tombstone or empty keys for strings, we want
/// to wrap std::string to indicate that this is a "special" string
/// not expected to take on certain values (those of the tombstone and
/// empty keys). This makes things a little safer as it clarifies
/// that DenseMap is really not appropriate for general strings.
class TableGenStringKey {
public:
TableGenStringKey(const std::string &str) : data(str) {}
TableGenStringKey(const char *str) : data(str) {}
const std::string &str() const { return data; }
friend hash_code hash_value(const TableGenStringKey &Value) {
using llvm::hash_value;
return hash_value(Value.str());
}
private:
std::string data;
};
/// Specialize DenseMapInfo for TableGenStringKey.
template<> struct DenseMapInfo<TableGenStringKey> {
static inline TableGenStringKey getEmptyKey() {
TableGenStringKey Empty("<<<EMPTY KEY>>>");
return Empty;
}
static inline TableGenStringKey getTombstoneKey() {
TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
return Tombstone;
}
static unsigned getHashValue(const TableGenStringKey& Val) {
using llvm::hash_value;
return hash_value(Val);
}
static bool isEqual(const TableGenStringKey& LHS,
const TableGenStringKey& RHS) {
return LHS.str() == RHS.str();
}
};
} // namespace llvm
//===----------------------------------------------------------------------===//
// Type implementations
//===----------------------------------------------------------------------===//
BitRecTy BitRecTy::Shared;
IntRecTy IntRecTy::Shared;
StringRecTy StringRecTy::Shared;
DagRecTy DagRecTy::Shared;
void RecTy::dump() const { print(errs()); }
ListRecTy *RecTy::getListTy() {
if (!ListTy)
ListTy.reset(new ListRecTy(this));
return ListTy.get();
}
bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
assert(RHS && "NULL pointer");
return Kind == RHS->getRecTyKind();
}
bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
return true;
if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
return BitsTy->getNumBits() == 1;
return false;
}
BitsRecTy *BitsRecTy::get(unsigned Sz) {
static std::vector<std::unique_ptr<BitsRecTy>> Shared;
if (Sz >= Shared.size())
Shared.resize(Sz + 1);
std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
if (!Ty)
Ty.reset(new BitsRecTy(Sz));
return Ty.get();
}
std::string BitsRecTy::getAsString() const {
return "bits<" + utostr(Size) + ">";
}
bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
return cast<BitsRecTy>(RHS)->Size == Size;
RecTyKind kind = RHS->getRecTyKind();
return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
}
bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
RecTyKind kind = RHS->getRecTyKind();
return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
}
std::string StringRecTy::getAsString() const {
return "string";
}
std::string ListRecTy::getAsString() const {
return "list<" + Ty->getAsString() + ">";
}
bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
return Ty->typeIsConvertibleTo(ListTy->getElementType());
return false;
}
std::string DagRecTy::getAsString() const {
return "dag";
}
RecordRecTy *RecordRecTy::get(Record *R) {
return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
}
std::string RecordRecTy::getAsString() const {
return Rec->getName();
}
bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
if (!RTy)
return false;
if (RTy->getRecord() == Rec || Rec->isSubClassOf(RTy->getRecord()))
return true;
for (Record *SC : RTy->getRecord()->getSuperClasses())
if (Rec->isSubClassOf(SC))
return true;
return false;
}
/// resolveTypes - Find a common type that T1 and T2 convert to.
/// Return null if no such type exists.
///
RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
if (T1->typeIsConvertibleTo(T2))
return T2;
if (T2->typeIsConvertibleTo(T1))
return T1;
// If one is a Record type, check superclasses
if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
// See if T2 inherits from a type T1 also inherits from
for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
if (NewType1)
return NewType1;
}
}
if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
// See if T1 inherits from a type T2 also inherits from
for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
if (NewType2)
return NewType2;
}
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// Initializer implementations
//===----------------------------------------------------------------------===//
void Init::anchor() { }
void Init::dump() const { return print(errs()); }
UnsetInit *UnsetInit::get() {
static UnsetInit TheInit;
return &TheInit;
}
Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
SmallVector<Init *, 16> NewBits(BRT->getNumBits());
for (unsigned i = 0; i != BRT->getNumBits(); ++i)
NewBits[i] = UnsetInit::get();
return BitsInit::get(NewBits);
}
// All other types can just be returned.
return const_cast<UnsetInit *>(this);
}
BitInit *BitInit::get(bool V) {
static BitInit True(true);
static BitInit False(false);
return V ? &True : &False;
}
Init *BitInit::convertInitializerTo(RecTy *Ty) const {
if (isa<BitRecTy>(Ty))
return const_cast<BitInit *>(this);
if (isa<IntRecTy>(Ty))
return IntInit::get(getValue());
if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
// Can only convert single bit.
if (BRT->getNumBits() == 1)
return BitsInit::get(const_cast<BitInit *>(this));
}
return nullptr;
}
static void
ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
ID.AddInteger(Range.size());
for (Init *I : Range)
ID.AddPointer(I);
}
BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
static FoldingSet<BitsInit> ThePool;
static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
FoldingSetNodeID ID;
ProfileBitsInit(ID, Range);
void *IP = nullptr;
if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
return I;
BitsInit *I = new BitsInit(Range);
ThePool.InsertNode(I, IP);
TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
return I;
}
void BitsInit::Profile(FoldingSetNodeID &ID) const {
ProfileBitsInit(ID, Bits);
}
Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
if (isa<BitRecTy>(Ty)) {
if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
return getBit(0);
}
if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
// If the number of bits is right, return it. Otherwise we need to expand
// or truncate.
if (getNumBits() != BRT->getNumBits()) return nullptr;
return const_cast<BitsInit *>(this);
}
if (isa<IntRecTy>(Ty)) {
int64_t Result = 0;
for (unsigned i = 0, e = getNumBits(); i != e; ++i)
if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
Result |= static_cast<int64_t>(Bit->getValue()) << i;
else
return nullptr;
return IntInit::get(Result);
}
return nullptr;
}
Init *
BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
SmallVector<Init *, 16> NewBits(Bits.size());
for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
if (Bits[i] >= getNumBits())
return nullptr;
NewBits[i] = getBit(Bits[i]);
}
return BitsInit::get(NewBits);
}
std::string BitsInit::getAsString() const {
std::string Result = "{ ";
for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
if (i) Result += ", ";
if (Init *Bit = getBit(e-i-1))
Result += Bit->getAsString();
else
Result += "*";
}
return Result + " }";
}
// Fix bit initializer to preserve the behavior that bit reference from a unset
// bits initializer will resolve into VarBitInit to keep the field name and bit
// number used in targets with fixed insn length.
static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
if (RV || !isa<UnsetInit>(After))
return After;
return Before;
}
// resolveReferences - If there are any field references that refer to fields
// that have been filled in, we can propagate the values now.
//
Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
bool Changed = false;
SmallVector<Init *, 16> NewBits(getNumBits());
Init *CachedInit = nullptr;
Init *CachedBitVar = nullptr;
bool CachedBitVarChanged = false;
for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
Init *CurBit = Bits[i];
Init *CurBitVar = CurBit->getBitVar();
NewBits[i] = CurBit;
if (CurBitVar == CachedBitVar) {
if (CachedBitVarChanged) {
Init *Bit = CachedInit->getBit(CurBit->getBitNum());
NewBits[i] = fixBitInit(RV, CurBit, Bit);
}
continue;
}
CachedBitVar = CurBitVar;
CachedBitVarChanged = false;
Init *B;
do {
B = CurBitVar;
CurBitVar = CurBitVar->resolveReferences(R, RV);
CachedBitVarChanged |= B != CurBitVar;
Changed |= B != CurBitVar;
} while (B != CurBitVar);
CachedInit = CurBitVar;
if (CachedBitVarChanged) {
Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
NewBits[i] = fixBitInit(RV, CurBit, Bit);
}
}
if (Changed)
return BitsInit::get(NewBits);
return const_cast<BitsInit *>(this);
}
IntInit *IntInit::get(int64_t V) {
static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
std::unique_ptr<IntInit> &I = ThePool[V];
if (!I) I.reset(new IntInit(V));
return I.get();
}
std::string IntInit::getAsString() const {
return itostr(Value);
}
/// canFitInBitfield - Return true if the number of bits is large enough to hold
/// the integer value.
static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
// For example, with NumBits == 4, we permit Values from [-7 .. 15].
return (NumBits >= sizeof(Value) * 8) ||
(Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
}
Init *IntInit::convertInitializerTo(RecTy *Ty) const {
if (isa<IntRecTy>(Ty))
return const_cast<IntInit *>(this);
if (isa<BitRecTy>(Ty)) {
int64_t Val = getValue();
if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
return BitInit::get(Val != 0);
}
if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
int64_t Value = getValue();
// Make sure this bitfield is large enough to hold the integer value.
if (!canFitInBitfield(Value, BRT->getNumBits()))
return nullptr;
SmallVector<Init *, 16> NewBits(BRT->getNumBits());
for (unsigned i = 0; i != BRT->getNumBits(); ++i)
NewBits[i] = BitInit::get(Value & (1LL << i));
return BitsInit::get(NewBits);
}
return nullptr;
}
Init *
IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
SmallVector<Init *, 16> NewBits(Bits.size());
for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
if (Bits[i] >= 64)
return nullptr;
NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
}
return BitsInit::get(NewBits);
}
StringInit *StringInit::get(StringRef V) {
static StringMap<std::unique_ptr<StringInit>> ThePool;
std::unique_ptr<StringInit> &I = ThePool[V];
if (!I) I.reset(new StringInit(V));
return I.get();
}
Init *StringInit::convertInitializerTo(RecTy *Ty) const {
if (isa<StringRecTy>(Ty))
return const_cast<StringInit *>(this);
return nullptr;
}
static void ProfileListInit(FoldingSetNodeID &ID,
ArrayRef<Init *> Range,
RecTy *EltTy) {
ID.AddInteger(Range.size());
ID.AddPointer(EltTy);
for (Init *I : Range)
ID.AddPointer(I);
}
ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
static FoldingSet<ListInit> ThePool;
static std::vector<std::unique_ptr<ListInit>> TheActualPool;
FoldingSetNodeID ID;
ProfileListInit(ID, Range, EltTy);
void *IP = nullptr;
if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
return I;
ListInit *I = new ListInit(Range, EltTy);
ThePool.InsertNode(I, IP);
TheActualPool.push_back(std::unique_ptr<ListInit>(I));
return I;
}
void ListInit::Profile(FoldingSetNodeID &ID) const {
RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
ProfileListInit(ID, Values, EltTy);
}
Init *ListInit::convertInitializerTo(RecTy *Ty) const {
if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
std::vector<Init*> Elements;
// Verify that all of the elements of the list are subclasses of the
// appropriate class!
for (Init *I : getValues())
if (Init *CI = I->convertInitializerTo(LRT->getElementType()))
Elements.push_back(CI);
else
return nullptr;
if (isa<ListRecTy>(getType()))
return ListInit::get(Elements, Ty);
}
return nullptr;
}
Init *
ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
std::vector<Init*> Vals;
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
if (Elements[i] >= size())
return nullptr;
Vals.push_back(getElement(Elements[i]));
}
return ListInit::get(Vals, getType());
}
Record *ListInit::getElementAsRecord(unsigned i) const {
assert(i < Values.size() && "List element index out of range!");
DefInit *DI = dyn_cast<DefInit>(Values[i]);
if (!DI)
PrintFatalError("Expected record in list!");
return DI->getDef();
}
Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
std::vector<Init*> Resolved;
Resolved.reserve(size());
bool Changed = false;
for (Init *CurElt : getValues()) {
Init *E;
do {
E = CurElt;
CurElt = CurElt->resolveReferences(R, RV);
Changed |= E != CurElt;
} while (E != CurElt);
Resolved.push_back(E);
}
if (Changed)
return ListInit::get(Resolved, getType());
return const_cast<ListInit *>(this);
}
Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
unsigned Elt) const {
if (Elt >= size())
return nullptr; // Out of range reference.
Init *E = getElement(Elt);
// If the element is set to some value, or if we are resolving a reference
// to a specific variable and that variable is explicitly unset, then
// replace the VarListElementInit with it.
if (IRV || !isa<UnsetInit>(E))
return E;
return nullptr;
}
std::string ListInit::getAsString() const {
std::string Result = "[";
for (unsigned i = 0, e = Values.size(); i != e; ++i) {
if (i) Result += ", ";
Result += Values[i]->getAsString();
}
return Result + "]";
}
Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
unsigned Elt) const {
Init *Resolved = resolveReferences(R, IRV);
OpInit *OResolved = dyn_cast<OpInit>(Resolved);
if (OResolved) {
Resolved = OResolved->Fold(&R, nullptr);
}
if (Resolved != this) {
TypedInit *Typed = cast<TypedInit>(Resolved);
if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
return New;
return VarListElementInit::get(Typed, Elt);
}
return nullptr;
}
Init *OpInit::getBit(unsigned Bit) const {
if (getType() == BitRecTy::get())
return const_cast<OpInit*>(this);
return VarBitInit::get(const_cast<OpInit*>(this), Bit);
}
UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
if (!I) I.reset(new UnOpInit(opc, lhs, Type));
return I.get();
}
Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
switch (getOpcode()) {
case CAST: {
if (isa<StringRecTy>(getType())) {
if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
return LHSs;
if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
return StringInit::get(LHSd->getAsString());
if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
return StringInit::get(LHSi->getAsString());
} else {
if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
std::string Name = LHSs->getValue();
// From TGParser::ParseIDValue
if (CurRec) {
if (const RecordVal *RV = CurRec->getValue(Name)) {
if (RV->getType() != getType())
PrintFatalError("type mismatch in cast");
return VarInit::get(Name, RV->getType());
}
Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
":");
if (CurRec->isTemplateArg(TemplateArgName)) {
const RecordVal *RV = CurRec->getValue(TemplateArgName);
assert(RV && "Template arg doesn't exist??");
if (RV->getType() != getType())
PrintFatalError("type mismatch in cast");
return VarInit::get(TemplateArgName, RV->getType());
}
}
if (CurMultiClass) {
Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
"::");
if (CurMultiClass->Rec.isTemplateArg(MCName)) {
const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
assert(RV && "Template arg doesn't exist??");
if (RV->getType() != getType())
PrintFatalError("type mismatch in cast");
return VarInit::get(MCName, RV->getType());
}
}
assert(CurRec && "NULL pointer");
if (Record *D = (CurRec->getRecords()).getDef(Name))
return DefInit::get(D);
PrintFatalError(CurRec->getLoc(),
"Undefined reference:'" + Name + "'\n");
}
}
break;
}
case HEAD: {
if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
assert(!LHSl->empty() && "Empty list in head");
return LHSl->getElement(0);
}
break;
}
case TAIL: {
if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
assert(!LHSl->empty() && "Empty list in tail");
// Note the +1. We can't just pass the result of getValues()
// directly.
return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
}
break;
}
case EMPTY: {
if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
return IntInit::get(LHSl->empty());
if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
return IntInit::get(LHSs->getValue().empty());
break;
}
}
return const_cast<UnOpInit *>(this);
}
Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
Init *lhs = LHS->resolveReferences(R, RV);
if (LHS != lhs)
return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
return Fold(&R, nullptr);
}
std::string UnOpInit::getAsString() const {
std::string Result;
switch (Opc) {
case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
case HEAD: Result = "!head"; break;
case TAIL: Result = "!tail"; break;
case EMPTY: Result = "!empty"; break;
}
return Result + "(" + LHS->getAsString() + ")";
}
BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
Init *rhs, RecTy *Type) {
typedef std::pair<
std::pair<std::pair<unsigned, Init *>, Init *>,
RecTy *
> Key;
static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
Type));
std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
return I.get();
}
Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
switch (getOpcode()) {
case CONCAT: {
DagInit *LHSs = dyn_cast<DagInit>(LHS);
DagInit *RHSs = dyn_cast<DagInit>(RHS);
if (LHSs && RHSs) {
DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
PrintFatalError("Concated Dag operators do not match!");
std::vector<Init*> Args;
std::vector<std::string> ArgNames;
for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
Args.push_back(LHSs->getArg(i));
ArgNames.push_back(LHSs->getArgName(i));
}
for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
Args.push_back(RHSs->getArg(i));
ArgNames.push_back(RHSs->getArgName(i));
}
return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
}
break;
}
case LISTCONCAT: {
ListInit *LHSs = dyn_cast<ListInit>(LHS);
ListInit *RHSs = dyn_cast<ListInit>(RHS);
if (LHSs && RHSs) {
std::vector<Init *> Args;
Args.insert(Args.end(), LHSs->begin(), LHSs->end());
Args.insert(Args.end(), RHSs->begin(), RHSs->end());
return ListInit::get(
Args, cast<ListRecTy>(LHSs->getType())->getElementType());
}
break;
}
case STRCONCAT: {
StringInit *LHSs = dyn_cast<StringInit>(LHS);
StringInit *RHSs = dyn_cast<StringInit>(RHS);
if (LHSs && RHSs)
return StringInit::get(LHSs->getValue() + RHSs->getValue());
break;
}
case EQ: {
// try to fold eq comparison for 'bit' and 'int', otherwise fallback
// to string objects.
IntInit *L =
dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
IntInit *R =
dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
if (L && R)
return IntInit::get(L->getValue() == R->getValue());
StringInit *LHSs = dyn_cast<StringInit>(LHS);
StringInit *RHSs = dyn_cast<StringInit>(RHS);
// Make sure we've resolved
if (LHSs && RHSs)
return IntInit::get(LHSs->getValue() == RHSs->getValue());
break;
}
case ADD:
case AND:
case SHL:
case SRA:
case SRL: {
IntInit *LHSi =
dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
IntInit *RHSi =
dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
if (LHSi && RHSi) {
int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
int64_t Result;
switch (getOpcode()) {
default: llvm_unreachable("Bad opcode!");
case ADD: Result = LHSv + RHSv; break;
case AND: Result = LHSv & RHSv; break;
case SHL: Result = LHSv << RHSv; break;
case SRA: Result = LHSv >> RHSv; break;
case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
}
return IntInit::get(Result);
}
break;
}
}
return const_cast<BinOpInit *>(this);
}
Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
Init *lhs = LHS->resolveReferences(R, RV);
Init *rhs = RHS->resolveReferences(R, RV);
if (LHS != lhs || RHS != rhs)
return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
return Fold(&R, nullptr);
}
std::string BinOpInit::getAsString() const {
std::string Result;
switch (Opc) {
case CONCAT: Result = "!con"; break;
case ADD: Result = "!add"; break;
case AND: Result = "!and"; break;
case SHL: Result = "!shl"; break;
case SRA: Result = "!sra"; break;
case SRL: Result = "!srl"; break;
case EQ: Result = "!eq"; break;
case LISTCONCAT: Result = "!listconcat"; break;
case STRCONCAT: Result = "!strconcat"; break;
}
return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
}
TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
RecTy *Type) {
typedef std::pair<
std::pair<
std::pair<std::pair<unsigned, RecTy *>, Init *>,
Init *
>,
Init *
> Key;
static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
Type),
lhs),
mhs),
rhs));
std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
return I.get();
}
static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
Record *CurRec, MultiClass *CurMultiClass);
static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
RecTy *Type, Record *CurRec,
MultiClass *CurMultiClass) {
// If this is a dag, recurse
if (auto *TArg = dyn_cast<TypedInit>(Arg))
if (isa<DagRecTy>(TArg->getType()))
return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
std::vector<Init *> NewOperands;
for (unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
Type, CurRec, CurMultiClass))
NewOperands.push_back(Result);
else
NewOperands.push_back(Arg);
} else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
NewOperands.push_back(Arg);
} else {
NewOperands.push_back(RHSo->getOperand(i));
}
}
// Now run the operator and use its result as the new leaf
const OpInit *NewOp = RHSo->clone(NewOperands);
Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
return (NewVal != NewOp) ? NewVal : nullptr;
}
static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
Record *CurRec, MultiClass *CurMultiClass) {
OpInit *RHSo = dyn_cast<OpInit>(RHS);
if (!RHSo)
PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
if (!LHSt)
PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
DagInit *MHSd = dyn_cast<DagInit>(MHS);
if (MHSd && isa<DagRecTy>(Type)) {
Init *Val = MHSd->getOperator();
if (Init *Result = EvaluateOperation(RHSo, LHS, Val,
Type, CurRec, CurMultiClass))
Val = Result;
std::vector<std::pair<Init *, std::string> > args;
for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
Init *Arg = MHSd->getArg(i);
std::string ArgName = MHSd->getArgName(i);
// Process args
if (Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
CurRec, CurMultiClass))
Arg = Result;
// TODO: Process arg names
args.push_back(std::make_pair(Arg, ArgName));
}
return DagInit::get(Val, "", args);
}
ListInit *MHSl = dyn_cast<ListInit>(MHS);
if (MHSl && isa<ListRecTy>(Type)) {
std::vector<Init *> NewOperands;
std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
for (Init *&Item : NewList) {
NewOperands.clear();
for(unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
// First, replace the foreach variable with the list item
if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
NewOperands.push_back(Item);
else
NewOperands.push_back(RHSo->getOperand(i));
}
// Now run the operator and use its result as the new list item
const OpInit *NewOp = RHSo->clone(NewOperands);
Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
if (NewItem != NewOp)
Item = NewItem;
}
return ListInit::get(NewList, MHSl->getType());
}
return nullptr;
}
Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
switch (getOpcode()) {
case SUBST: {
DefInit *LHSd = dyn_cast<DefInit>(LHS);
VarInit *LHSv = dyn_cast<VarInit>(LHS);
StringInit *LHSs = dyn_cast<StringInit>(LHS);
DefInit *MHSd = dyn_cast<DefInit>(MHS);
VarInit *MHSv = dyn_cast<VarInit>(MHS);
StringInit *MHSs = dyn_cast<StringInit>(MHS);
DefInit *RHSd = dyn_cast<DefInit>(RHS);
VarInit *RHSv = dyn_cast<VarInit>(RHS);
StringInit *RHSs = dyn_cast<StringInit>(RHS);
if (LHSd && MHSd && RHSd) {
Record *Val = RHSd->getDef();
if (LHSd->getAsString() == RHSd->getAsString())
Val = MHSd->getDef();
return DefInit::get(Val);
}
if (LHSv && MHSv && RHSv) {
std::string Val = RHSv->getName();
if (LHSv->getAsString() == RHSv->getAsString())
Val = MHSv->getName();
return VarInit::get(Val, getType());
}
if (LHSs && MHSs && RHSs) {
std::string Val = RHSs->getValue();
std::string::size_type found;
std::string::size_type idx = 0;
while (true) {
found = Val.find(LHSs->getValue(), idx);
if (found == std::string::npos)
break;
Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
idx = found + MHSs->getValue().size();
}
return StringInit::get(Val);
}
break;
}
case FOREACH: {
if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
CurRec, CurMultiClass))
return Result;
break;
}
case IF: {
IntInit *LHSi = dyn_cast<IntInit>(LHS);
if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
LHSi = dyn_cast<IntInit>(I);
if (LHSi) {
if (LHSi->getValue())
return MHS;
return RHS;
}
break;
}
}
return const_cast<TernOpInit *>(this);
}
Init *TernOpInit::resolveReferences(Record &R,
const RecordVal *RV) const {
Init *lhs = LHS->resolveReferences(R, RV);
if (Opc == IF && lhs != LHS) {
IntInit *Value = dyn_cast<IntInit>(lhs);
if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
Value = dyn_cast<IntInit>(I);
if (Value) {
// Short-circuit
if (Value->getValue()) {
Init *mhs = MHS->resolveReferences(R, RV);
return (TernOpInit::get(getOpcode(), lhs, mhs,
RHS, getType()))->Fold(&R, nullptr);
}
Init *rhs = RHS->resolveReferences(R, RV);
return (TernOpInit::get(getOpcode(), lhs, MHS,
rhs, getType()))->Fold(&R, nullptr);
}
}
Init *mhs = MHS->resolveReferences(R, RV);
Init *rhs = RHS->resolveReferences(R, RV);
if (LHS != lhs || MHS != mhs || RHS != rhs)
return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
getType()))->Fold(&R, nullptr);
return Fold(&R, nullptr);
}
std::string TernOpInit::getAsString() const {
std::string Result;
switch (Opc) {
case SUBST: Result = "!subst"; break;
case FOREACH: Result = "!foreach"; break;
case IF: Result = "!if"; break;
}
return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
RHS->getAsString() + ")";
}
RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
return Field->getType();
return nullptr;
}
Init *
TypedInit::convertInitializerTo(RecTy *Ty) const {
if (isa<IntRecTy>(Ty)) {
if (getType()->typeIsConvertibleTo(Ty))
return const_cast<TypedInit *>(this);
return nullptr;
}
if (isa<StringRecTy>(Ty)) {
if (isa<StringRecTy>(getType()))
return const_cast<TypedInit *>(this);
return nullptr;
}
if (isa<BitRecTy>(Ty)) {
// Accept variable if it is already of bit type!
if (isa<BitRecTy>(getType()))
return const_cast<TypedInit *>(this);
if (auto *BitsTy = dyn_cast<BitsRecTy>(getType())) {
// Accept only bits<1> expression.
if (BitsTy->getNumBits() == 1)
return const_cast<TypedInit *>(this);
return nullptr;
}
// Ternary !if can be converted to bit, but only if both sides are
// convertible to a bit.
if (const auto *TOI = dyn_cast<TernOpInit>(this)) {
if (TOI->getOpcode() == TernOpInit::TernaryOp::IF &&
TOI->getMHS()->convertInitializerTo(BitRecTy::get()) &&
TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
return const_cast<TypedInit *>(this);
return nullptr;
}
return nullptr;
}
if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
if (BRT->getNumBits() == 1 && isa<BitRecTy>(getType()))
return BitsInit::get(const_cast<TypedInit *>(this));
if (getType()->typeIsConvertibleTo(BRT)) {
SmallVector<Init *, 16> NewBits(BRT->getNumBits());
for (unsigned i = 0; i != BRT->getNumBits(); ++i)
NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), i);
return BitsInit::get(NewBits);
}
return nullptr;
}
if (auto *DLRT = dyn_cast<ListRecTy>(Ty)) {
if (auto *SLRT = dyn_cast<ListRecTy>(getType()))
if (SLRT->getElementType()->typeIsConvertibleTo(DLRT->getElementType()))
return const_cast<TypedInit *>(this);
return nullptr;
}
if (auto *DRT = dyn_cast<DagRecTy>(Ty)) {
if (getType()->typeIsConvertibleTo(DRT))
return const_cast<TypedInit *>(this);
return nullptr;
}
if (auto *SRRT = dyn_cast<RecordRecTy>(Ty)) {
// Ensure that this is compatible with Rec.
if (RecordRecTy *DRRT = dyn_cast<RecordRecTy>(getType()))
if (DRRT->getRecord()->isSubClassOf(SRRT->getRecord()) ||
DRRT->getRecord() == SRRT->getRecord())
return const_cast<TypedInit *>(this);
return nullptr;
}
return nullptr;
}
Init *
TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
if (!T) return nullptr; // Cannot subscript a non-bits variable.
unsigned NumBits = T->getNumBits();
SmallVector<Init *, 16> NewBits(Bits.size());
for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
if (Bits[i] >= NumBits)
return nullptr;
NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
}
return BitsInit::get(NewBits);
}
Init *
TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
ListRecTy *T = dyn_cast<ListRecTy>(getType());
if (!T) return nullptr; // Cannot subscript a non-list variable.
if (Elements.size() == 1)
return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
std::vector<Init*> ListInits;
ListInits.reserve(Elements.size());
for (unsigned i = 0, e = Elements.size(); i != e; ++i)
ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
Elements[i]));
return ListInit::get(ListInits, T);
}
VarInit *VarInit::get(const std::string &VN, RecTy *T) {
Init *Value = StringInit::get(VN);
return VarInit::get(Value, T);
}
VarInit *VarInit::get(Init *VN, RecTy *T) {
typedef std::pair<RecTy *, Init *> Key;
static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
Key TheKey(std::make_pair(T, VN));
std::unique_ptr<VarInit> &I = ThePool[TheKey];
if (!I) I.reset(new VarInit(VN, T));
return I.get();
}
const std::string &VarInit::getName() const {
StringInit *NameString = cast<StringInit>(getNameInit());
return NameString->getValue();
}
Init *VarInit::getBit(unsigned Bit) const {
if (getType() == BitRecTy::get())
return const_cast<VarInit*>(this);
return VarBitInit::get(const_cast<VarInit*>(this), Bit);
}
Init *VarInit::resolveListElementReference(Record &R,
const RecordVal *IRV,
unsigned Elt) const {
if (R.isTemplateArg(getNameInit())) return nullptr;
if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
RecordVal *RV = R.getValue(getNameInit());
assert(RV && "Reference to a non-existent variable?");
ListInit *LI = dyn_cast<ListInit>(RV->getValue());
if (!LI)
return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
if (Elt >= LI->size())
return nullptr; // Out of range reference.
Init *E = LI->getElement(Elt);
// If the element is set to some value, or if we are resolving a reference
// to a specific variable and that variable is explicitly unset, then
// replace the VarListElementInit with it.
if (IRV || !isa<UnsetInit>(E))
return E;
return nullptr;
}
RecTy *VarInit::getFieldType(const std::string &FieldName) const {
if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
return RV->getType();
return nullptr;
}
Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
const std::string &FieldName) const {
if (isa<RecordRecTy>(getType()))
if (const RecordVal *Val = R.getValue(VarName)) {
if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
return nullptr;
Init *TheInit = Val->getValue();
assert(TheInit != this && "Infinite loop detected!");
if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
return I;
return nullptr;
}
return nullptr;
}
/// resolveReferences - This method is used by classes that refer to other
/// variables which may not be defined at the time the expression is formed.
/// If a value is set for the variable later, this method will be called on
/// users of the value to allow the value to propagate out.
///
Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
if (RecordVal *Val = R.getValue(VarName))
if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
return Val->getValue();
return const_cast<VarInit *>(this);
}
VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
typedef std::pair<TypedInit *, unsigned> Key;
static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
Key TheKey(std::make_pair(T, B));
std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
if (!I) I.reset(new VarBitInit(T, B));
return I.get();
}
Init *VarBitInit::convertInitializerTo(RecTy *Ty) const {
if (isa<BitRecTy>(Ty))
return const_cast<VarBitInit *>(this);
return nullptr;
}
std::string VarBitInit::getAsString() const {
return TI->getAsString() + "{" + utostr(Bit) + "}";
}
Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
Init *I = TI->resolveReferences(R, RV);
if (TI != I)
return I->getBit(getBitNum());
return const_cast<VarBitInit*>(this);
}
VarListElementInit *VarListElementInit::get(TypedInit *T,
unsigned E) {
typedef std::pair<TypedInit *, unsigned> Key;
static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
Key TheKey(std::make_pair(T, E));
std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
if (!I) I.reset(new VarListElementInit(T, E));
return I.get();
}
std::string VarListElementInit::getAsString() const {
return TI->getAsString() + "[" + utostr(Element) + "]";
}
Init *
VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
if (Init *I = getVariable()->resolveListElementReference(R, RV,
getElementNum()))
return I;
return const_cast<VarListElementInit *>(this);
}
Init *VarListElementInit::getBit(unsigned Bit) const {
if (getType() == BitRecTy::get())
return const_cast<VarListElementInit*>(this);
return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
}
Init *VarListElementInit:: resolveListElementReference(Record &R,
const RecordVal *RV,
unsigned Elt) const {
if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
if (Init *Result2 = TInit->resolveListElementReference(R, RV, Elt))
return Result2;
return VarListElementInit::get(TInit, Elt);
}
return Result;
}
return nullptr;
}
DefInit *DefInit::get(Record *R) {
return R->getDefInit();
}
Init *DefInit::convertInitializerTo(RecTy *Ty) const {
if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
if (getDef()->isSubClassOf(RRT->getRecord()))
return const_cast<DefInit *>(this);
return nullptr;
}
RecTy *DefInit::getFieldType(const std::string &FieldName) const {
if (const RecordVal *RV = Def->getValue(FieldName))
return RV->getType();
return nullptr;
}
Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
const std::string &FieldName) const {
return Def->getValue(FieldName)->getValue();
}
std::string DefInit::getAsString() const {
return Def->getName();
}
FieldInit *FieldInit::get(Init *R, const std::string &FN) {
typedef std::pair<Init *, TableGenStringKey> Key;
static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
Key TheKey(std::make_pair(R, FN));
std::unique_ptr<FieldInit> &I = ThePool[TheKey];
if (!I) I.reset(new FieldInit(R, FN));
return I.get();
}
Init *FieldInit::getBit(unsigned Bit) const {
if (getType() == BitRecTy::get())
return const_cast<FieldInit*>(this);
return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
}
Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
unsigned Elt) const {
if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
if (Elt >= LI->size()) return nullptr;
Init *E = LI->getElement(Elt);
// If the element is set to some value, or if we are resolving a
// reference to a specific variable and that variable is explicitly
// unset, then replace the VarListElementInit with it.
if (RV || !isa<UnsetInit>(E))
return E;
}
return nullptr;
}
Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
Init *BVR = BitsVal->resolveReferences(R, RV);
return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
}
if (NewRec != Rec)
return FieldInit::get(NewRec, FieldName);
return const_cast<FieldInit *>(this);
}
static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
ArrayRef<Init *> ArgRange,
ArrayRef<std::string> NameRange) {
ID.AddPointer(V);
ID.AddString(VN);
ArrayRef<Init *>::iterator Arg = ArgRange.begin();
ArrayRef<std::string>::iterator Name = NameRange.begin();
while (Arg != ArgRange.end()) {
assert(Name != NameRange.end() && "Arg name underflow!");
ID.AddPointer(*Arg++);
ID.AddString(*Name++);
}
assert(Name == NameRange.end() && "Arg name overflow!");
}
DagInit *
DagInit::get(Init *V, const std::string &VN,
ArrayRef<Init *> ArgRange,
ArrayRef<std::string> NameRange) {
static FoldingSet<DagInit> ThePool;
static std::vector<std::unique_ptr<DagInit>> TheActualPool;
FoldingSetNodeID ID;
ProfileDagInit(ID, V, VN, ArgRange, NameRange);
void *IP = nullptr;
if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
return I;
DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
ThePool.InsertNode(I, IP);
TheActualPool.push_back(std::unique_ptr<DagInit>(I));
return I;
}
DagInit *
DagInit::get(Init *V, const std::string &VN,
const std::vector<std::pair<Init*, std::string> > &args) {
std::vector<Init *> Args;
std::vector<std::string> Names;
for (const auto &Arg : args) {
Args.push_back(Arg.first);
Names.push_back(Arg.second);
}
return DagInit::get(V, VN, Args, Names);
}
void DagInit::Profile(FoldingSetNodeID &ID) const {
ProfileDagInit(ID, Val, ValName, Args, ArgNames);
}
Init *DagInit::convertInitializerTo(RecTy *Ty) const {
if (isa<DagRecTy>(Ty))
return const_cast<DagInit *>(this);
return nullptr;
}
Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
std::vector<Init*> NewArgs;
for (unsigned i = 0, e = Args.size(); i != e; ++i)
NewArgs.push_back(Args[i]->resolveReferences(R, RV));
Init *Op = Val->resolveReferences(R, RV);
if (Args != NewArgs || Op != Val)
return DagInit::get(Op, ValName, NewArgs, ArgNames);
return const_cast<DagInit *>(this);
}
std::string DagInit::getAsString() const {
std::string Result = "(" + Val->getAsString();
if (!ValName.empty())
Result += ":" + ValName;
if (!Args.empty()) {
Result += " " + Args[0]->getAsString();
if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
Result += ", " + Args[i]->getAsString();
if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
}
}
return Result + ")";
}
//===----------------------------------------------------------------------===//
// Other implementations
//===----------------------------------------------------------------------===//
RecordVal::RecordVal(Init *N, RecTy *T, bool P)
: NameAndPrefix(N, P), Ty(T) {
Value = UnsetInit::get()->convertInitializerTo(Ty);
assert(Value && "Cannot create unset value for current type!");
}
RecordVal::RecordVal(const std::string &N, RecTy *T, bool P)
: NameAndPrefix(StringInit::get(N), P), Ty(T) {
Value = UnsetInit::get()->convertInitializerTo(Ty);
assert(Value && "Cannot create unset value for current type!");
}
const std::string &RecordVal::getName() const {
return cast<StringInit>(getNameInit())->getValue();
}
void RecordVal::dump() const { errs() << *this; }
void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
if (getPrefix()) OS << "field ";
OS << *getType() << " " << getNameInitAsString();
if (getValue())
OS << " = " << *getValue();
if (PrintSem) OS << ";\n";
}
unsigned Record::LastID = 0;
void Record::init() {
checkName();
// Every record potentially has a def at the top. This value is
// replaced with the top-level def name at instantiation time.
RecordVal DN("NAME", StringRecTy::get(), 0);
addValue(DN);
}
void Record::checkName() {
// Ensure the record name has string type.
const TypedInit *TypedName = cast<const TypedInit>(Name);
if (!isa<StringRecTy>(TypedName->getType()))
PrintFatalError(getLoc(), "Record name is not a string!");
}
DefInit *Record::getDefInit() {
if (!TheInit)
TheInit.reset(new DefInit(this, new RecordRecTy(this)));
return TheInit.get();
}
const std::string &Record::getName() const {
return cast<StringInit>(Name)->getValue();
}
void Record::setName(Init *NewName) {
Name = NewName;
checkName();
// DO NOT resolve record values to the name at this point because
// there might be default values for arguments of this def. Those
// arguments might not have been resolved yet so we don't want to
// prematurely assume values for those arguments were not passed to
// this def.
//
// Nonetheless, it may be that some of this Record's values
// reference the record name. Indeed, the reason for having the
// record name be an Init is to provide this flexibility. The extra
// resolve steps after completely instantiating defs takes care of
// this. See TGParser::ParseDef and TGParser::ParseDefm.
}
void Record::setName(const std::string &Name) {
setName(StringInit::get(Name));
}
/// resolveReferencesTo - If anything in this record refers to RV, replace the
/// reference to RV with the RHS of RV. If RV is null, we resolve all possible
/// references.
void Record::resolveReferencesTo(const RecordVal *RV) {
for (unsigned i = 0, e = Values.size(); i != e; ++i) {
if (RV == &Values[i]) // Skip resolve the same field as the given one
continue;
if (Init *V = Values[i].getValue())
if (Values[i].setValue(V->resolveReferences(*this, RV)))
PrintFatalError(getLoc(), "Invalid value is found when setting '" +
Values[i].getNameInitAsString() +
"' after resolving references" +
(RV ? " against '" + RV->getNameInitAsString() +
"' of (" + RV->getValue()->getAsUnquotedString() +
")"
: "") + "\n");
}
Init *OldName = getNameInit();
Init *NewName = Name->resolveReferences(*this, RV);
if (NewName != OldName) {
// Re-register with RecordKeeper.
setName(NewName);
}
}
void Record::dump() const { errs() << *this; }
raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
OS << R.getNameInitAsString();
const std::vector<Init *> &TArgs = R.getTemplateArgs();
if (!TArgs.empty()) {
OS << "<";
bool NeedComma = false;
for (const Init *TA : TArgs) {
if (NeedComma) OS << ", ";
NeedComma = true;
const RecordVal *RV = R.getValue(TA);
assert(RV && "Template argument record not found??");
RV->print(OS, false);
}
OS << ">";
}
OS << " {";
ArrayRef<Record *> SC = R.getSuperClasses();
if (!SC.empty()) {
OS << "\t//";
for (const Record *Super : SC)
OS << " " << Super->getNameInitAsString();
}
OS << "\n";
for (const RecordVal &Val : R.getValues())
if (Val.getPrefix() && !R.isTemplateArg(Val.getName()))
OS << Val;
for (const RecordVal &Val : R.getValues())
if (!Val.getPrefix() && !R.isTemplateArg(Val.getName()))
OS << Val;
return OS << "}\n";
}
/// getValueInit - Return the initializer for a value with the specified name,
/// or abort if the field does not exist.
///
Init *Record::getValueInit(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
return R->getValue();
}
/// getValueAsString - This method looks up the specified field and returns its
/// value as a string, aborts if the field does not exist or if
/// the value is not a string.
///
std::string Record::getValueAsString(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
return SI->getValue();
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a string initializer!");
}
/// getValueAsBitsInit - This method looks up the specified field and returns
/// its value as a BitsInit, aborts if the field does not exist or if
/// the value is not the right type.
///
BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
return BI;
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a BitsInit initializer!");
}
/// getValueAsListInit - This method looks up the specified field and returns
/// its value as a ListInit, aborting if the field does not exist or if
/// the value is not the right type.
///
ListInit *Record::getValueAsListInit(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
return LI;
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a list initializer!");
}
/// getValueAsListOfDefs - This method looks up the specified field and returns
/// its value as a vector of records, aborting if the field does not exist
/// or if the value is not the right type.
///
std::vector<Record*>
Record::getValueAsListOfDefs(StringRef FieldName) const {
ListInit *List = getValueAsListInit(FieldName);
std::vector<Record*> Defs;
for (Init *I : List->getValues()) {
if (DefInit *DI = dyn_cast<DefInit>(I))
Defs.push_back(DI->getDef());
else
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' list is not entirely DefInit!");
}
return Defs;
}
/// getValueAsInt - This method looks up the specified field and returns its
/// value as an int64_t, aborting if the field does not exist or if the value
/// is not the right type.
///
int64_t Record::getValueAsInt(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
return II->getValue();
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have an int initializer!");
}
/// getValueAsListOfInts - This method looks up the specified field and returns
/// its value as a vector of integers, aborting if the field does not exist or
/// if the value is not the right type.
///
std::vector<int64_t>
Record::getValueAsListOfInts(StringRef FieldName) const {
ListInit *List = getValueAsListInit(FieldName);
std::vector<int64_t> Ints;
for (Init *I : List->getValues()) {
if (IntInit *II = dyn_cast<IntInit>(I))
Ints.push_back(II->getValue());
else
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a list of ints initializer!");
}
return Ints;
}
/// getValueAsListOfStrings - This method looks up the specified field and
/// returns its value as a vector of strings, aborting if the field does not
/// exist or if the value is not the right type.
///
std::vector<std::string>
Record::getValueAsListOfStrings(StringRef FieldName) const {
ListInit *List = getValueAsListInit(FieldName);
std::vector<std::string> Strings;
for (Init *I : List->getValues()) {
if (StringInit *SI = dyn_cast<StringInit>(I))
Strings.push_back(SI->getValue());
else
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a list of strings initializer!");
}
return Strings;
}
/// getValueAsDef - This method looks up the specified field and returns its
/// value as a Record, aborting if the field does not exist or if the value
/// is not the right type.
///
Record *Record::getValueAsDef(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
return DI->getDef();
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a def initializer!");
}
/// getValueAsBit - This method looks up the specified field and returns its
/// value as a bit, aborting if the field does not exist or if the value is
/// not the right type.
///
bool Record::getValueAsBit(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
return BI->getValue();
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a bit initializer!");
}
bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName.str() + "'!\n");
if (isa<UnsetInit>(R->getValue())) {
Unset = true;
return false;
}
Unset = false;
if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
return BI->getValue();
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a bit initializer!");
}
/// getValueAsDag - This method looks up the specified field and returns its
/// value as an Dag, aborting if the field does not exist or if the value is
/// not the right type.
///
DagInit *Record::getValueAsDag(StringRef FieldName) const {
const RecordVal *R = getValue(FieldName);
if (!R || !R->getValue())
PrintFatalError(getLoc(), "Record `" + getName() +
"' does not have a field named `" + FieldName + "'!\n");
if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
return DI;
PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
FieldName + "' does not have a dag initializer!");
}
void MultiClass::dump() const {
errs() << "Record:\n";
Rec.dump();
errs() << "Defs:\n";
for (const auto &Proto : DefPrototypes)
Proto->dump();
}
void RecordKeeper::dump() const { errs() << *this; }
raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
OS << "------------- Classes -----------------\n";
for (const auto &C : RK.getClasses())
OS << "class " << *C.second;
OS << "------------- Defs -----------------\n";
for (const auto &D : RK.getDefs())
OS << "def " << *D.second;
return OS;
}
/// getAllDerivedDefinitions - This method returns all concrete definitions
/// that derive from the specified class name. If a class with the specified
/// name does not exist, an error is printed and true is returned.
std::vector<Record*>
RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
Record *Class = getClass(ClassName);
if (!Class)
PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
std::vector<Record*> Defs;
for (const auto &D : getDefs())
if (D.second->isSubClassOf(Class))
Defs.push_back(D.second.get());
return Defs;
}
/// QualifyName - Return an Init with a qualifier prefix referring
/// to CurRec's name.
Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
Init *Name, const std::string &Scoper) {
RecTy *Type = cast<TypedInit>(Name)->getType();
BinOpInit *NewName =
BinOpInit::get(BinOpInit::STRCONCAT,
BinOpInit::get(BinOpInit::STRCONCAT,
CurRec.getNameInit(),
StringInit::get(Scoper),
Type)->Fold(&CurRec, CurMultiClass),
Name,
Type);
if (CurMultiClass && Scoper != "::") {
NewName =
BinOpInit::get(BinOpInit::STRCONCAT,
BinOpInit::get(BinOpInit::STRCONCAT,
CurMultiClass->Rec.getNameInit(),
StringInit::get("::"),
Type)->Fold(&CurRec, CurMultiClass),
NewName->Fold(&CurRec, CurMultiClass),
Type);
}
return NewName->Fold(&CurRec, CurMultiClass);
}
/// QualifyName - Return an Init with a qualifier prefix referring
/// to CurRec's name.
Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
const std::string &Name,
const std::string &Scoper) {
return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/LLVMBuild.txt | ;===- ./lib/TableGen/LLVMBuild.txt -----------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = TableGen
parent = Libraries
required_libraries = Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/Main.cpp | //===- Main.cpp - Top-Level TableGen implementation -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TableGen is a tool which can be used to build up a description of something,
// then invoke one or more "tablegen backends" to emit information about the
// description in some predefined format. In practice, this is used by the LLVM
// code generators to automate generation of a code generator through a
// high-level description of the target.
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/Main.h"
#include "TGParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <algorithm>
#include <cstdio>
#include <system_error>
using namespace llvm;
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
cl::init("-"));
static cl::opt<std::string>
DependFilename("d",
cl::desc("Dependency filename"),
cl::value_desc("filename"),
cl::init(""));
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
static cl::list<std::string>
IncludeDirs("I", cl::desc("Directory of include files"),
cl::value_desc("directory"), cl::Prefix);
/// \brief Create a dependency file for `-d` option.
///
/// This functionality is really only for the benefit of the build system.
/// It is similar to GCC's `-M*` family of options.
static int createDependencyFile(const TGParser &Parser, const char *argv0) {
if (OutputFilename == "-") {
errs() << argv0 << ": the option -d must be used together with -o\n";
return 1;
}
std::error_code EC;
tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text);
if (EC) {
errs() << argv0 << ": error opening " << DependFilename << ":"
<< EC.message() << "\n";
return 1;
}
DepOut.os() << OutputFilename << ":";
for (const auto &Dep : Parser.getDependencies()) {
DepOut.os() << ' ' << Dep.first;
}
DepOut.os() << "\n";
DepOut.keep();
return 0;
}
int llvm::TableGenMain(char *argv0, TableGenMainFn *MainFn) {
RecordKeeper Records;
// HLSL Change Starts
struct SrcMgrCleanup {
~SrcMgrCleanup() {
SrcMgr.Reset();
}
};
SrcMgrCleanup SrcMgrCleanupInstance;
// HLSL Change Ends
// Parse the input file.
ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = FileOrErr.getError()) {
errs() << "Could not open input file '" << InputFilename
<< "': " << EC.message() << "\n";
return 1;
}
// Tell SrcMgr about this buffer, which is what TGParser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
// Record the location of the include directory so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(IncludeDirs);
TGParser Parser(SrcMgr, Records);
if (Parser.ParseFile())
return 1;
std::error_code EC;
tool_output_file Out(OutputFilename, EC, sys::fs::F_Text);
if (EC) {
errs() << argv0 << ": error opening " << OutputFilename << ":"
<< EC.message() << "\n";
return 1;
}
if (!DependFilename.empty()) {
if (int Ret = createDependencyFile(Parser, argv0))
return Ret;
}
if (MainFn(Out.os(), Records))
return 1;
if (ErrorsPrinted > 0) {
errs() << argv0 << ": " << ErrorsPrinted << " errors.\n";
return 1;
}
// Declare success.
Out.keep();
return 0;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/module.modulemap | module TableGen { requires cplusplus umbrella "." module * { export * } }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/TGLexer.cpp | //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implement the Lexer for TableGen.
//
//===----------------------------------------------------------------------===//
#include "TGLexer.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h" // for strtoull()/strtoll() define
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/TableGen/Error.h"
#include <cctype>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace llvm;
TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) {
CurBuffer = SrcMgr.getMainFileID();
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = CurBuf.begin();
TokStart = nullptr;
}
SMLoc TGLexer::getLoc() const {
return SMLoc::getFromPointer(TokStart);
}
/// ReturnError - Set the error to the specified string at the specified
/// location. This is defined to always return tgtok::Error.
tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
PrintError(Loc, Msg);
return tgtok::Error;
}
int TGLexer::getNextChar() {
char CurChar = *CurPtr++;
switch (CurChar) {
default:
return (unsigned char)CurChar;
case 0: {
// A nul character in the stream is either the end of the current buffer or
// a random nul in the file. Disambiguate that here.
if (CurPtr-1 != CurBuf.end())
return 0; // Just whitespace.
// If this is the end of an included file, pop the parent file off the
// include stack.
SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
if (ParentIncludeLoc != SMLoc()) {
CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = ParentIncludeLoc.getPointer();
return getNextChar();
}
// Otherwise, return end of file.
--CurPtr; // Another call to lex will return EOF again.
return EOF;
}
case '\n':
case '\r':
// Handle the newline character by ignoring it and incrementing the line
// count. However, be careful about 'dos style' files with \n\r in them.
// Only treat a \n\r or \r\n as a single line.
if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
*CurPtr != CurChar)
++CurPtr; // Eat the two char newline sequence.
return '\n';
}
}
int TGLexer::peekNextChar(int Index) {
return *(CurPtr + Index);
}
tgtok::TokKind TGLexer::LexToken() {
TokStart = CurPtr;
// This always consumes at least one character.
int CurChar = getNextChar();
switch (CurChar) {
default:
// Handle letters: [a-zA-Z_]
if (isalpha(CurChar) || CurChar == '_')
return LexIdentifier();
// Unknown character, emit an error.
return ReturnError(TokStart, "Unexpected character");
case EOF: return tgtok::Eof;
case ':': return tgtok::colon;
case ';': return tgtok::semi;
case '.': return tgtok::period;
case ',': return tgtok::comma;
case '<': return tgtok::less;
case '>': return tgtok::greater;
case ']': return tgtok::r_square;
case '{': return tgtok::l_brace;
case '}': return tgtok::r_brace;
case '(': return tgtok::l_paren;
case ')': return tgtok::r_paren;
case '=': return tgtok::equal;
case '?': return tgtok::question;
case '#': return tgtok::paste;
case 0:
case ' ':
case '\t':
case '\n':
case '\r':
// Ignore whitespace.
return LexToken();
case '/':
// If this is the start of a // comment, skip until the end of the line or
// the end of the buffer.
if (*CurPtr == '/')
SkipBCPLComment();
else if (*CurPtr == '*') {
if (SkipCComment())
return tgtok::Error;
} else // Otherwise, this is an error.
return ReturnError(TokStart, "Unexpected character");
return LexToken();
case '-': case '+':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9': {
int NextChar = 0;
if (isdigit(CurChar)) {
// Allow identifiers to start with a number if it is followed by
// an identifier. This can happen with paste operations like
// foo#8i.
int i = 0;
do {
NextChar = peekNextChar(i++);
} while (isdigit(NextChar));
if (NextChar == 'x' || NextChar == 'b') {
// If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
// likely a number.
int NextNextChar = peekNextChar(i);
switch (NextNextChar) {
default:
break;
case '0': case '1':
if (NextChar == 'b')
return LexNumber();
LLVM_FALLTHROUGH; // HLSL Change
case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
if (NextChar == 'x')
return LexNumber();
break;
}
}
}
if (isalpha(NextChar) || NextChar == '_')
return LexIdentifier();
return LexNumber();
}
case '"': return LexString();
case '$': return LexVarName();
case '[': return LexBracket();
case '!': return LexExclaim();
}
}
/// LexString - Lex "[^"]*"
tgtok::TokKind TGLexer::LexString() {
const char *StrStart = CurPtr;
CurStrVal = "";
while (*CurPtr != '"') {
// If we hit the end of the buffer, report an error.
if (*CurPtr == 0 && CurPtr == CurBuf.end())
return ReturnError(StrStart, "End of file in string literal");
if (*CurPtr == '\n' || *CurPtr == '\r')
return ReturnError(StrStart, "End of line in string literal");
if (*CurPtr != '\\') {
CurStrVal += *CurPtr++;
continue;
}
++CurPtr;
switch (*CurPtr) {
case '\\': case '\'': case '"':
// These turn into their literal character.
CurStrVal += *CurPtr++;
break;
case 't':
CurStrVal += '\t';
++CurPtr;
break;
case 'n':
CurStrVal += '\n';
++CurPtr;
break;
case '\n':
case '\r':
return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
// If we hit the end of the buffer, report an error.
case '\0':
if (CurPtr == CurBuf.end())
return ReturnError(StrStart, "End of file in string literal");
LLVM_FALLTHROUGH; // HLSL Change
default:
return ReturnError(CurPtr, "invalid escape in string literal");
}
}
++CurPtr;
return tgtok::StrVal;
}
tgtok::TokKind TGLexer::LexVarName() {
if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
return ReturnError(TokStart, "Invalid variable name");
// Otherwise, we're ok, consume the rest of the characters.
const char *VarNameStart = CurPtr++;
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
CurStrVal.assign(VarNameStart, CurPtr);
return tgtok::VarName;
}
tgtok::TokKind TGLexer::LexIdentifier() {
// The first letter is [a-zA-Z_#].
const char *IdentStart = TokStart;
// Match the rest of the identifier regex: [0-9a-zA-Z_#]*
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
// Check to see if this identifier is a keyword.
StringRef Str(IdentStart, CurPtr-IdentStart);
if (Str == "include") {
if (LexInclude()) return tgtok::Error;
return Lex();
}
tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str)
.Case("int", tgtok::Int)
.Case("bit", tgtok::Bit)
.Case("bits", tgtok::Bits)
.Case("string", tgtok::String)
.Case("list", tgtok::List)
.Case("code", tgtok::Code)
.Case("dag", tgtok::Dag)
.Case("class", tgtok::Class)
.Case("def", tgtok::Def)
.Case("foreach", tgtok::Foreach)
.Case("defm", tgtok::Defm)
.Case("multiclass", tgtok::MultiClass)
.Case("field", tgtok::Field)
.Case("let", tgtok::Let)
.Case("in", tgtok::In)
.Default(tgtok::Id);
if (Kind == tgtok::Id)
CurStrVal.assign(Str.begin(), Str.end());
return Kind;
}
/// LexInclude - We just read the "include" token. Get the string token that
/// comes next and enter the include.
bool TGLexer::LexInclude() {
// The token after the include must be a string.
tgtok::TokKind Tok = LexToken();
if (Tok == tgtok::Error) return true;
if (Tok != tgtok::StrVal) {
PrintError(getLoc(), "Expected filename after include");
return true;
}
// Get the string.
std::string Filename = CurStrVal;
std::string IncludedFile;
CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
IncludedFile);
if (!CurBuffer) {
PrintError(getLoc(), "Could not find include file '" + Filename + "'");
return true;
}
DependenciesMapTy::const_iterator Found = Dependencies.find(IncludedFile);
if (Found != Dependencies.end()) {
PrintError(getLoc(),
"File '" + IncludedFile + "' has already been included.");
SrcMgr.PrintMessage(Found->second, SourceMgr::DK_Note,
"previously included here");
return true;
}
Dependencies.insert(std::make_pair(IncludedFile, getLoc()));
// Save the line number and lex buffer of the includer.
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = CurBuf.begin();
return false;
}
void TGLexer::SkipBCPLComment() {
++CurPtr; // skip the second slash.
while (1) {
switch (*CurPtr) {
case '\n':
case '\r':
return; // Newline is end of comment.
case 0:
// If this is the end of the buffer, end the comment.
if (CurPtr == CurBuf.end())
return;
break;
}
// Otherwise, skip the character.
++CurPtr;
}
}
/// SkipCComment - This skips C-style /**/ comments. The only difference from C
/// is that we allow nesting.
bool TGLexer::SkipCComment() {
++CurPtr; // skip the star.
unsigned CommentDepth = 1;
while (1) {
int CurChar = getNextChar();
switch (CurChar) {
case EOF:
PrintError(TokStart, "Unterminated comment!");
return true;
case '*':
// End of the comment?
if (CurPtr[0] != '/') break;
++CurPtr; // End the */.
if (--CommentDepth == 0)
return false;
break;
case '/':
// Start of a nested comment?
if (CurPtr[0] != '*') break;
++CurPtr;
++CommentDepth;
break;
}
}
}
/// LexNumber - Lex:
/// [-+]?[0-9]+
/// 0x[0-9a-fA-F]+
/// 0b[01]+
tgtok::TokKind TGLexer::LexNumber() {
if (CurPtr[-1] == '0') {
if (CurPtr[0] == 'x') {
++CurPtr;
const char *NumStart = CurPtr;
while (isxdigit(CurPtr[0]))
++CurPtr;
// Requires at least one hex digit.
if (CurPtr == NumStart)
return ReturnError(TokStart, "Invalid hexadecimal number");
errno = 0;
CurIntVal = strtoll(NumStart, nullptr, 16);
if (errno == EINVAL)
return ReturnError(TokStart, "Invalid hexadecimal number");
if (errno == ERANGE) {
errno = 0;
CurIntVal = (int64_t)strtoull(NumStart, nullptr, 16);
if (errno == EINVAL)
return ReturnError(TokStart, "Invalid hexadecimal number");
if (errno == ERANGE)
return ReturnError(TokStart, "Hexadecimal number out of range");
}
return tgtok::IntVal;
} else if (CurPtr[0] == 'b') {
++CurPtr;
const char *NumStart = CurPtr;
while (CurPtr[0] == '0' || CurPtr[0] == '1')
++CurPtr;
// Requires at least one binary digit.
if (CurPtr == NumStart)
return ReturnError(CurPtr-2, "Invalid binary number");
CurIntVal = strtoll(NumStart, nullptr, 2);
return tgtok::BinaryIntVal;
}
}
// Check for a sign without a digit.
if (!isdigit(CurPtr[0])) {
if (CurPtr[-1] == '-')
return tgtok::minus;
else if (CurPtr[-1] == '+')
return tgtok::plus;
}
while (isdigit(CurPtr[0]))
++CurPtr;
CurIntVal = strtoll(TokStart, nullptr, 10);
return tgtok::IntVal;
}
/// LexBracket - We just read '['. If this is a code block, return it,
/// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
tgtok::TokKind TGLexer::LexBracket() {
if (CurPtr[0] != '{')
return tgtok::l_square;
++CurPtr;
const char *CodeStart = CurPtr;
while (1) {
int Char = getNextChar();
if (Char == EOF) break;
if (Char != '}') continue;
Char = getNextChar();
if (Char == EOF) break;
if (Char == ']') {
CurStrVal.assign(CodeStart, CurPtr-2);
return tgtok::CodeFragment;
}
}
return ReturnError(CodeStart-2, "Unterminated Code Block");
}
/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
tgtok::TokKind TGLexer::LexExclaim() {
if (!isalpha(*CurPtr))
return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
const char *Start = CurPtr++;
while (isalpha(*CurPtr))
++CurPtr;
// Check to see which operator this is.
tgtok::TokKind Kind =
StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
.Case("eq", tgtok::XEq)
.Case("if", tgtok::XIf)
.Case("head", tgtok::XHead)
.Case("tail", tgtok::XTail)
.Case("con", tgtok::XConcat)
.Case("add", tgtok::XADD)
.Case("and", tgtok::XAND)
.Case("shl", tgtok::XSHL)
.Case("sra", tgtok::XSRA)
.Case("srl", tgtok::XSRL)
.Case("cast", tgtok::XCast)
.Case("empty", tgtok::XEmpty)
.Case("subst", tgtok::XSubst)
.Case("foreach", tgtok::XForEach)
.Case("listconcat", tgtok::XListConcat)
.Case("strconcat", tgtok::XStrConcat)
.Default(tgtok::Error);
return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/StringMatcher.cpp | //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the StringMatcher class.
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
/// FindFirstNonCommonLetter - Find the first character in the keys of the
/// string pairs that is not shared across the whole set of strings. All
/// strings are assumed to have the same length.
static unsigned
FindFirstNonCommonLetter(const std::vector<const
StringMatcher::StringPair*> &Matches) {
assert(!Matches.empty());
for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
// Check to see if letter i is the same across the set.
char Letter = Matches[0]->first[i];
for (unsigned str = 0, e = Matches.size(); str != e; ++str)
if (Matches[str]->first[i] != Letter)
return i;
}
return Matches[0]->first.size();
}
/// EmitStringMatcherForChar - Given a set of strings that are known to be the
/// same length and whose characters leading up to CharNo are the same, emit
/// code to verify that CharNo and later are the same.
///
/// \return - True if control can leave the emitted code fragment.
bool StringMatcher::
EmitStringMatcherForChar(const std::vector<const StringPair*> &Matches,
unsigned CharNo, unsigned IndentCount) const {
assert(!Matches.empty() && "Must have at least one string to match!");
std::string Indent(IndentCount*2+4, ' ');
// If we have verified that the entire string matches, we're done: output the
// matching code.
if (CharNo == Matches[0]->first.size()) {
assert(Matches.size() == 1 && "Had duplicate keys to match on");
// If the to-execute code has \n's in it, indent each subsequent line.
StringRef Code = Matches[0]->second;
std::pair<StringRef, StringRef> Split = Code.split('\n');
OS << Indent << Split.first << "\t // \"" << Matches[0]->first << "\"\n";
Code = Split.second;
while (!Code.empty()) {
Split = Code.split('\n');
OS << Indent << Split.first << "\n";
Code = Split.second;
}
return false;
}
// Bucket the matches by the character we are comparing.
std::map<char, std::vector<const StringPair*> > MatchesByLetter;
for (unsigned i = 0, e = Matches.size(); i != e; ++i)
MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
// If we have exactly one bucket to match, see how many characters are common
// across the whole set and match all of them at once.
if (MatchesByLetter.size() == 1) {
unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
unsigned NumChars = FirstNonCommonLetter-CharNo;
// Emit code to break out if the prefix doesn't match.
if (NumChars == 1) {
// Do the comparison with if (Str[1] != 'f')
// FIXME: Need to escape general characters.
OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
<< Matches[0]->first[CharNo] << "')\n";
OS << Indent << " break;\n";
} else {
// Do the comparison with if memcmp(Str.data()+1, "foo", 3).
// FIXME: Need to escape general strings.
OS << Indent << "if (memcmp(" << StrVariableName << ".data()+" << CharNo
<< ", \"" << Matches[0]->first.substr(CharNo, NumChars) << "\", "
<< NumChars << "))\n";
OS << Indent << " break;\n";
}
return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount);
}
// Otherwise, we have multiple possible things, emit a switch on the
// character.
OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
OS << Indent << "default: break;\n";
for (std::map<char, std::vector<const StringPair*> >::iterator LI =
MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
// TODO: escape hard stuff (like \n) if we ever care about it.
OS << Indent << "case '" << LI->first << "':\t // "
<< LI->second.size() << " string";
if (LI->second.size() != 1) OS << 's';
OS << " to match.\n";
if (EmitStringMatcherForChar(LI->second, CharNo+1, IndentCount+1))
OS << Indent << " break;\n";
}
OS << Indent << "}\n";
return true;
}
/// Emit - Top level entry point.
///
void StringMatcher::Emit(unsigned Indent) const {
// If nothing to match, just fall through.
if (Matches.empty()) return;
// First level categorization: group strings by length.
std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
for (unsigned i = 0, e = Matches.size(); i != e; ++i)
MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
// Output a switch statement on length and categorize the elements within each
// bin.
OS.indent(Indent*2+2) << "switch (" << StrVariableName << ".size()) {\n";
OS.indent(Indent*2+2) << "default: break;\n";
for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
OS.indent(Indent*2+2) << "case " << LI->first << ":\t // "
<< LI->second.size()
<< " string" << (LI->second.size() == 1 ? "" : "s") << " to match.\n";
if (EmitStringMatcherForChar(LI->second, 0, Indent))
OS.indent(Indent*2+4) << "break;\n";
}
OS.indent(Indent*2+2) << "}\n";
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/SetTheory.cpp | //===- SetTheory.cpp - Generate ordered sets from DAG expressions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SetTheory class that computes ordered sets of
// Records from DAG expressions.
//
//===----------------------------------------------------------------------===//
#include "llvm/TableGen/SetTheory.h"
#include "llvm/Support/Format.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
using namespace llvm;
// Define the standard operators.
namespace {
typedef SetTheory::RecSet RecSet;
typedef SetTheory::RecVec RecVec;
// (add a, b, ...) Evaluate and union all arguments.
struct AddOp : public SetTheory::Operator {
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
}
};
// (sub Add, Sub, ...) Set difference.
struct SubOp : public SetTheory::Operator {
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
if (Expr->arg_size() < 2)
PrintFatalError(Loc, "Set difference needs at least two arguments: " +
Expr->getAsString());
RecSet Add, Sub;
ST.evaluate(*Expr->arg_begin(), Add, Loc);
ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Sub, Loc);
for (RecSet::iterator I = Add.begin(), E = Add.end(); I != E; ++I)
if (!Sub.count(*I))
Elts.insert(*I);
}
};
// (and S1, S2) Set intersection.
struct AndOp : public SetTheory::Operator {
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
if (Expr->arg_size() != 2)
PrintFatalError(Loc, "Set intersection requires two arguments: " +
Expr->getAsString());
RecSet S1, S2;
ST.evaluate(Expr->arg_begin()[0], S1, Loc);
ST.evaluate(Expr->arg_begin()[1], S2, Loc);
for (RecSet::iterator I = S1.begin(), E = S1.end(); I != E; ++I)
if (S2.count(*I))
Elts.insert(*I);
}
};
// SetIntBinOp - Abstract base class for (Op S, N) operators.
struct SetIntBinOp : public SetTheory::Operator {
virtual void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
RecSet &Elts, ArrayRef<SMLoc> Loc) = 0;
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
if (Expr->arg_size() != 2)
PrintFatalError(Loc, "Operator requires (Op Set, Int) arguments: " +
Expr->getAsString());
RecSet Set;
ST.evaluate(Expr->arg_begin()[0], Set, Loc);
IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]);
if (!II)
PrintFatalError(Loc, "Second argument must be an integer: " +
Expr->getAsString());
apply2(ST, Expr, Set, II->getValue(), Elts, Loc);
}
};
// (shl S, N) Shift left, remove the first N elements.
struct ShlOp : public SetIntBinOp {
void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
RecSet &Elts, ArrayRef<SMLoc> Loc) override {
if (N < 0)
PrintFatalError(Loc, "Positive shift required: " +
Expr->getAsString());
if (unsigned(N) < Set.size())
Elts.insert(Set.begin() + N, Set.end());
}
};
// (trunc S, N) Truncate after the first N elements.
struct TruncOp : public SetIntBinOp {
void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
RecSet &Elts, ArrayRef<SMLoc> Loc) override {
if (N < 0)
PrintFatalError(Loc, "Positive length required: " +
Expr->getAsString());
if (unsigned(N) > Set.size())
N = Set.size();
Elts.insert(Set.begin(), Set.begin() + N);
}
};
// Left/right rotation.
struct RotOp : public SetIntBinOp {
const bool Reverse;
RotOp(bool Rev) : Reverse(Rev) {}
void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
RecSet &Elts, ArrayRef<SMLoc> Loc) override {
if (Reverse)
N = -N;
// N > 0 -> rotate left, N < 0 -> rotate right.
if (Set.empty())
return;
if (N < 0)
N = Set.size() - (-N % Set.size());
else
N %= Set.size();
Elts.insert(Set.begin() + N, Set.end());
Elts.insert(Set.begin(), Set.begin() + N);
}
};
// (decimate S, N) Pick every N'th element of S.
struct DecimateOp : public SetIntBinOp {
void apply2(SetTheory &ST, DagInit *Expr, RecSet &Set, int64_t N,
RecSet &Elts, ArrayRef<SMLoc> Loc) override {
if (N <= 0)
PrintFatalError(Loc, "Positive stride required: " +
Expr->getAsString());
for (unsigned I = 0; I < Set.size(); I += N)
Elts.insert(Set[I]);
}
};
// (interleave S1, S2, ...) Interleave elements of the arguments.
struct InterleaveOp : public SetTheory::Operator {
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
// Evaluate the arguments individually.
SmallVector<RecSet, 4> Args(Expr->getNumArgs());
unsigned MaxSize = 0;
for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i) {
ST.evaluate(Expr->getArg(i), Args[i], Loc);
MaxSize = std::max(MaxSize, unsigned(Args[i].size()));
}
// Interleave arguments into Elts.
for (unsigned n = 0; n != MaxSize; ++n)
for (unsigned i = 0, e = Expr->getNumArgs(); i != e; ++i)
if (n < Args[i].size())
Elts.insert(Args[i][n]);
}
};
// (sequence "Format", From, To) Generate a sequence of records by name.
struct SequenceOp : public SetTheory::Operator {
void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts,
ArrayRef<SMLoc> Loc) override {
int Step = 1;
if (Expr->arg_size() > 4)
PrintFatalError(Loc, "Bad args to (sequence \"Format\", From, To): " +
Expr->getAsString());
else if (Expr->arg_size() == 4) {
if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[3])) {
Step = II->getValue();
} else
PrintFatalError(Loc, "Stride must be an integer: " +
Expr->getAsString());
}
std::string Format;
if (StringInit *SI = dyn_cast<StringInit>(Expr->arg_begin()[0]))
Format = SI->getValue();
else
PrintFatalError(Loc, "Format must be a string: " + Expr->getAsString());
int64_t From, To;
if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[1]))
From = II->getValue();
else
PrintFatalError(Loc, "From must be an integer: " + Expr->getAsString());
if (From < 0 || From >= (1 << 30))
PrintFatalError(Loc, "From out of range");
if (IntInit *II = dyn_cast<IntInit>(Expr->arg_begin()[2]))
To = II->getValue();
else
PrintFatalError(Loc, "From must be an integer: " + Expr->getAsString());
if (To < 0 || To >= (1 << 30))
PrintFatalError(Loc, "To out of range");
RecordKeeper &Records =
cast<DefInit>(Expr->getOperator())->getDef()->getRecords();
Step *= From <= To ? 1 : -1;
while (true) {
if (Step > 0 && From > To)
break;
else if (Step < 0 && From < To)
break;
std::string Name;
raw_string_ostream OS(Name);
OS << format(Format.c_str(), unsigned(From));
Record *Rec = Records.getDef(OS.str());
if (!Rec)
PrintFatalError(Loc, "No def named '" + Name + "': " +
Expr->getAsString());
// Try to reevaluate Rec in case it is a set.
if (const RecVec *Result = ST.expand(Rec))
Elts.insert(Result->begin(), Result->end());
else
Elts.insert(Rec);
From += Step;
}
}
};
// Expand a Def into a set by evaluating one of its fields.
struct FieldExpander : public SetTheory::Expander {
StringRef FieldName;
FieldExpander(StringRef fn) : FieldName(fn) {}
void expand(SetTheory &ST, Record *Def, RecSet &Elts) override {
ST.evaluate(Def->getValueInit(FieldName), Elts, Def->getLoc());
}
};
} // end anonymous namespace
// Pin the vtables to this file.
void SetTheory::Operator::anchor() {}
void SetTheory::Expander::anchor() {}
SetTheory::SetTheory() {
addOperator("add", llvm::make_unique<AddOp>());
addOperator("sub", llvm::make_unique<SubOp>());
addOperator("and", llvm::make_unique<AndOp>());
addOperator("shl", llvm::make_unique<ShlOp>());
addOperator("trunc", llvm::make_unique<TruncOp>());
addOperator("rotl", llvm::make_unique<RotOp>(false));
addOperator("rotr", llvm::make_unique<RotOp>(true));
addOperator("decimate", llvm::make_unique<DecimateOp>());
addOperator("interleave", llvm::make_unique<InterleaveOp>());
addOperator("sequence", llvm::make_unique<SequenceOp>());
}
void SetTheory::addOperator(StringRef Name, std::unique_ptr<Operator> Op) {
Operators[Name] = std::move(Op);
}
void SetTheory::addExpander(StringRef ClassName, std::unique_ptr<Expander> E) {
Expanders[ClassName] = std::move(E);
}
void SetTheory::addFieldExpander(StringRef ClassName, StringRef FieldName) {
addExpander(ClassName, llvm::make_unique<FieldExpander>(FieldName));
}
void SetTheory::evaluate(Init *Expr, RecSet &Elts, ArrayRef<SMLoc> Loc) {
// A def in a list can be a just an element, or it may expand.
if (DefInit *Def = dyn_cast<DefInit>(Expr)) {
if (const RecVec *Result = expand(Def->getDef()))
return Elts.insert(Result->begin(), Result->end());
Elts.insert(Def->getDef());
return;
}
// Lists simply expand.
if (ListInit *LI = dyn_cast<ListInit>(Expr))
return evaluate(LI->begin(), LI->end(), Elts, Loc);
// Anything else must be a DAG.
DagInit *DagExpr = dyn_cast<DagInit>(Expr);
if (!DagExpr)
PrintFatalError(Loc, "Invalid set element: " + Expr->getAsString());
DefInit *OpInit = dyn_cast<DefInit>(DagExpr->getOperator());
if (!OpInit)
PrintFatalError(Loc, "Bad set expression: " + Expr->getAsString());
auto I = Operators.find(OpInit->getDef()->getName());
if (I == Operators.end())
PrintFatalError(Loc, "Unknown set operator: " + Expr->getAsString());
I->second->apply(*this, DagExpr, Elts, Loc);
}
const RecVec *SetTheory::expand(Record *Set) {
// Check existing entries for Set and return early.
ExpandMap::iterator I = Expansions.find(Set);
if (I != Expansions.end())
return &I->second;
// This is the first time we see Set. Find a suitable expander.
ArrayRef<Record *> SC = Set->getSuperClasses();
for (unsigned i = 0, e = SC.size(); i != e; ++i) {
// Skip unnamed superclasses.
if (!dyn_cast<StringInit>(SC[i]->getNameInit()))
continue;
auto I = Expanders.find(SC[i]->getName());
if (I != Expanders.end()) {
// This breaks recursive definitions.
RecVec &EltVec = Expansions[Set];
RecSet Elts;
I->second->expand(*this, Set, Elts);
EltVec.assign(Elts.begin(), Elts.end());
return &EltVec;
}
}
// Set is not expandable.
return nullptr;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/TGLexer.h | //===- TGLexer.h - Lexer for TableGen Files ---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class represents the Lexer for tablegen files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TABLEGEN_TGLEXER_H
#define LLVM_LIB_TABLEGEN_TGLEXER_H
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/SMLoc.h"
#include <cassert>
#include <map>
#include <string>
namespace llvm {
class SourceMgr;
class SMLoc;
class Twine;
namespace tgtok {
enum TokKind {
// Markers
Eof, Error,
// Tokens with no info.
minus, plus, // - +
l_square, r_square, // [ ]
l_brace, r_brace, // { }
l_paren, r_paren, // ( )
less, greater, // < >
colon, semi, // : ;
comma, period, // , .
equal, question, // = ?
paste, // #
// Keywords.
Bit, Bits, Class, Code, Dag, Def, Foreach, Defm, Field, In, Int, Let, List,
MultiClass, String,
// !keywords.
XConcat, XADD, XAND, XSRA, XSRL, XSHL, XListConcat, XStrConcat, XCast,
XSubst, XForEach, XHead, XTail, XEmpty, XIf, XEq,
// Integer value.
IntVal,
// Binary constant. Note that these are sized according to the number of
// bits given.
BinaryIntVal,
// String valued tokens.
Id, StrVal, VarName, CodeFragment
};
}
/// TGLexer - TableGen Lexer class.
class TGLexer {
SourceMgr &SrcMgr;
const char *CurPtr;
StringRef CurBuf;
// Information about the current token.
const char *TokStart;
tgtok::TokKind CurCode;
std::string CurStrVal; // This is valid for ID, STRVAL, VARNAME, CODEFRAGMENT
int64_t CurIntVal; // This is valid for INTVAL.
/// CurBuffer - This is the current buffer index we're lexing from as managed
/// by the SourceMgr object.
unsigned CurBuffer;
public:
typedef std::map<std::string, SMLoc> DependenciesMapTy;
private:
/// Dependencies - This is the list of all included files.
DependenciesMapTy Dependencies;
public:
TGLexer(SourceMgr &SrcMgr);
tgtok::TokKind Lex() {
return CurCode = LexToken();
}
const DependenciesMapTy &getDependencies() const {
return Dependencies;
}
tgtok::TokKind getCode() const { return CurCode; }
const std::string &getCurStrVal() const {
assert((CurCode == tgtok::Id || CurCode == tgtok::StrVal ||
CurCode == tgtok::VarName || CurCode == tgtok::CodeFragment) &&
"This token doesn't have a string value");
return CurStrVal;
}
int64_t getCurIntVal() const {
assert(CurCode == tgtok::IntVal && "This token isn't an integer");
return CurIntVal;
}
std::pair<int64_t, unsigned> getCurBinaryIntVal() const {
assert(CurCode == tgtok::BinaryIntVal &&
"This token isn't a binary integer");
return std::make_pair(CurIntVal, (CurPtr - TokStart)-2);
}
SMLoc getLoc() const;
private:
/// LexToken - Read the next token and return its code.
tgtok::TokKind LexToken();
tgtok::TokKind ReturnError(const char *Loc, const Twine &Msg);
int getNextChar();
int peekNextChar(int Index);
void SkipBCPLComment();
bool SkipCComment();
tgtok::TokKind LexIdentifier();
bool LexInclude();
tgtok::TokKind LexString();
tgtok::TokKind LexVarName();
tgtok::TokKind LexNumber();
tgtok::TokKind LexBracket();
tgtok::TokKind LexExclaim();
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/TableGen/TGParser.h | //===- TGParser.h - Parser for TableGen Files -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class represents the Parser for tablegen files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TABLEGEN_TGPARSER_H
#define LLVM_LIB_TABLEGEN_TGPARSER_H
#include "TGLexer.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <map>
namespace llvm {
class Record;
class RecordVal;
class RecordKeeper;
class RecTy;
class Init;
struct MultiClass;
struct SubClassReference;
struct SubMultiClassReference;
struct LetRecord {
std::string Name;
std::vector<unsigned> Bits;
Init *Value;
SMLoc Loc;
LetRecord(const std::string &N, const std::vector<unsigned> &B, Init *V,
SMLoc L)
: Name(N), Bits(B), Value(V), Loc(L) {
}
};
/// ForeachLoop - Record the iteration state associated with a for loop.
/// This is used to instantiate items in the loop body.
struct ForeachLoop {
VarInit *IterVar;
ListInit *ListValue;
ForeachLoop(VarInit *IVar, ListInit *LValue)
: IterVar(IVar), ListValue(LValue) {}
};
class TGParser {
TGLexer Lex;
std::vector<std::vector<LetRecord> > LetStack;
std::map<std::string, std::unique_ptr<MultiClass>> MultiClasses;
/// Loops - Keep track of any foreach loops we are within.
///
typedef std::vector<ForeachLoop> LoopVector;
LoopVector Loops;
/// CurMultiClass - If we are parsing a 'multiclass' definition, this is the
/// current value.
MultiClass *CurMultiClass;
// Record tracker
RecordKeeper &Records;
unsigned AnonCounter;
// A "named boolean" indicating how to parse identifiers. Usually
// identifiers map to some existing object but in special cases
// (e.g. parsing def names) no such object exists yet because we are
// in the middle of creating in. For those situations, allow the
// parser to ignore missing object errors.
enum IDParseMode {
ParseValueMode, // We are parsing a value we expect to look up.
ParseNameMode, // We are parsing a name of an object that does not yet
// exist.
ParseForeachMode // We are parsing a foreach init.
};
public:
TGParser(SourceMgr &SrcMgr, RecordKeeper &records)
: Lex(SrcMgr), CurMultiClass(nullptr), Records(records), AnonCounter(0) {}
/// ParseFile - Main entrypoint for parsing a tblgen file. These parser
/// routines return true on error, or false on success.
bool ParseFile();
bool Error(SMLoc L, const Twine &Msg) const {
PrintError(L, Msg);
return true;
}
bool TokError(const Twine &Msg) const {
return Error(Lex.getLoc(), Msg);
}
const TGLexer::DependenciesMapTy &getDependencies() const {
return Lex.getDependencies();
}
private: // Semantic analysis methods.
bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV);
bool SetValue(Record *TheRec, SMLoc Loc, Init *ValName,
const std::vector<unsigned> &BitList, Init *V);
bool SetValue(Record *TheRec, SMLoc Loc, const std::string &ValName,
const std::vector<unsigned> &BitList, Init *V) {
return SetValue(TheRec, Loc, StringInit::get(ValName), BitList, V);
}
bool AddSubClass(Record *Rec, SubClassReference &SubClass);
bool AddSubMultiClass(MultiClass *CurMC,
SubMultiClassReference &SubMultiClass);
std::string GetNewAnonymousName();
// IterRecord: Map an iterator name to a value.
struct IterRecord {
VarInit *IterVar;
Init *IterValue;
IterRecord(VarInit *Var, Init *Val) : IterVar(Var), IterValue(Val) {}
};
// IterSet: The set of all iterator values at some point in the
// iteration space.
typedef std::vector<IterRecord> IterSet;
bool ProcessForeachDefs(Record *CurRec, SMLoc Loc);
bool ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals);
private: // Parser methods.
bool ParseObjectList(MultiClass *MC = nullptr);
bool ParseObject(MultiClass *MC);
bool ParseClass();
bool ParseMultiClass();
Record *InstantiateMulticlassDef(MultiClass &MC,
Record *DefProto,
Init *&DefmPrefix,
SMRange DefmPrefixRange,
const std::vector<Init *> &TArgs,
std::vector<Init *> &TemplateVals);
bool ResolveMulticlassDefArgs(MultiClass &MC,
Record *DefProto,
SMLoc DefmPrefixLoc,
SMLoc SubClassLoc,
const std::vector<Init *> &TArgs,
std::vector<Init *> &TemplateVals,
bool DeleteArgs);
bool ResolveMulticlassDef(MultiClass &MC,
Record *CurRec,
Record *DefProto,
SMLoc DefmPrefixLoc);
bool ParseDefm(MultiClass *CurMultiClass);
bool ParseDef(MultiClass *CurMultiClass);
bool ParseForeach(MultiClass *CurMultiClass);
bool ParseTopLevelLet(MultiClass *CurMultiClass);
std::vector<LetRecord> ParseLetList();
bool ParseObjectBody(Record *CurRec);
bool ParseBody(Record *CurRec);
bool ParseBodyItem(Record *CurRec);
bool ParseTemplateArgList(Record *CurRec);
Init *ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
VarInit *ParseForeachDeclaration(ListInit *&ForeachListValue);
SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
SubMultiClassReference ParseSubMultiClassReference(MultiClass *CurMC);
Init *ParseIDValue(Record *CurRec, const std::string &Name, SMLoc NameLoc,
IDParseMode Mode = ParseValueMode);
Init *ParseSimpleValue(Record *CurRec, RecTy *ItemType = nullptr,
IDParseMode Mode = ParseValueMode);
Init *ParseValue(Record *CurRec, RecTy *ItemType = nullptr,
IDParseMode Mode = ParseValueMode);
std::vector<Init*> ParseValueList(Record *CurRec, Record *ArgsRec = nullptr,
RecTy *EltTy = nullptr);
std::vector<std::pair<llvm::Init*, std::string> > ParseDagArgList(Record *);
bool ParseOptionalRangeList(std::vector<unsigned> &Ranges);
bool ParseOptionalBitList(std::vector<unsigned> &Ranges);
std::vector<unsigned> ParseRangeList();
bool ParseRangePiece(std::vector<unsigned> &Ranges);
RecTy *ParseType();
Init *ParseOperation(Record *CurRec, RecTy *ItemType);
RecTy *ParseOperatorType();
Init *ParseObjectName(MultiClass *CurMultiClass);
Record *ParseClassID();
MultiClass *ParseMultiClassID();
bool ApplyLetStack(Record *CurRec);
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSourceFiles.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSourceFiles.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <vector>
#include "dia2.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Metadata.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class SourceFile : public IDiaSourceFile {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<Session> m_pSession;
DWORD m_index;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaSourceFile>(this, iid, ppvObject);
}
SourceFile(IMalloc *pMalloc, Session *pSession, DWORD index);
llvm::MDTuple *NameContent() const;
llvm::StringRef Name() const;
STDMETHODIMP get_uniqueId(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_fileName(
/* [retval][out] */ BSTR *pRetVal) override;
STDMETHODIMP get_checksumType(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_compilands(
/* [retval][out] */ IDiaEnumSymbols **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_checksum(
/* [in] */ DWORD cbData,
/* [out] */ DWORD *pcbData,
/* [size_is][out] */ BYTE *pbData) override {
return ENotImpl();
}
};
class SourceFilesTable
: public impl::TableBase<IDiaEnumSourceFiles, IDiaSourceFile> {
public:
SourceFilesTable(IMalloc *pMalloc, Session *pSession);
SourceFilesTable(IMalloc *pMalloc, Session *pSession,
std::vector<CComPtr<IDiaSourceFile>> &&items);
HRESULT GetItem(DWORD index, IDiaSourceFile **ppItem) override;
private:
std::vector<CComPtr<IDiaSourceFile>> m_items;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableInputAssemblyFile.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableInputAssemblyFile.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class InputAssemblyFilesTable
: public impl::TableBase<IDiaEnumInputAssemblyFiles,
IDiaInputAssemblyFile> {
public:
InputAssemblyFilesTable(IMalloc *pMalloc, Session *pSession);
HRESULT GetItem(DWORD index, IDiaInputAssemblyFile **ppItem) override;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixLiveVariables.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixLiveVariables.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Implements a mapping from the instructions in the Module to the set of //
// live variables available in that instruction. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <map>
#include <memory>
#include <vector>
#include "DxcPixDxilDebugInfo.h"
namespace llvm {
class DIVariable;
class Instruction;
class Module;
class Value;
} // namespace llvm
namespace dxil_debug_info {
// VariableInfo is the bag with the information about a particular
// DIVariable in the Module.
struct VariableInfo {
using OffsetInBits = unsigned;
// Location is the dxil alloca register where this variable lives.
struct Location {
llvm::Value *m_V = nullptr;
unsigned m_FragmentIndex = 0;
};
explicit VariableInfo(llvm::DIVariable *Variable) : m_Variable(Variable) {}
llvm::DIVariable *m_Variable;
std::map<OffsetInBits, Location> m_ValueLocationMap;
#ifndef NDEBUG
std::vector<bool> m_DbgDeclareValidation;
#endif // !NDEBUG
};
class LiveVariables {
public:
LiveVariables();
~LiveVariables();
HRESULT Init(DxcPixDxilDebugInfo *pDxilDebugInfo);
void Clear();
HRESULT
GetLiveVariablesAtInstruction(llvm::Instruction *Instr,
IDxcPixDxilLiveVariables **Result) const;
private:
struct Impl;
std::unique_ptr<Impl> m_pImpl;
};
HRESULT
CreateDxilLiveVariables(DxcPixDxilDebugInfo *pDxilDebugInfo,
std::vector<const VariableInfo *> &&LiveVariables,
IDxcPixDxilLiveVariables **ppResult);
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaDataSource.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaDataSource.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaDataSource.h"
#include "dxc/DXIL/DxilPDB.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/dxcapi.impl.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "DxilDiaSession.h"
dxil_dia::DataSource::DataSource(IMalloc *pMalloc) : m_pMalloc(pMalloc) {}
dxil_dia::DataSource::~DataSource() {
// These are cross-referenced, so let's be explicit.
m_finder.reset();
m_module.reset();
m_context.reset();
}
STDMETHODIMP dxil_dia::DataSource::get_lastError(BSTR *pRetVal) {
*pRetVal = nullptr;
return S_OK;
}
namespace dxil_dia {
std::unique_ptr<llvm::MemoryBuffer>
getMemBufferFromBlob(IDxcBlob *pBlob, const llvm::Twine &BufferName) {
llvm::StringRef Data((LPSTR)pBlob->GetBufferPointer(),
pBlob->GetBufferSize());
return llvm::MemoryBuffer::getMemBufferCopy(Data, BufferName);
}
std::unique_ptr<llvm::MemoryBuffer>
getMemBufferFromStream(IStream *pStream, std::vector<char> &DataContainer,
const llvm::Twine &BufferName) {
CComPtr<IDxcBlob> pBlob;
if (SUCCEEDED(pStream->QueryInterface(&pBlob))) {
return getMemBufferFromBlob(pBlob, BufferName);
}
STATSTG statstg;
IFT(pStream->Stat(&statstg, STATFLAG_NONAME));
size_t size = statstg.cbSize.LowPart;
DataContainer.resize(size);
ULONG read;
IFT(pStream->Read(DataContainer.data(), size, &read));
llvm::StringRef Str(DataContainer.data(), size);
std::unique_ptr<llvm::MemoryBuffer> result(
llvm::MemoryBuffer::getMemBuffer(Str, BufferName.str(), false));
return result;
}
} // namespace dxil_dia
STDMETHODIMP dxil_dia::DataSource::loadDataFromIStream(IStream *pInputIStream) {
try {
DxcThreadMalloc TM(m_pMalloc);
if (m_module.get() != nullptr) {
return E_FAIL;
}
// Setup filesystem because bitcode reader might emit warning
::llvm::sys::fs::MSFileSystem *msfPtr;
IFT(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
CComPtr<IStream> pIStream = pInputIStream;
CComPtr<IDxcBlob> pContainer;
if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(m_pMalloc, pInputIStream,
&pContainer))) {
const hlsl::DxilContainerHeader *pContainerHeader =
hlsl::IsDxilContainerLike(pContainer->GetBufferPointer(),
pContainer->GetBufferSize());
if (!hlsl::IsValidDxilContainer(pContainerHeader,
pContainer->GetBufferSize()))
return E_FAIL;
const hlsl::DxilPartHeader *PartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DFCC_ShaderDebugInfoDXIL);
if (!PartHeader)
return E_FAIL;
CComPtr<IDxcBlobEncoding> pPinnedBlob;
IFR(hlsl::DxcCreateBlobWithEncodingFromPinned(
PartHeader + 1, PartHeader->PartSize, CP_ACP, &pPinnedBlob));
pIStream.Release();
IFR(hlsl::CreateReadOnlyBlobStream(pPinnedBlob, &pIStream));
}
m_context.reset();
m_finder.reset();
m_context = std::make_shared<llvm::LLVMContext>();
llvm::MemoryBuffer *pBitcodeBuffer;
std::unique_ptr<llvm::MemoryBuffer> pEmbeddedBuffer;
std::vector<char> DataContainer;
std::unique_ptr<llvm::MemoryBuffer> pBuffer =
getMemBufferFromStream(pIStream, DataContainer, "data");
size_t bufferSize = pBuffer->getBufferSize();
// The buffer can hold LLVM bitcode for a module, or the ILDB
// part from a container.
if (bufferSize < sizeof(UINT32)) {
return DXC_E_MALFORMED_CONTAINER;
}
const UINT32 BC_C0DE = ((INT32)(INT8)'B' | (INT32)(INT8)'C' << 8 |
(INT32)0xDEC0 << 16); // BC0xc0de in big endian
if (BC_C0DE == *(const UINT32 *)pBuffer->getBufferStart()) {
pBitcodeBuffer = pBuffer.get();
} else {
if (bufferSize <= sizeof(hlsl::DxilProgramHeader)) {
return DXC_E_MALFORMED_CONTAINER;
}
const hlsl::DxilProgramHeader *pDxilProgramHeader =
(const hlsl::DxilProgramHeader *)pBuffer->getBufferStart();
if (pDxilProgramHeader->BitcodeHeader.DxilMagic != hlsl::DxilMagicValue) {
return DXC_E_MALFORMED_CONTAINER;
}
UINT32 BlobSize;
const char *pBitcode = nullptr;
hlsl::GetDxilProgramBitcode(pDxilProgramHeader, &pBitcode, &BlobSize);
std::unique_ptr<llvm::MemoryBuffer> p = llvm::MemoryBuffer::getMemBuffer(
llvm::StringRef(pBitcode, BlobSize), "data",
false /* RequiresNullTerminator */);
pEmbeddedBuffer.swap(p);
pBitcodeBuffer = pEmbeddedBuffer.get();
}
std::string DiagStr;
std::unique_ptr<llvm::Module> pModule =
hlsl::dxilutil::LoadModuleFromBitcode(pBitcodeBuffer, *m_context.get(),
DiagStr);
if (!pModule.get())
return E_FAIL;
m_finder = std::make_shared<llvm::DebugInfoFinder>();
m_finder->processModule(*pModule.get());
m_module.reset(pModule.release());
}
CATCH_CPP_RETURN_HRESULT();
return S_OK;
}
STDMETHODIMP dxil_dia::DataSource::openSession(IDiaSession **ppSession) {
DxcThreadMalloc TM(m_pMalloc);
*ppSession = nullptr;
if (m_module.get() == nullptr)
return E_FAIL;
::llvm::sys::fs::MSFileSystem *msfPtr;
IFT(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
CComPtr<Session> pSession = Session::Alloc(DxcGetThreadMallocNoRef());
IFROOM(pSession.p);
pSession->Init(m_context, m_module, m_finder);
*ppSession = pSession.Detach();
return S_OK;
}
HRESULT CreateDxcDiaDataSource(REFIID riid, LPVOID *ppv) {
CComPtr<dxil_dia::DataSource> result =
CreateOnMalloc<dxil_dia::DataSource>(DxcGetThreadMallocNoRef());
if (result == nullptr) {
*ppv = nullptr;
return E_OUTOFMEMORY;
}
return result.p->QueryInterface(riid, ppv);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableFrameData.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableFrameData.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class FrameDataTable
: public impl::TableBase<IDiaEnumFrameData, IDiaFrameData> {
public:
FrameDataTable(IMalloc *pMalloc, Session *pSession);
// HLSL inlines functions for a program, so no data to return.
STDMETHODIMP frameByRVA(
/* [in] */ DWORD relativeVirtualAddress,
/* [retval][out] */ IDiaFrameData **frame) override {
return ENotImpl();
}
STDMETHODIMP frameByVA(
/* [in] */ ULONGLONG virtualAddress,
/* [retval][out] */ IDiaFrameData **frame) override {
return ENotImpl();
}
HRESULT GetItem(DWORD index, IDiaFrameData **ppItem) override;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixTypes.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixTypes.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines the implementation for the DxcPixType -- and its subinterfaces. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxcPixTypes.h"
#include "DxcPixBase.h"
#include "DxilDiaSession.h"
static const char *GetTypeNameOrDefault(llvm::DIType *diType) {
auto stringRef = diType->getName();
if (stringRef.empty())
return "<unnamed>";
return stringRef.data();
}
HRESULT dxil_debug_info::CreateDxcPixType(DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIType *diType,
IDxcPixType **ppResult) {
if (auto *BT = llvm::dyn_cast<llvm::DIBasicType>(diType)) {
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixScalarType>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, BT);
} else if (auto *CT = llvm::dyn_cast<llvm::DICompositeType>(diType)) {
switch (CT->getTag()) {
default:
break;
case llvm::dwarf::DW_TAG_array_type: {
const unsigned FirstDim = 0;
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixArrayType>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, CT,
FirstDim);
}
case llvm::dwarf::DW_TAG_class_type:
case llvm::dwarf::DW_TAG_structure_type:
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixStructType>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, CT);
}
} else if (auto *DT = llvm::dyn_cast<llvm::DIDerivedType>(diType)) {
switch (DT->getTag()) {
default:
break;
case llvm::dwarf::DW_TAG_const_type:
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixConstType>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, DT);
case llvm::dwarf::DW_TAG_typedef:
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixTypedefType>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, DT);
}
}
return E_UNEXPECTED;
}
STDMETHODIMP dxil_debug_info::DxcPixConstType::GetName(BSTR *Name) {
CComPtr<IDxcPixType> BaseType;
IFR(UnAlias(&BaseType));
CComBSTR BaseName;
IFR(BaseType->GetName(&BaseName));
*Name = CComBSTR((L"const " + std::wstring(BaseName)).c_str()).Detach();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixConstType::GetSizeInBits(DWORD *pSize) {
CComPtr<IDxcPixType> BaseType;
IFR(UnAlias(&BaseType));
return BaseType->GetSizeInBits(pSize);
}
STDMETHODIMP dxil_debug_info::DxcPixConstType::UnAlias(IDxcPixType **ppType) {
return CreateDxcPixType(m_pDxilDebugInfo, m_pBaseType, ppType);
}
STDMETHODIMP dxil_debug_info::DxcPixTypedefType::GetName(BSTR *Name) {
*Name = CComBSTR(CA2W(GetTypeNameOrDefault(m_pType))).Detach();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixTypedefType::GetSizeInBits(DWORD *pSize) {
CComPtr<IDxcPixType> BaseType;
IFR(UnAlias(&BaseType));
return BaseType->GetSizeInBits(pSize);
}
STDMETHODIMP dxil_debug_info::DxcPixTypedefType::UnAlias(IDxcPixType **ppType) {
return CreateDxcPixType(m_pDxilDebugInfo, m_pBaseType, ppType);
}
STDMETHODIMP dxil_debug_info::DxcPixScalarType::GetName(BSTR *Name) {
*Name = CComBSTR(CA2W(GetTypeNameOrDefault(m_pType))).Detach();
return S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixScalarType::GetSizeInBits(DWORD *pSizeInBits) {
*pSizeInBits = m_pType->getSizeInBits();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixScalarType::UnAlias(IDxcPixType **ppType) {
*ppType = this;
this->AddRef();
return S_FALSE;
}
STDMETHODIMP dxil_debug_info::DxcPixArrayType::GetName(BSTR *Name) {
CComBSTR name(CA2W(GetTypeNameOrDefault(m_pBaseType)));
name.Append(L"[]");
*Name = name.Detach();
return S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixArrayType::GetSizeInBits(DWORD *pSizeInBits) {
*pSizeInBits = m_pArray->getSizeInBits();
for (unsigned ContainerDims = 0; ContainerDims < m_DimNum; ++ContainerDims) {
auto *SR = llvm::dyn_cast<llvm::DISubrange>(
m_pArray->getElements()[ContainerDims]);
auto count = SR->getCount();
if (count == 0) {
return E_FAIL;
}
*pSizeInBits /= count;
}
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixArrayType::UnAlias(IDxcPixType **ppType) {
*ppType = this;
this->AddRef();
return S_FALSE;
}
STDMETHODIMP
dxil_debug_info::DxcPixArrayType::GetNumElements(DWORD *ppNumElements) {
auto *SR =
llvm::dyn_cast<llvm::DISubrange>(m_pArray->getElements()[m_DimNum]);
if (SR == nullptr) {
return E_FAIL;
}
*ppNumElements = SR->getCount();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixArrayType::GetIndexedType(
IDxcPixType **ppIndexedElement) {
assert(1 + m_DimNum <= m_pArray->getElements().size());
if (1 + m_DimNum == m_pArray->getElements().size()) {
return CreateDxcPixType(m_pDxilDebugInfo, m_pBaseType, ppIndexedElement);
}
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixArrayType>(
ppIndexedElement, m_pMalloc, m_pDxilDebugInfo, m_pArray, 1 + m_DimNum);
}
STDMETHODIMP
dxil_debug_info::DxcPixArrayType::GetElementType(IDxcPixType **ppElementType) {
return CreateDxcPixType(m_pDxilDebugInfo, m_pBaseType, ppElementType);
}
STDMETHODIMP dxil_debug_info::DxcPixStructType::GetName(BSTR *Name) {
*Name = CComBSTR(CA2W(GetTypeNameOrDefault(m_pStruct))).Detach();
return S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixStructType::GetSizeInBits(DWORD *pSizeInBits) {
*pSizeInBits = m_pStruct->getSizeInBits();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixStructType::UnAlias(IDxcPixType **ppType) {
*ppType = this;
this->AddRef();
return S_FALSE;
}
STDMETHODIMP
dxil_debug_info::DxcPixStructType::GetNumFields(DWORD *ppNumFields) {
*ppNumFields = 0;
// DWARF lists the ancestor class, if any, and member fns
// as a member element. Don't count those as data members:
for (auto *Node : m_pStruct->getElements()) {
if (Node->getTag() != llvm::dwarf::DW_TAG_inheritance &&
Node->getTag() != llvm::dwarf::DW_TAG_subprogram) {
(*ppNumFields)++;
}
}
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixStructType::GetFieldByIndex(
DWORD dwIndex, IDxcPixStructField **ppField) {
*ppField = nullptr;
// DWARF lists the ancestor class, if any, and member fns
// as a member element. Skip such fields when enumerating
// by index.
DWORD ElementIndex = 0;
DWORD ElementSkipCount = 0;
for (auto *Node : m_pStruct->getElements()) {
if (Node->getTag() == llvm::dwarf::DW_TAG_inheritance ||
Node->getTag() == llvm::dwarf::DW_TAG_subprogram) {
ElementSkipCount++;
} else {
if (dwIndex + ElementSkipCount == ElementIndex) {
auto *pDIField = llvm::dyn_cast<llvm::DIDerivedType>(
m_pStruct->getElements()[ElementIndex]);
if (pDIField == nullptr) {
return E_FAIL;
}
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixStructField>(
ppField, m_pMalloc, m_pDxilDebugInfo, pDIField);
}
}
ElementIndex++;
}
return E_BOUNDS;
}
STDMETHODIMP dxil_debug_info::DxcPixStructType::GetFieldByName(
LPCWSTR lpName, IDxcPixStructField **ppField) {
std::string name = std::string(CW2A(lpName));
for (auto *Node : m_pStruct->getElements()) {
auto *pDIField = llvm::dyn_cast<llvm::DIDerivedType>(Node);
if (pDIField == nullptr) {
return E_FAIL;
}
if (pDIField->getTag() == llvm::dwarf::DW_TAG_inheritance) {
continue;
} else {
if (name == pDIField->getName()) {
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixStructField>(
ppField, m_pMalloc, m_pDxilDebugInfo, pDIField);
}
}
}
return E_BOUNDS;
}
STDMETHODIMP
dxil_debug_info::DxcPixStructType::GetBaseType(IDxcPixType **ppType) {
for (auto *Node : m_pStruct->getElements()) {
auto *pDIField = llvm::dyn_cast<llvm::DIDerivedType>(Node);
if (pDIField != nullptr) {
if (pDIField->getTag() == llvm::dwarf::DW_TAG_inheritance) {
const llvm::DITypeIdentifierMap EmptyMap;
auto baseType = pDIField->getBaseType().resolve(EmptyMap);
if (auto *CompositeType =
llvm::dyn_cast<llvm::DICompositeType>(baseType)) {
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixStructType>(
ppType, m_pMalloc, m_pDxilDebugInfo, CompositeType);
} else {
return E_NOINTERFACE;
}
}
}
}
return E_NOINTERFACE;
}
STDMETHODIMP dxil_debug_info::DxcPixStructField::GetName(BSTR *Name) {
*Name = CComBSTR(CA2W(GetTypeNameOrDefault(m_pField))).Detach();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixStructField::GetType(IDxcPixType **ppType) {
return CreateDxcPixType(m_pDxilDebugInfo, m_pType, ppType);
}
STDMETHODIMP
dxil_debug_info::DxcPixStructField::GetOffsetInBits(DWORD *pOffsetInBits) {
*pOffsetInBits = m_pField->getOffsetInBits();
return S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixStructField::GetFieldSizeInBits(
DWORD *pFieldSizeInBits) {
*pFieldSizeInBits = m_pField->getSizeInBits();
return S_OK;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixLiveVariables.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixLiveVariables.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines the mapping between instructions and the set of live variables //
// for it. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "DxcPixDxilDebugInfo.h"
#include "DxcPixLiveVariables.h"
#include "DxcPixLiveVariables_FragmentIterator.h"
#include "DxilDiaSession.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include <unordered_map>
// If a function is inlined, then the scope of variables within that function
// will be that scope. Since many such callers may inline the function, we
// actually need a "scope" that's unique to each "instance" of that function.
// The caller's scope would be unique, but would have the undesirable
// side-effect of smushing all of the function's variables together with the
// caller's variables, at least from the point of view of PIX. The pair of
// scopes (the function's and the caller's) is both unique to that particular
// inlining, and distinct from the caller's scope by itself.
class UniqueScopeForInlinedFunctions {
llvm::DIScope *FunctionScope;
llvm::DIScope *InlinedAtScope;
public:
bool Valid() const { return FunctionScope != nullptr; }
void AscendScopeHierarchy() {
// DINamespace has a getScope member (that hides DIScope's)
// that returns a DIScope directly, but if that namespace
// is at file-level scope, it will return nullptr.
if (auto Namespace = llvm::dyn_cast<llvm::DINamespace>(FunctionScope)) {
if (auto *ContainingScope = Namespace->getScope()) {
if (FunctionScope == InlinedAtScope)
InlinedAtScope = FunctionScope = ContainingScope;
else
FunctionScope = ContainingScope;
return;
}
}
const llvm::DITypeIdentifierMap EmptyMap;
if (FunctionScope == InlinedAtScope)
InlinedAtScope = FunctionScope =
FunctionScope->getScope().resolve(EmptyMap);
else
FunctionScope = FunctionScope->getScope().resolve(EmptyMap);
}
static UniqueScopeForInlinedFunctions Create(llvm::DebugLoc const &DbgLoc,
llvm::DIScope *FunctionScope) {
UniqueScopeForInlinedFunctions ret;
ret.FunctionScope = FunctionScope;
ret.InlinedAtScope =
llvm::dyn_cast_or_null<llvm::DIScope>(DbgLoc.getInlinedAtScope());
return ret;
}
bool operator==(const UniqueScopeForInlinedFunctions &o) const {
return FunctionScope == o.FunctionScope &&
InlinedAtScope == o.InlinedAtScope;
}
std::size_t operator()(const UniqueScopeForInlinedFunctions &k) const {
using std::hash;
using std::size_t;
const uint64_t f = reinterpret_cast<uint64_t>(k.FunctionScope);
const uint64_t s = reinterpret_cast<uint64_t>(k.InlinedAtScope);
std::hash<uint64_t> h;
return (h(f) ^ h(s));
}
};
// ValidateDbgDeclare ensures that all of the bits in
// [FragmentSizeInBits, FragmentOffsetInBits) are currently
// not assigned to a dxil alloca register -- i.e., it
// tries to find overlapping alloca registers -- which should
// never happen -- to report the issue.
void ValidateDbgDeclare(dxil_debug_info::VariableInfo *VarInfo,
unsigned FragmentSizeInBits,
unsigned FragmentOffsetInBits) {
// #DSLTodo: When operating on libraries, each exported
// function is instrumented separately, resulting in
// overlapping variables. This is not a problem for, e.g.
// raytracing debugging because WinPIX only ever (so far)
// invokes debugging on one export at a time.
// With the advent of DSL, this will have to change...
#if 0 // ndef NDEBUG
for (unsigned i = 0; i < FragmentSizeInBits; ++i)
{
const unsigned BitNum = FragmentOffsetInBits + i;
VarInfo->m_DbgDeclareValidation.resize(
std::max<unsigned>(VarInfo->m_DbgDeclareValidation.size(),
BitNum + 1));
assert(!VarInfo->m_DbgDeclareValidation[BitNum]);
VarInfo->m_DbgDeclareValidation[BitNum] = true;
}
#endif // !NDEBUG
}
struct dxil_debug_info::LiveVariables::Impl {
using VariableInfoMap =
std::unordered_map<llvm::DIVariable *, std::unique_ptr<VariableInfo>>;
using LiveVarsMap =
std::unordered_map<UniqueScopeForInlinedFunctions, VariableInfoMap,
UniqueScopeForInlinedFunctions>;
IMalloc *m_pMalloc;
DxcPixDxilDebugInfo *m_pDxilDebugInfo;
llvm::Module *m_pModule;
LiveVarsMap m_LiveVarsDbgDeclare;
VariableInfoMap m_LiveGlobalVarsDbgDeclare;
void Init(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::Module *pModule);
void Init_DbgDeclare(llvm::DbgDeclareInst *DbgDeclare);
VariableInfo *AssignValueToOffset(VariableInfoMap *VarInfoMap,
llvm::DIVariable *Var, llvm::Value *Address,
unsigned FragmentIndex,
unsigned FragmentOffsetInBits);
bool IsVariableLive(const VariableInfoMap::value_type &VarAndInfo,
const llvm::DIScope *S, const llvm::DebugLoc &DL);
};
void dxil_debug_info::LiveVariables::Impl::Init(
IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::Module *pModule) {
m_pMalloc = pMalloc;
m_pDxilDebugInfo = pDxilDebugInfo;
m_pModule = pModule;
llvm::Function *DbgDeclareFn =
llvm::Intrinsic::getDeclaration(m_pModule, llvm::Intrinsic::dbg_declare);
for (llvm::User *U : DbgDeclareFn->users()) {
if (auto *DbgDeclare = llvm::dyn_cast<llvm::DbgDeclareInst>(U)) {
Init_DbgDeclare(DbgDeclare);
}
}
}
void dxil_debug_info::LiveVariables::Impl::Init_DbgDeclare(
llvm::DbgDeclareInst *DbgDeclare) {
llvm::Value *Address = DbgDeclare->getAddress();
auto *Variable = DbgDeclare->getVariable();
auto *Expression = DbgDeclare->getExpression();
if (Address == nullptr || Variable == nullptr || Expression == nullptr) {
return;
}
auto *AddressAsAlloca = llvm::dyn_cast<llvm::AllocaInst>(Address);
if (AddressAsAlloca == nullptr) {
return;
}
auto S = UniqueScopeForInlinedFunctions::Create(DbgDeclare->getDebugLoc(),
Variable->getScope());
if (!S.Valid()) {
return;
}
auto Iter = CreateMemberIterator(DbgDeclare, m_pModule->getDataLayout(),
AddressAsAlloca, Expression);
if (!Iter) {
// MemberIterator creation failure, this skip this var.
return;
}
VariableInfoMap *LiveVarInfoMap;
if (Variable->getName().startswith("global.")) {
LiveVarInfoMap = &m_LiveGlobalVarsDbgDeclare;
} else {
LiveVarInfoMap = &m_LiveVarsDbgDeclare[S];
}
unsigned FragmentIndex;
while (Iter->Next(&FragmentIndex)) {
const unsigned FragmentSizeInBits = Iter->SizeInBits(FragmentIndex);
const unsigned FragmentOffsetInBits = Iter->OffsetInBits(FragmentIndex);
VariableInfo *VarInfo = AssignValueToOffset(
LiveVarInfoMap, Variable, Address, FragmentIndex, FragmentOffsetInBits);
// SROA can split structs so that multiple allocas back the same variable.
// In this case the expression will be empty
if (Expression->getNumElements() != 0) {
ValidateDbgDeclare(VarInfo, FragmentSizeInBits, FragmentOffsetInBits);
}
}
}
dxil_debug_info::VariableInfo *
dxil_debug_info::LiveVariables::Impl::AssignValueToOffset(
VariableInfoMap *VarInfoMap, llvm::DIVariable *Variable,
llvm::Value *Address, unsigned FragmentIndex,
unsigned FragmentOffsetInBits) {
// FragmentIndex is the index within the alloca'd value
// FragmentOffsetInBits is the offset within the HLSL variable
// that maps to Address[FragmentIndex]
auto it = VarInfoMap->find(Variable);
if (it == VarInfoMap->end()) {
auto InsertIt =
VarInfoMap->emplace(Variable, std::make_unique<VariableInfo>(Variable));
assert(InsertIt.second);
it = InsertIt.first;
}
auto *VarInfo = it->second.get();
auto &FragmentLocation = VarInfo->m_ValueLocationMap[FragmentOffsetInBits];
FragmentLocation.m_V = Address;
FragmentLocation.m_FragmentIndex = FragmentIndex;
return VarInfo;
}
dxil_debug_info::LiveVariables::LiveVariables() = default;
dxil_debug_info::LiveVariables::~LiveVariables() = default;
HRESULT
dxil_debug_info::LiveVariables::Init(DxcPixDxilDebugInfo *pDxilDebugInfo) {
Clear();
m_pImpl->Init(pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo,
pDxilDebugInfo->GetModuleRef());
return S_OK;
}
void dxil_debug_info::LiveVariables::Clear() {
m_pImpl.reset(new dxil_debug_info::LiveVariables::Impl());
}
HRESULT dxil_debug_info::LiveVariables::GetLiveVariablesAtInstruction(
llvm::Instruction *IP, IDxcPixDxilLiveVariables **ppResult) const {
DXASSERT(IP != nullptr, "else IP should not be nullptr");
DXASSERT(ppResult != nullptr, "else Result should not be nullptr");
std::vector<const VariableInfo *> LiveVars;
std::set<std::string> LiveVarsName;
const llvm::DebugLoc &DL = IP->getDebugLoc();
if (!DL) {
return E_FAIL;
}
auto S = UniqueScopeForInlinedFunctions::Create(DL, DL->getScope());
if (!S.Valid()) {
return E_FAIL;
}
while (S.Valid()) {
auto it = m_pImpl->m_LiveVarsDbgDeclare.find(S);
if (it != m_pImpl->m_LiveVarsDbgDeclare.end()) {
for (const auto &VarAndInfo : it->second) {
auto *Var = VarAndInfo.first;
llvm::StringRef VarName = Var->getName();
if (Var->getLine() > DL.getLine()) {
// Defined later in the HLSL source.
continue;
}
if (VarName.empty()) {
// No name?...
continue;
}
if (!LiveVarsName.insert(VarAndInfo.first->getName()).second) {
// There's a variable with the same name; use the
// previous one instead.
return false;
}
LiveVars.emplace_back(VarAndInfo.second.get());
}
}
S.AscendScopeHierarchy();
}
for (const auto &VarAndInfo : m_pImpl->m_LiveGlobalVarsDbgDeclare) {
// Only consider references to the global variable that are in the same
// function as the instruction.
if (hlsl::dxilutil::DemangleFunctionName(
IP->getParent()->getParent()->getName()) ==
VarAndInfo.first->getScope()->getName()) {
if (!LiveVarsName.insert(VarAndInfo.first->getName()).second) {
// There shouldn't ever be a global variable with the same
// name, but it doesn't hurt to check
continue;
}
LiveVars.emplace_back(VarAndInfo.second.get());
}
}
return CreateDxilLiveVariables(m_pImpl->m_pDxilDebugInfo, std::move(LiveVars),
ppResult);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixDxilDebugInfo.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixDxilDebugInfo.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines the main class for dxcompiler's API for PIX support. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/exception.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "DxcPixBase.h"
#include "DxcPixDxilDebugInfo.h"
#include "DxcPixLiveVariables.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
STDMETHODIMP dxil_debug_info::DxcPixDxilDebugInfo::GetLiveVariablesAt(
DWORD InstructionOffset, IDxcPixDxilLiveVariables **ppLiveVariables) {
return m_LiveVars->GetLiveVariablesAtInstruction(
FindInstruction(InstructionOffset), ppLiveVariables);
}
STDMETHODIMP dxil_debug_info::DxcPixDxilDebugInfo::IsVariableInRegister(
DWORD InstructionOffset, const wchar_t *VariableName) {
return S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilDebugInfo::GetFunctionName(DWORD InstructionOffset,
BSTR *ppFunctionName) {
llvm::Instruction *IP = FindInstruction(InstructionOffset);
const llvm::DITypeIdentifierMap EmptyMap;
if (const llvm::DebugLoc &DL = IP->getDebugLoc()) {
auto *S = llvm::dyn_cast<llvm::DIScope>(DL.getScope());
while (S != nullptr && !llvm::isa<llvm::DICompileUnit>(S)) {
if (auto *SS = llvm::dyn_cast<llvm::DISubprogram>(S)) {
*ppFunctionName = CComBSTR(CA2W(SS->getName().data())).Detach();
return S_OK;
}
S = S->getScope().resolve(EmptyMap);
}
}
*ppFunctionName = CComBSTR(L"<\?\?\?>").Detach();
return S_FALSE;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilDebugInfo::GetStackDepth(DWORD InstructionOffset,
DWORD *StackDepth) {
llvm::Instruction *IP = FindInstruction(InstructionOffset);
DWORD Depth = 0;
llvm::DebugLoc DL = IP->getDebugLoc();
while (DL && DL.getInlinedAtScope() != nullptr) {
DL = DL.getInlinedAt();
++Depth;
}
*StackDepth = Depth;
return S_OK;
}
#include "DxilDiaSession.h"
dxil_debug_info::DxcPixDxilDebugInfo::DxcPixDxilDebugInfo(
IMalloc *pMalloc, dxil_dia::Session *pSession)
: m_pMalloc(pMalloc), m_pSession(pSession),
m_LiveVars(new LiveVariables()) {
m_LiveVars->Init(this);
}
dxil_debug_info::DxcPixDxilDebugInfo::~DxcPixDxilDebugInfo() = default;
llvm::Module *dxil_debug_info::DxcPixDxilDebugInfo::GetModuleRef() {
return &m_pSession->ModuleRef();
}
llvm::Instruction *dxil_debug_info::DxcPixDxilDebugInfo::FindInstruction(
DWORD InstructionOffset) const {
const auto &Instructions = m_pSession->InstructionsRef();
auto it = Instructions.find(InstructionOffset);
if (it == Instructions.end()) {
throw hlsl::Exception(E_BOUNDS, "Out-of-bounds: Instruction offset");
}
return const_cast<llvm::Instruction *>(it->second);
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilDebugInfo::InstructionOffsetsFromSourceLocation(
const wchar_t *FileName, DWORD SourceLine, DWORD SourceColumn,
IDxcPixDxilInstructionOffsets **ppOffsets) {
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilInstructionOffsets>(
ppOffsets, m_pMalloc, m_pSession, FileName, SourceLine, SourceColumn);
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilDebugInfo::SourceLocationsFromInstructionOffset(
DWORD InstructionOffset, IDxcPixDxilSourceLocations **ppSourceLocations) {
llvm::Instruction *IP = FindInstruction(InstructionOffset);
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilSourceLocations>(ppSourceLocations, m_pMalloc,
m_pSession, IP);
}
static bool CompareFilenames(const wchar_t *l, const char *r) {
while (*l && *r) {
bool theSame = false;
if (*l == L'/' && *r == '\\') {
theSame = true;
}
if (*l == L'\\' && *r == '/') {
theSame = true;
}
if (!theSame) {
if (::tolower(*l) != ::tolower(*r)) {
return false;
}
}
l++;
r++;
}
if (*l || *r) {
return false;
}
return true;
}
dxil_debug_info::DxcPixDxilInstructionOffsets::DxcPixDxilInstructionOffsets(
IMalloc *pMalloc, dxil_dia::Session *pSession, const wchar_t *FileName,
DWORD SourceLine, DWORD SourceColumn) {
assert(SourceColumn == 0);
(void)SourceColumn;
for (llvm::Function &Fn :
pSession->DxilModuleRef().GetModule()->functions()) {
if (Fn.isDeclaration() || Fn.isIntrinsic() || hlsl::OP::IsDxilOpFunc(&Fn))
continue;
auto &Blocks = Fn.getBasicBlockList();
for (auto &CurrentBlock : Blocks) {
auto &Is = CurrentBlock.getInstList();
for (auto &Inst : Is) {
auto &debugLoc = Inst.getDebugLoc();
if (debugLoc) {
unsigned line = debugLoc.getLine();
if (line == SourceLine) {
auto file = debugLoc.get()->getFilename();
if (CompareFilenames(FileName, file.str().c_str())) {
std::uint32_t InstructionNumber;
if (pix_dxil::PixDxilInstNum::FromInst(&Inst,
&InstructionNumber)) {
m_offsets.push_back(InstructionNumber);
}
}
}
}
}
}
}
}
DWORD dxil_debug_info::DxcPixDxilInstructionOffsets::GetCount() {
return static_cast<DWORD>(m_offsets.size());
}
DWORD dxil_debug_info::DxcPixDxilInstructionOffsets::GetOffsetByIndex(
DWORD Index) {
if (Index < static_cast<DWORD>(m_offsets.size())) {
return m_offsets[Index];
}
return static_cast<DWORD>(-1);
}
dxil_debug_info::DxcPixDxilSourceLocations::DxcPixDxilSourceLocations(
IMalloc *pMalloc, dxil_dia::Session *pSession, llvm::Instruction *IP) {
const llvm::DITypeIdentifierMap EmptyMap;
if (const llvm::DebugLoc &DL = IP->getDebugLoc()) {
auto *S = llvm::dyn_cast<llvm::DIScope>(DL.getScope());
while (S != nullptr && !llvm::isa<llvm::DIFile>(S)) {
if (auto Namespace = llvm::dyn_cast<llvm::DINamespace>(S)) {
// DINamespace has a getScope member (that hides DIScope's)
// that returns a DIScope directly, but if that namespace
// is at file-level scope, it will return nullptr.
if (auto *ContainingScope = Namespace->getScope())
S = ContainingScope;
else
S = S->getFile();
} else if (auto Subprogram = llvm::dyn_cast<llvm::DISubprogram>(S)) {
S = Subprogram->getFile();
} else
S = S->getScope().resolve(EmptyMap);
}
if (S != nullptr) {
Location loc;
loc.Line = DL->getLine();
loc.Column = DL->getColumn();
loc.Filename = CA2W(S->getFilename().data());
m_locations.emplace_back(std::move(loc));
}
}
}
STDMETHODIMP_(DWORD) dxil_debug_info::DxcPixDxilSourceLocations::GetCount() {
return static_cast<DWORD>(m_locations.size());
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilSourceLocations::GetFileNameByIndex(DWORD Index,
BSTR *Name) {
if (Index >= static_cast<DWORD>(m_locations.size())) {
return E_BOUNDS;
}
*Name = m_locations[Index].Filename.Copy();
return S_OK;
}
STDMETHODIMP_(DWORD)
dxil_debug_info::DxcPixDxilSourceLocations::GetColumnByIndex(DWORD Index) {
if (Index >= static_cast<DWORD>(m_locations.size())) {
return E_BOUNDS;
}
return m_locations[Index].Column;
}
STDMETHODIMP_(DWORD)
dxil_debug_info::DxcPixDxilSourceLocations::GetLineNumberByIndex(DWORD Index) {
if (Index >= static_cast<DWORD>(m_locations.size())) {
return E_BOUNDS;
}
return m_locations[Index].Line;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableLineNumbers.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableLineNumbers.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <vector>
#include "dia2.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Instruction.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class LineNumber : public IDiaLineNumber {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<Session> m_pSession;
const llvm::Instruction *m_inst;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
STDMETHODIMP QueryInterface(REFIID iid, void **ppvObject) override {
return DoBasicQueryInterface<IDiaLineNumber>(this, iid, ppvObject);
}
LineNumber(
/* [in] */ IMalloc *pMalloc,
/* [in] */ Session *pSession,
/* [in] */ const llvm::Instruction *inst);
const llvm::DebugLoc &DL() const;
const llvm::Instruction *Inst() const { return m_inst; }
STDMETHODIMP get_compiland(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_sourceFile(
/* [retval][out] */ IDiaSourceFile **pRetVal) override;
STDMETHODIMP get_lineNumber(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_lineNumberEnd(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_columnNumber(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_columnNumberEnd(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_addressSection(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_addressOffset(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_relativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_virtualAddress(
/* [retval][out] */ ULONGLONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_length(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_sourceFileId(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_statement(
/* [retval][out] */ BOOL *pRetVal) override;
STDMETHODIMP get_compilandId(
/* [retval][out] */ DWORD *pRetVal) override;
};
class LineNumbersTable
: public impl::TableBase<IDiaEnumLineNumbers, IDiaLineNumber> {
public:
LineNumbersTable(
/* [in] */ IMalloc *pMalloc,
/* [in] */ Session *pSession);
LineNumbersTable(
/* [in] */ IMalloc *pMalloc,
/* [in] */ Session *pSession,
/* [in] */ std::vector<const llvm::Instruction *> &&instructions);
HRESULT GetItem(
/* [in] */ DWORD index,
/* [out] */ IDiaLineNumber **ppItem) override;
private:
// Keep a reference to the instructions that contain the line numbers.
const std::vector<const llvm::Instruction *> &m_instructions;
// Provide storage space for instructions for when the table contains
// a subset of all instructions.
std::vector<const llvm::Instruction *> m_instructionsStorage;
};
} // namespace dxil_dia |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSymbols.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSymbols.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableSymbols.h"
#include <comdef.h>
#include "dxc/Support/Unicode.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_os_ostream.h"
#include "DxilDiaSession.h"
dxil_dia::Symbol::~Symbol() = default;
void dxil_dia::Symbol::Init(Session *pSession, DWORD ID, DWORD symTag) {
DXASSERT_ARGS(m_pSession == nullptr, "Double init on symbol %d", ID);
m_pSession = pSession;
m_ID = ID;
m_symTag = symTag;
}
STDMETHODIMP dxil_dia::Symbol::get_symIndexId(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = m_ID;
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_symTag(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = m_symTag;
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_name(
/* [retval][out] */ BSTR *pRetVal) {
DxcThreadMalloc TM(m_pSession->GetMallocNoRef());
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = nullptr;
if (!m_hasName) {
return S_FALSE;
}
return m_name.CopyTo(pRetVal);
}
STDMETHODIMP dxil_dia::Symbol::get_lexicalParent(
/* [retval][out] */ IDiaSymbol **pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = nullptr;
DWORD dwParentID = this->m_lexicalParent;
if (dwParentID == 0) {
return S_FALSE;
}
Symbol *pParent;
IFR(m_pSession->SymMgr().GetSymbolByID(dwParentID, &pParent));
*pRetVal = pParent;
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_type(
/* [retval][out] */ IDiaSymbol **pRetVal) {
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_dataKind(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
if (!m_hasDataKind) {
return S_FALSE;
}
*pRetVal = m_dataKind;
return m_dataKind ? S_OK : S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_locationType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = LocIsNull;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_sourceFileName(
/* [retval][out] */ BSTR *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = nullptr;
if (!m_hasSourceFileName) {
return S_FALSE;
}
*pRetVal = m_sourceFileName.Copy();
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_value(
/* [retval][out] */ VARIANT *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
ZeroMemory(pRetVal, sizeof(*pRetVal));
if (!m_hasValue) {
return S_FALSE;
}
return VariantCopy(pRetVal, &m_value);
}
STDMETHODIMP dxil_dia::Symbol::get_baseType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal != nullptr) {
return E_INVALIDARG;
}
*pRetVal = btNoType;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_count(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_offset(
/* [retval][out] */ LONG *pRetVal) {
if (pRetVal != nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_length(
/* [retval][out] */ ULONGLONG *pRetVal) {
if (pRetVal != nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_lexicalParentId(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
if (!m_hasLexicalParent) {
return S_FALSE;
}
*pRetVal = m_lexicalParent;
return S_OK;
}
void dxil_dia::SymbolChildrenEnumerator::Init(
std::vector<CComPtr<Symbol>> &&syms) {
std::swap(syms, m_symbols);
m_pos = m_symbols.begin();
}
HRESULT STDMETHODCALLTYPE dxil_dia::SymbolChildrenEnumerator::get_Count(
/* [retval][out] */ LONG *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = m_symbols.size();
return S_OK;
}
HRESULT STDMETHODCALLTYPE dxil_dia::SymbolChildrenEnumerator::Item(
/* [in] */ DWORD index,
/* [retval][out] */ IDiaSymbol **symbol) {
if (symbol == nullptr) {
return E_INVALIDARG;
}
*symbol = nullptr;
if (index < 0 || index > m_symbols.size()) {
return E_INVALIDARG;
}
*symbol = m_symbols[index];
(*symbol)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE dxil_dia::SymbolChildrenEnumerator::Reset(void) {
m_pos = m_symbols.begin();
return S_OK;
}
HRESULT STDMETHODCALLTYPE dxil_dia::SymbolChildrenEnumerator::Next(
/* [in] */ ULONG celt,
/* [out] */ IDiaSymbol **rgelt,
/* [out] */ ULONG *pceltFetched) {
DxcThreadMalloc TM(m_pMalloc);
if (rgelt == nullptr || pceltFetched == nullptr) {
return E_INVALIDARG;
}
*pceltFetched = 0;
ZeroMemory(rgelt, sizeof(*rgelt) * celt);
for (; *pceltFetched < celt && m_pos != m_symbols.end();
++m_pos, ++rgelt, ++(*pceltFetched)) {
*rgelt = *m_pos;
(*rgelt)->AddRef();
}
return (*pceltFetched == celt) ? S_OK : S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::findChildren(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) {
return findChildrenEx(symtag, name, compareFlags, ppResult);
;
}
STDMETHODIMP dxil_dia::Symbol::findChildrenEx(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) {
DxcThreadMalloc TM(m_pMalloc);
if (ppResult == nullptr) {
return E_INVALIDARG;
}
*ppResult = nullptr;
CComPtr<SymbolChildrenEnumerator> ret =
SymbolChildrenEnumerator::Alloc(m_pMalloc);
if (!ret) {
return E_OUTOFMEMORY;
}
std::vector<CComPtr<Symbol>> children;
IFR(GetChildren(&children));
if (symtag != SymTagNull) {
std::vector<CComPtr<Symbol>> tmp;
tmp.reserve(children.size());
for (const auto &c : children) {
if (c->m_symTag == symtag) {
tmp.emplace_back(c);
}
}
std::swap(tmp, children);
}
if (name != nullptr && compareFlags != nsNone) {
std::vector<CComPtr<Symbol>> tmp;
tmp.reserve(children.size());
for (const auto &c : children) {
CComBSTR cName;
IFR(c->get_name(&cName));
// Careful with the string comparison function we use as it can make us
// pull in new dependencies CompareStringOrdinal lives in kernel32.dll
if (CompareStringOrdinal(cName, cName.Length(), name, -1,
(BOOL)(compareFlags == nsfCaseInsensitive)) !=
CSTR_EQUAL) {
continue;
}
if (c->m_symTag == symtag) {
tmp.emplace_back(c);
}
}
std::swap(tmp, children);
}
ret->Init(std::move(children));
*ppResult = ret.Detach();
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_isAggregated(
/* [retval][out] */ BOOL *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = false;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_registerType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_sizeInUdt(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_liveRangeStartAddressOffset(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
SymbolManager::LiveRange LR;
IFR(m_pSession->SymMgr().GetLiveRangeOf(this, &LR));
*pRetVal = LR.Start;
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_liveRangeLength(
/* [retval][out] */ ULONGLONG *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
SymbolManager::LiveRange LR;
IFR(m_pSession->SymMgr().GetLiveRangeOf(this, &LR));
*pRetVal = LR.Length;
return S_OK;
}
STDMETHODIMP dxil_dia::Symbol::get_offsetInUdt(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_numericProperties(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ DWORD *pProperties) {
if (pcnt == nullptr || pProperties == nullptr) {
return E_INVALIDARG;
}
ZeroMemory(pProperties, sizeof(*pProperties) * cnt);
*pcnt = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_numberOfRegisterIndices(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Symbol::get_isHLSLData(
/* [retval][out] */ BOOL *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = false;
if (!m_hasIsHLSLData) {
return S_FALSE;
}
*pRetVal = m_isHLSLData;
return S_OK;
}
dxil_dia::SymbolsTable::SymbolsTable(IMalloc *pMalloc, Session *pSession)
: impl::TableBase<IDiaEnumSymbols, IDiaSymbol>(pMalloc, pSession,
Table::Kind::Symbols) {
m_count = pSession->SymMgr().NumSymbols();
}
HRESULT dxil_dia::SymbolsTable::GetItem(DWORD index, IDiaSymbol **ppItem) {
if (ppItem == nullptr) {
return E_INVALIDARG;
}
*ppItem = nullptr;
Symbol *ret = nullptr;
const DWORD dwSymID = index + 1;
IFR(m_pSession->SymMgr().GetSymbolByID(dwSymID, &ret));
*ppItem = ret;
return S_OK;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixCompilationInfo.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixCompilationInfo.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Retrieves compilation info such as HLSL entry point, macro defs, etc. //
// from llvm debug metadata //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <map>
#include <memory>
#include <vector>
namespace dxil_debug_info {
HRESULT
CreateDxilCompilationInfo(IMalloc *pMalloc, dxil_dia::Session *pSession,
IDxcPixCompilationInfo **ppResult);
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSourceFiles.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSourceFiles.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableSourceFiles.h"
#include "DxilDiaSession.h"
dxil_dia::SourceFile::SourceFile(IMalloc *pMalloc, Session *pSession,
DWORD index)
: m_pMalloc(pMalloc), m_pSession(pSession), m_index(index) {}
llvm::MDTuple *dxil_dia::SourceFile::NameContent() const {
return llvm::cast<llvm::MDTuple>(m_pSession->Contents()->getOperand(m_index));
}
llvm::StringRef dxil_dia::SourceFile::Name() const {
return llvm::dyn_cast<llvm::MDString>(NameContent()->getOperand(0))
->getString();
}
STDMETHODIMP dxil_dia::SourceFile::get_uniqueId(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = m_index;
return S_OK;
}
STDMETHODIMP dxil_dia::SourceFile::get_fileName(
/* [retval][out] */ BSTR *pRetVal) {
DxcThreadMalloc TM(m_pMalloc);
return StringRefToBSTR(Name(), pRetVal);
}
dxil_dia::SourceFilesTable::SourceFilesTable(IMalloc *pMalloc,
Session *pSession)
: impl::TableBase<IDiaEnumSourceFiles, IDiaSourceFile>(
pMalloc, pSession, Table::Kind::SourceFiles) {
m_count = (m_pSession->Contents() == nullptr)
? 0
: m_pSession->Contents()->getNumOperands();
m_items.assign(m_count, nullptr);
}
dxil_dia::SourceFilesTable::SourceFilesTable(
IMalloc *pMalloc, Session *pSession,
std::vector<CComPtr<IDiaSourceFile>> &&items)
: impl::TableBase<IDiaEnumSourceFiles, IDiaSourceFile>(
pMalloc, pSession, Table::Kind::SourceFiles),
m_items(std::move(items)) {
m_count = m_items.size();
}
HRESULT dxil_dia::SourceFilesTable::GetItem(DWORD index,
IDiaSourceFile **ppItem) {
if (!m_items[index]) {
m_items[index] = CreateOnMalloc<SourceFile>(m_pMalloc, m_pSession, index);
if (m_items[index] == nullptr)
return E_OUTOFMEMORY;
}
m_items[index].p->AddRef();
*ppItem = m_items[index];
(*ppItem)->AddRef();
return S_OK;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixDxilStorage.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixDxilStorage.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines the DxcPixDxilStorage API. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxcPixDxilStorage.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/Support/WinIncludes.h"
#include "llvm/IR/Instructions.h"
#include "DxcPixBase.h"
#include "DxcPixLiveVariables.h"
#include "DxcPixTypes.h"
#include "DxilDiaSession.h"
static HRESULT UnAliasType(IDxcPixType *MaybeAlias,
IDxcPixType **OriginalType) {
CComPtr<IDxcPixType> Tmp(MaybeAlias);
HRESULT hr = E_FAIL;
*OriginalType = nullptr;
do {
CComPtr<IDxcPixType> Other;
hr = Tmp->UnAlias(&Other);
IFR(hr);
if (hr == S_FALSE) {
break;
}
Tmp = Other;
} while (true);
*OriginalType = Tmp.Detach();
return S_OK;
}
HRESULT CreateDxcPixStorageImpl(
dxil_debug_info::DxcPixDxilDebugInfo *pDxilDebugInfo,
IDxcPixType *OriginalType, const dxil_debug_info::VariableInfo *VarInfo,
unsigned CurrentOffsetInBits, IDxcPixDxilStorage **ppStorage) {
CComPtr<IDxcPixArrayType> ArrayTy;
CComPtr<IDxcPixStructType2> StructTy;
CComPtr<IDxcPixScalarType> ScalarTy;
CComPtr<IDxcPixType> UnalisedType;
IFR(UnAliasType(OriginalType, &UnalisedType));
if (UnalisedType->QueryInterface(&ArrayTy) == S_OK) {
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilArrayStorage>(
ppStorage, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo,
OriginalType, ArrayTy, VarInfo, CurrentOffsetInBits);
} else if (UnalisedType->QueryInterface(&StructTy) == S_OK) {
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilStructStorage>(
ppStorage, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo,
OriginalType, StructTy, VarInfo, CurrentOffsetInBits);
} else if (UnalisedType->QueryInterface(&ScalarTy) == S_OK) {
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilScalarStorage>(
ppStorage, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo,
OriginalType, ScalarTy, VarInfo, CurrentOffsetInBits);
}
return E_UNEXPECTED;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilArrayStorage::AccessField(
LPCWSTR Name, IDxcPixDxilStorage **ppResult) {
return E_FAIL;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilArrayStorage::Index(DWORD Index,
IDxcPixDxilStorage **ppResult) {
CComPtr<IDxcPixType> IndexedType;
IFR(m_pType->GetIndexedType(&IndexedType));
DWORD NumElements;
IFR(m_pType->GetNumElements(&NumElements));
if (Index >= NumElements) {
return E_BOUNDS;
}
DWORD IndexedTypeSizeInBits;
IFR(IndexedType->GetSizeInBits(&IndexedTypeSizeInBits));
const unsigned NewOffsetInBits =
m_OffsetFromStorageStartInBits + Index * IndexedTypeSizeInBits;
return CreateDxcPixStorageImpl(m_pDxilDebugInfo, IndexedType, m_pVarInfo,
NewOffsetInBits, ppResult);
}
STDMETHODIMP dxil_debug_info::DxcPixDxilArrayStorage::GetRegisterNumber(
DWORD *pRegisterNumber) {
return E_FAIL;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilArrayStorage::GetIsAlive() {
for (auto OffsetAndRegister : m_pVarInfo->m_ValueLocationMap) {
if (OffsetAndRegister.second.m_V != nullptr) {
return S_OK;
}
}
return E_FAIL;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilArrayStorage::GetType(IDxcPixType **ppType) {
*ppType = m_pOriginalType;
(*ppType)->AddRef();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilStructStorage::AccessField(
LPCWSTR Name, IDxcPixDxilStorage **ppResult) {
DWORD FieldOffsetInBits = 0;
CComPtr<IDxcPixType> FieldType;
if (*Name != 0) {
CComPtr<IDxcPixStructField> Field;
IFR(m_pType->GetFieldByName(Name, &Field));
IFR(Field->GetType(&FieldType));
IFR(Field->GetOffsetInBits(&FieldOffsetInBits));
} else {
IFR(m_pType->GetBaseType(&FieldType));
}
const unsigned NewOffsetInBits =
m_OffsetFromStorageStartInBits + FieldOffsetInBits;
return CreateDxcPixStorageImpl(m_pDxilDebugInfo, FieldType, m_pVarInfo,
NewOffsetInBits, ppResult);
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilStructStorage::Index(DWORD Index,
IDxcPixDxilStorage **ppResult) {
return E_FAIL;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilStructStorage::GetRegisterNumber(
DWORD *pRegisterNumber) {
return E_FAIL;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilStructStorage::GetIsAlive() {
for (auto OffsetAndRegister : m_pVarInfo->m_ValueLocationMap) {
if (OffsetAndRegister.second.m_V != nullptr) {
return S_OK;
}
}
return E_FAIL;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilStructStorage::GetType(IDxcPixType **ppType) {
*ppType = m_pOriginalType;
(*ppType)->AddRef();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilScalarStorage::AccessField(
LPCWSTR Name, IDxcPixDxilStorage **ppResult) {
return E_FAIL;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilScalarStorage::Index(DWORD Index,
IDxcPixDxilStorage **ppResult) {
return E_FAIL;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilScalarStorage::GetRegisterNumber(
DWORD *pRegisterNumber) {
const auto &ValueLocationMap = m_pVarInfo->m_ValueLocationMap;
auto RegIt = ValueLocationMap.find(m_OffsetFromStorageStartInBits);
if (RegIt == ValueLocationMap.end()) {
return E_FAIL;
}
if (auto *AllocaReg = llvm::dyn_cast<llvm::AllocaInst>(RegIt->second.m_V)) {
uint32_t RegNum;
uint32_t RegSize;
if (!pix_dxil::PixAllocaReg::FromInst(AllocaReg, &RegNum, &RegSize)) {
return E_FAIL;
}
*pRegisterNumber = RegNum + RegIt->second.m_FragmentIndex;
} else {
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilScalarStorage::GetIsAlive() {
const auto &ValueLocationMap = m_pVarInfo->m_ValueLocationMap;
auto RegIt = ValueLocationMap.find(m_OffsetFromStorageStartInBits);
return RegIt == ValueLocationMap.end() ? E_FAIL : S_OK;
}
STDMETHODIMP
dxil_debug_info::DxcPixDxilScalarStorage::GetType(IDxcPixType **ppType) {
*ppType = m_pOriginalType;
(*ppType)->AddRef();
return S_OK;
}
HRESULT dxil_debug_info::CreateDxcPixStorage(
DxcPixDxilDebugInfo *pDxilDebugInfo, llvm::DIType *diType,
const VariableInfo *VarInfo, unsigned CurrentOffsetInBits,
IDxcPixDxilStorage **ppStorage) {
CComPtr<IDxcPixType> OriginalType;
IFR(dxil_debug_info::CreateDxcPixType(pDxilDebugInfo, diType, &OriginalType));
return CreateDxcPixStorageImpl(pDxilDebugInfo, OriginalType, VarInfo,
CurrentOffsetInBits, ppStorage);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixDxilStorage.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixDxilStorage.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Declares the DxcPixDxilStorage API. This is the API that allows PIX to //
// find which register holds the value for a particular member of a //
// variable. //
// //
// For DxcPixDxilStorage, a member is a DIBasicType (i.e., float, int, etc.) //
// This library provides Storage classes for inspecting structs, arrays, and //
// basic types. This is what's minimally necessary for enable HLSL debugging //
// in PIX. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcpix.h"
#include "dxc/Support/microcom.h"
#include "DxcPixDxilDebugInfo.h"
namespace llvm {
class DIType;
} // namespace llvm
namespace dxil_debug_info {
struct VariableInfo;
HRESULT CreateDxcPixStorage(DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIType *diType, const VariableInfo *VarInfo,
unsigned CurrentOffsetInBits,
IDxcPixDxilStorage **ppStorage);
class DxcPixDxilArrayStorage : public IDxcPixDxilStorage {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
CComPtr<IDxcPixType> m_pOriginalType;
CComPtr<IDxcPixArrayType> m_pType;
VariableInfo const *m_pVarInfo;
unsigned m_OffsetFromStorageStartInBits;
DxcPixDxilArrayStorage(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
IDxcPixType *OriginalType, IDxcPixArrayType *pType,
const VariableInfo *pVarInfo,
unsigned OffsetFromStorageStartInBits)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo),
m_pOriginalType(OriginalType), m_pType(pType), m_pVarInfo(pVarInfo),
m_OffsetFromStorageStartInBits(OffsetFromStorageStartInBits) {}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilArrayStorage)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilStorage>(this, iid, ppvObject);
}
STDMETHODIMP AccessField(LPCWSTR Name,
IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP Index(DWORD Index, IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP GetRegisterNumber(DWORD *pRegisterNumber) override;
STDMETHODIMP GetIsAlive() override;
STDMETHODIMP GetType(IDxcPixType **ppType) override;
};
class DxcPixDxilStructStorage : public IDxcPixDxilStorage {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
CComPtr<IDxcPixType> m_pOriginalType;
CComPtr<IDxcPixStructType2> m_pType;
VariableInfo const *m_pVarInfo;
unsigned m_OffsetFromStorageStartInBits;
DxcPixDxilStructStorage(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
IDxcPixType *OriginalType, IDxcPixStructType2 *pType,
VariableInfo const *pVarInfo,
unsigned OffsetFromStorageStartInBits)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo),
m_pOriginalType(OriginalType), m_pType(pType), m_pVarInfo(pVarInfo),
m_OffsetFromStorageStartInBits(OffsetFromStorageStartInBits) {}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilStructStorage)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilStorage>(this, iid, ppvObject);
}
STDMETHODIMP AccessField(LPCWSTR Name,
IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP Index(DWORD Index, IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP GetRegisterNumber(DWORD *pRegisterNumber) override;
STDMETHODIMP GetIsAlive() override;
STDMETHODIMP GetType(IDxcPixType **ppType) override;
};
class DxcPixDxilScalarStorage : public IDxcPixDxilStorage {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
CComPtr<IDxcPixType> m_pOriginalType;
CComPtr<IDxcPixScalarType> m_pType;
VariableInfo const *m_pVarInfo;
unsigned m_OffsetFromStorageStartInBits;
DxcPixDxilScalarStorage(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
IDxcPixType *OriginalType, IDxcPixScalarType *pType,
VariableInfo const *pVarInfo,
unsigned OffsetFromStorageStartInBits)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo),
m_pOriginalType(OriginalType), m_pType(pType), m_pVarInfo(pVarInfo),
m_OffsetFromStorageStartInBits(OffsetFromStorageStartInBits) {}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilScalarStorage)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilStorage>(this, iid, ppvObject);
}
STDMETHODIMP AccessField(LPCWSTR Name,
IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP Index(DWORD Index, IDxcPixDxilStorage **ppResult) override;
STDMETHODIMP GetRegisterNumber(DWORD *pRegisterNumber) override;
STDMETHODIMP GetIsAlive() override;
STDMETHODIMP GetType(IDxcPixType **ppType) override;
};
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaSymbolManager.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaSymbolsManager.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <vector>
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/iterator_range.h"
namespace llvm {
class DIDerivedType;
class DILocalVariable;
class DIScope;
class DITemplateTypeParameter;
class DIType;
class Instruction;
} // namespace llvm
namespace dxil_dia {
class Session;
class Symbol;
class SymbolChildrenEnumerator;
class SymbolManager {
public:
struct LiveRange {
unsigned Start;
unsigned Length;
};
class SymbolFactory {
protected:
SymbolFactory(DWORD ID, DWORD ParentID);
DWORD m_ID;
DWORD m_ParentID;
public:
virtual ~SymbolFactory();
virtual HRESULT Create(Session *pSession, Symbol **) = 0;
};
using ScopeToIDMap = llvm::DenseMap<llvm::DIScope *, DWORD>;
using IDToLiveRangeMap = std::unordered_map<DWORD, LiveRange>;
using ParentToChildrenMap = std::unordered_multimap<DWORD, DWORD>;
SymbolManager();
SymbolManager(SymbolManager &&) = default;
SymbolManager &operator=(SymbolManager &&) = default;
~SymbolManager();
void Init(Session *pSes);
size_t NumSymbols() const { return m_symbolCtors.size(); }
HRESULT GetSymbolByID(size_t id, Symbol **ppSym) const;
HRESULT GetLiveRangeOf(Symbol *pSym, LiveRange *LR) const;
HRESULT GetGlobalScope(Symbol **ppSym) const;
HRESULT ChildrenOf(Symbol *pSym,
std::vector<CComPtr<Symbol>> *pChildren) const;
HRESULT DbgScopeOf(const llvm::Instruction *instr,
SymbolChildrenEnumerator **ppRet) const;
private:
HRESULT ChildrenOf(DWORD ID, std::vector<CComPtr<Symbol>> *pChildren) const;
// Not a CComPtr, and not AddRef'd - m_pSession is the owner of this.
Session *m_pSession = nullptr;
// Vector of factories for all symbols in the DXIL module.
std::vector<std::unique_ptr<SymbolFactory>> m_symbolCtors;
// Mapping from scope to its ID.
ScopeToIDMap m_scopeToID;
// Mapping from symbol ID to live range. Globals are live [0, end),
// locals, [first dbg.declare, end of scope)
// TODO: the live range information assumes structured dxil - which should
// hold for non-optimized code - so we need something more robust. For now,
// this is good enough.
IDToLiveRangeMap m_symbolToLiveRange;
ParentToChildrenMap m_parentToChildren;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTable.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTable.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
namespace dxil_dia {
class Session;
namespace Table {
enum class Kind {
Symbols,
SourceFiles,
LineNumbers,
Sections,
SegmentMap,
InjectedSource,
FrameData,
InputAssemblyFile
};
static constexpr Kind FirstKind = Kind::Symbols;
static constexpr Kind LastKind = Kind::InputAssemblyFile;
HRESULT Create(
/* [in] */ Session *pSession,
/* [in] */ Kind kind,
/* [out] */ IDiaTable **ppTable);
} // namespace Table
namespace impl {
template <typename T, typename TItem>
class TableBase : public IDiaTable, public T {
public:
// COM Interfaces do not have virtual destructors; they instead rely on
// AddRef/Release matching calls for managing object lifetimes. This
// template is inherited by the implementing table types (which is fine),
// and it also provides the base implementation of the COM's memory
// management callbacks (which is not fine: once a table goes out of scope
// a method in this class will invoke the object's destructor -- which, being
// non-virtual, will be this class' instead of the derived table's.)
// Therefore, we introduce a virtual destructor.
virtual ~TableBase() {
DXASSERT(m_dwRef == 0, "deleting COM table with active references");
}
protected:
static constexpr LPCWSTR TableNames[] = {
L"Symbols", L"SourceFiles", L"LineNumbers", L"Sections",
L"SegmentMap", L"InjectedSource", L"FrameData", L"InputAssemblyFiles"};
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<Session> m_pSession;
unsigned m_next;
unsigned m_count;
Table::Kind m_kind;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaTable, T, IEnumUnknown>(this, iid,
ppvObject);
}
TableBase(IMalloc *pMalloc, Session *pSession, Table::Kind kind) {
m_pMalloc = pMalloc;
m_pSession = pSession;
m_kind = kind;
m_next = 0;
m_count = 0;
}
// IEnumUnknown implementation.
STDMETHODIMP Next(ULONG celt, IUnknown **rgelt,
ULONG *pceltFetched) override {
DxcThreadMalloc TM(m_pMalloc);
ULONG fetched = 0;
while (fetched < celt && m_next < m_count) {
HRESULT hr = Item(m_next, &rgelt[fetched]);
if (FAILED(hr)) {
return hr; // TODO: this leaks prior tables.
}
++m_next, ++fetched;
}
if (pceltFetched != nullptr)
*pceltFetched = fetched;
return (fetched == celt) ? S_OK : S_FALSE;
}
STDMETHODIMP Skip(ULONG celt) override {
if (celt + m_next <= m_count) {
m_next += celt;
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP Reset(void) override {
m_next = 0;
return S_OK;
}
STDMETHODIMP Clone(IEnumUnknown **ppenum) override { return ENotImpl(); }
// IDiaTable implementation.
STDMETHODIMP get__NewEnum(IUnknown **pRetVal) override { return ENotImpl(); }
STDMETHODIMP get_name(BSTR *pRetVal) override {
*pRetVal = SysAllocString(TableNames[(unsigned)m_kind]);
return (*pRetVal) ? S_OK : E_OUTOFMEMORY;
}
STDMETHODIMP get_Count(LONG *pRetVal) override {
*pRetVal = m_count;
return S_OK;
}
STDMETHODIMP Item(DWORD index, IUnknown **table) override {
if (index >= m_count)
return E_INVALIDARG;
return GetItem(index, (TItem **)table);
}
// T implementation (partial).
STDMETHODIMP Clone(T **ppenum) override {
*ppenum = nullptr;
return ENotImpl();
}
STDMETHODIMP Next(
/* [in] */ ULONG celt,
/* [out] */ TItem **rgelt,
/* [out] */ ULONG *pceltFetched) override {
DxcThreadMalloc TM(m_pMalloc);
ULONG fetched = 0;
while (fetched < celt && m_next < m_count) {
HRESULT hr = GetItem(m_next, &rgelt[fetched]);
if (FAILED(hr)) {
return hr; // TODO: this leaks prior items.
}
++m_next, ++fetched;
}
if (pceltFetched != nullptr)
*pceltFetched = fetched;
return (fetched == celt) ? S_OK : S_FALSE;
}
STDMETHODIMP Item(
/* [in] */ DWORD index,
/* [retval][out] */ TItem **ppItem) override {
DxcThreadMalloc TM(m_pMalloc);
if (index >= m_count)
return E_INVALIDARG;
return GetItem(index, ppItem);
}
virtual HRESULT GetItem(DWORD index, TItem **ppItem) = 0;
};
} // namespace impl
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixCompilationInfo.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixCompilationInfo.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines all of the entrypoints for DXC's PIX interfaces for returning //
// compilation parameters such as target profile, entry point, etc. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcpix.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "DxcPixBase.h"
#include "DxcPixDxilDebugInfo.h"
#include <functional>
#include "dxc/Support/WinIncludes.h"
#include "DxcPixCompilationInfo.h"
#include "DxcPixDxilDebugInfo.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "DxilDiaSession.h"
#include <unordered_map>
namespace dxil_debug_info {
struct CompilationInfo : public IDxcPixCompilationInfo {
private:
DXC_MICROCOM_TM_REF_FIELDS();
dxil_dia::Session *m_pSession;
llvm::NamedMDNode *m_contents;
llvm::NamedMDNode *m_defines;
llvm::NamedMDNode *m_mainFileName;
llvm::NamedMDNode *m_arguments;
public:
CompilationInfo(IMalloc *pMalloc, dxil_dia::Session *pSession);
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL();
DXC_MICROCOM_TM_ALLOC(CompilationInfo);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) final {
return DoBasicQueryInterface<IDxcPixCompilationInfo>(this, iid, ppvObject);
}
virtual STDMETHODIMP GetSourceFile(DWORD SourceFileOrdinal, BSTR *pSourceName,
BSTR *pSourceContents) override;
virtual STDMETHODIMP GetArguments(BSTR *pArguments) override;
virtual STDMETHODIMP GetMacroDefinitions(BSTR *pMacroDefinitions) override;
virtual STDMETHODIMP GetEntryPointFile(BSTR *pEntryPointFile) override;
virtual STDMETHODIMP GetHlslTarget(BSTR *pHlslTarget) override;
virtual STDMETHODIMP GetEntryPoint(BSTR *pEntryPoint) override;
};
CompilationInfo::CompilationInfo(IMalloc *pMalloc, dxil_dia::Session *pSession)
: m_pMalloc(pMalloc), m_pSession(pSession) {
auto *Module = m_pSession->DxilModuleRef().GetModule();
m_contents =
Module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceContentsMDName);
if (!m_contents)
m_contents = Module->getNamedMetadata("llvm.dbg.contents");
m_defines =
Module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceDefinesMDName);
if (!m_defines)
m_defines = Module->getNamedMetadata("llvm.dbg.defines");
m_mainFileName = Module->getNamedMetadata(
hlsl::DxilMDHelper::kDxilSourceMainFileNameMDName);
if (!m_mainFileName)
m_mainFileName = Module->getNamedMetadata("llvm.dbg.mainFileName");
m_arguments =
Module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceArgsMDName);
if (!m_arguments)
m_arguments = Module->getNamedMetadata("llvm.dbg.args");
}
static void MDStringOperandToBSTR(llvm::MDOperand const &mdOperand,
BSTR *pBStr) {
llvm::StringRef MetadataAsStringRef =
llvm::dyn_cast<llvm::MDString>(mdOperand)->getString();
std::string StringWithTerminator(MetadataAsStringRef.begin(),
MetadataAsStringRef.size());
CA2W cv(StringWithTerminator.c_str());
CComBSTR BStr;
BStr.Append(cv);
BStr.Append(L"\0", 1);
*pBStr = BStr.Detach();
}
STDMETHODIMP
CompilationInfo::GetSourceFile(DWORD SourceFileOrdinal, BSTR *pSourceName,
BSTR *pSourceContents) {
*pSourceName = nullptr;
*pSourceContents = nullptr;
if (SourceFileOrdinal >= m_contents->getNumOperands()) {
return E_INVALIDARG;
}
llvm::MDTuple *FileTuple =
llvm::cast<llvm::MDTuple>(m_contents->getOperand(SourceFileOrdinal));
MDStringOperandToBSTR(FileTuple->getOperand(0), pSourceName);
MDStringOperandToBSTR(FileTuple->getOperand(1), pSourceContents);
return S_OK;
}
STDMETHODIMP CompilationInfo::GetArguments(BSTR *pArguments) {
llvm::MDNode *argsNode = m_arguments->getOperand(0);
// Don't return any arguments that denote things that are returned via
// other methods in this class (and that PIX isn't expecting to see
// in the arguments list):
const char *specialCases[] = {
"/T", "-T", "-D", "/D", "-E", "/E",
};
// Concatenate arguments into one string
CComBSTR pBSTR;
for (llvm::MDNode::op_iterator it = argsNode->op_begin();
it != argsNode->op_end(); ++it) {
llvm::StringRef strRef = llvm::dyn_cast<llvm::MDString>(*it)->getString();
bool skip = false;
bool skipTwice = false;
for (unsigned i = 0; i < _countof(specialCases); i++) {
// It's legal for users to specify, for example, /Emain or /E main:
if (strRef == specialCases[i]) {
skipTwice = true;
skip = true;
break;
} else if (strRef.startswith(specialCases[i])) {
skip = true;
break;
}
}
if (skip) {
if (skipTwice)
++it;
continue;
}
std::string str(strRef.begin(), strRef.size());
CA2W cv(str.c_str());
pBSTR.Append(cv);
pBSTR.Append(L" ", 1);
}
pBSTR.Append(L"\0", 1);
*pArguments = pBSTR.Detach();
return S_OK;
}
STDMETHODIMP CompilationInfo::GetMacroDefinitions(BSTR *pMacroDefinitions) {
llvm::MDNode *definesNode = m_defines->getOperand(0);
// Concatenate definitions into one string separated by spaces
CComBSTR pBSTR;
for (llvm::MDNode::op_iterator it = definesNode->op_begin();
it != definesNode->op_end(); ++it) {
llvm::StringRef strRef = llvm::dyn_cast<llvm::MDString>(*it)->getString();
std::string str(strRef.begin(), strRef.size());
// PIX is expecting quoted strings as the definitions. So if no quotes were
// given, add them now:
auto findEquals = str.find_first_of("=");
if (findEquals != std::string::npos && findEquals + 1 < str.length()) {
std::string definition = str.substr(findEquals + 1);
if (definition.front() != '\"') {
definition.insert(definition.begin(), '\"');
}
if (definition.back() != '\"') {
definition.push_back('\"');
}
std::string name = str.substr(0, findEquals);
str = name + "=" + definition;
}
CA2W cv(str.c_str());
pBSTR.Append(L"-D", 2);
pBSTR.Append(cv);
pBSTR.Append(L" ", 1);
}
pBSTR.Append(L"\0", 1);
*pMacroDefinitions = pBSTR.Detach();
return S_OK;
}
STDMETHODIMP
CompilationInfo::GetEntryPointFile(BSTR *pEntryPointFile) {
llvm::StringRef strRef = llvm::dyn_cast<llvm::MDString>(
m_mainFileName->getOperand(0)->getOperand(0))
->getString();
std::string str(strRef.begin(),
strRef.size()); // To make sure str is null terminated
CA2W cv(str.c_str());
CComBSTR pBSTR;
pBSTR.Append(cv);
*pEntryPointFile = pBSTR.Detach();
return S_OK;
}
STDMETHODIMP
CompilationInfo::GetHlslTarget(BSTR *pHlslTarget) {
CA2W cv(m_pSession->DxilModuleRef().GetShaderModel()->GetName());
CComBSTR pBSTR;
pBSTR.Append(cv);
*pHlslTarget = pBSTR.Detach();
return S_OK;
}
STDMETHODIMP
CompilationInfo::GetEntryPoint(BSTR *pEntryPoint) {
auto name = m_pSession->DxilModuleRef().GetEntryFunctionName();
CA2W cv(name.c_str());
CComBSTR pBSTR;
pBSTR.Append(cv);
*pEntryPoint = pBSTR.Detach();
return S_OK;
}
} // namespace dxil_debug_info
HRESULT
dxil_debug_info::CreateDxilCompilationInfo(IMalloc *pMalloc,
dxil_dia::Session *pSession,
IDxcPixCompilationInfo **ppResult) {
return NewDxcPixDxilDebugInfoObjectOrThrow<CompilationInfo>(ppResult, pMalloc,
pSession);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixVariables.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixVariables.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines DXC's PIX api for exposing llvm::DIVariables. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "dxc/dxcpix.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "DxcPixBase.h"
#include "DxcPixDxilDebugInfo.h"
#include "DxcPixDxilStorage.h"
#include "DxcPixLiveVariables.h"
#include "DxcPixTypes.h"
#include "DxilDiaSession.h"
#include <set>
#include <vector>
namespace dxil_debug_info {
template <typename T> class DxcPixVariable : public IDxcPixVariable {
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
T *m_pVariable;
VariableInfo const *m_pVarInfo;
llvm::DIType *m_pType;
DxcPixVariable(IMalloc *pMalloc, DxcPixDxilDebugInfo *DxilDebugInfo,
T *pVariable, VariableInfo const *pVarInfo)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(DxilDebugInfo),
m_pVariable(pVariable), m_pVarInfo(pVarInfo) {
const llvm::DITypeIdentifierMap EmptyMap;
m_pType = m_pVariable->getType().resolve(EmptyMap);
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixVariable)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixVariable>(this, iid, ppvObject);
}
public:
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetType(IDxcPixType **ppType) override;
STDMETHODIMP GetStorage(IDxcPixDxilStorage **ppStorage) override;
};
} // namespace dxil_debug_info
template <typename T>
STDMETHODIMP dxil_debug_info::DxcPixVariable<T>::GetName(BSTR *Name) {
*Name = CComBSTR(CA2W(m_pVariable->getName().data())).Detach();
return S_OK;
}
template <typename T>
STDMETHODIMP dxil_debug_info::DxcPixVariable<T>::GetType(IDxcPixType **ppType) {
return dxil_debug_info::CreateDxcPixType(m_pDxilDebugInfo, m_pType, ppType);
}
template <typename T>
STDMETHODIMP
dxil_debug_info::DxcPixVariable<T>::GetStorage(IDxcPixDxilStorage **ppStorage) {
const unsigned InitialOffsetInBits = 0;
return CreateDxcPixStorage(m_pDxilDebugInfo, m_pType, m_pVarInfo,
InitialOffsetInBits, ppStorage);
}
namespace dxil_debug_info {
class DxcPixDxilLiveVariables : public IDxcPixDxilLiveVariables {
private:
DXC_MICROCOM_TM_REF_FIELDS();
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
std::vector<const VariableInfo *> m_LiveVars;
DxcPixDxilLiveVariables(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
std::vector<const VariableInfo *> LiveVars)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo),
m_LiveVars(std::move(LiveVars)) {
#ifndef NDEBUG
for (auto VarAndInfo : m_LiveVars) {
assert(llvm::isa<llvm::DIGlobalVariable>(VarAndInfo->m_Variable) ||
llvm::isa<llvm::DILocalVariable>(VarAndInfo->m_Variable));
}
#endif // !NDEBUG
}
STDMETHODIMP CreateDxcPixVariable(IDxcPixVariable **ppVariable,
VariableInfo const *VarInfo) const;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL();
DXC_MICROCOM_TM_ALLOC(DxcPixDxilLiveVariables);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) final {
return DoBasicQueryInterface<IDxcPixDxilLiveVariables>(this, iid,
ppvObject);
}
STDMETHODIMP GetCount(DWORD *dwSize) override;
STDMETHODIMP GetVariableByIndex(DWORD Index,
IDxcPixVariable **ppVariable) override;
STDMETHODIMP GetVariableByName(LPCWSTR Name,
IDxcPixVariable **ppVariable) override;
};
} // namespace dxil_debug_info
STDMETHODIMP dxil_debug_info::DxcPixDxilLiveVariables::GetCount(DWORD *dwSize) {
*dwSize = m_LiveVars.size();
return S_OK;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilLiveVariables::CreateDxcPixVariable(
IDxcPixVariable **ppVariable, VariableInfo const *VarInfo) const {
auto *Var = VarInfo->m_Variable;
if (auto *DILV = llvm::dyn_cast<llvm::DILocalVariable>(Var)) {
return NewDxcPixDxilDebugInfoObjectOrThrow<
DxcPixVariable<llvm::DILocalVariable>>(ppVariable, m_pMalloc,
m_pDxilDebugInfo, DILV, VarInfo);
} else if (auto *DIGV = llvm::dyn_cast<llvm::DIGlobalVariable>(Var)) {
return NewDxcPixDxilDebugInfoObjectOrThrow<
DxcPixVariable<llvm::DIGlobalVariable>>(
ppVariable, m_pMalloc, m_pDxilDebugInfo, DIGV, VarInfo);
}
return E_UNEXPECTED;
}
STDMETHODIMP dxil_debug_info::DxcPixDxilLiveVariables::GetVariableByIndex(
DWORD Index, IDxcPixVariable **ppVariable) {
if (Index >= m_LiveVars.size()) {
return E_BOUNDS;
}
auto *VarInfo = m_LiveVars[Index];
return CreateDxcPixVariable(ppVariable, VarInfo);
}
STDMETHODIMP dxil_debug_info::DxcPixDxilLiveVariables::GetVariableByName(
LPCWSTR Name, IDxcPixVariable **ppVariable) {
std::string name = std::string(CW2A(Name));
for (auto *VarInfo : m_LiveVars) {
auto *Var = VarInfo->m_Variable;
if (Var->getName() == name) {
return CreateDxcPixVariable(ppVariable, VarInfo);
}
}
return E_BOUNDS;
}
HRESULT dxil_debug_info::CreateDxilLiveVariables(
DxcPixDxilDebugInfo *pDxilDebugInfo,
std::vector<const VariableInfo *> &&LiveVariables,
IDxcPixDxilLiveVariables **ppResult) {
return NewDxcPixDxilDebugInfoObjectOrThrow<DxcPixDxilLiveVariables>(
ppResult, pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo,
std::move(LiveVariables));
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSegmentMap.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSegmentMap.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableSegmentMap.h"
#include "DxilDiaSession.h"
dxil_dia::SegmentMapTable::SegmentMapTable(IMalloc *pMalloc, Session *pSession)
: impl::TableBase<IDiaEnumSegments, IDiaSegment>(pMalloc, pSession,
Table::Kind::SegmentMap) {}
HRESULT dxil_dia::SegmentMapTable::GetItem(DWORD index, IDiaSegment **ppItem) {
*ppItem = nullptr;
return E_FAIL;
} |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableInputAssemblyFile.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableInputAssemblyFile.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableInputAssemblyFile.h"
#include "DxilDiaSession.h"
dxil_dia::InputAssemblyFilesTable::InputAssemblyFilesTable(IMalloc *pMalloc,
Session *pSession)
: impl::TableBase<IDiaEnumInputAssemblyFiles, IDiaInputAssemblyFile>(
pMalloc, pSession, Table::Kind::InputAssemblyFile) {}
HRESULT
dxil_dia::InputAssemblyFilesTable::GetItem(DWORD index,
IDiaInputAssemblyFile **ppItem) {
*ppItem = nullptr;
return E_FAIL;
} |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSegmentMap.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSegmentMap.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class SegmentMapTable : public impl::TableBase<IDiaEnumSegments, IDiaSegment> {
public:
SegmentMapTable(IMalloc *pMalloc, Session *pSession);
HRESULT GetItem(DWORD index, IDiaSegment **ppItem) override;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaSymbolManager.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaSymbolsManager.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaSymbolManager.h"
#include <cctype>
#include <functional>
#include <type_traits>
#include <comdef.h>
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/Support/Unicode.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "DxilDiaSession.h"
#include "DxilDiaTableSymbols.h"
static constexpr std::uint32_t kNullSymbolID = 0;
namespace dxil_dia {
namespace hlsl_symbols {
// HLSL Symbol Hierarchy
// ---- ------ ---------
//
// +---------------+
// | Program (EXE) | Global Scope
// +------+--------+
// |
// +--------^-----------+
// | Compiland (Shader) | Compilation Unit
// +--------+-----------+
// |
// +------------+------------+--------+-------+------------+--------------+
// | | | | | | |
// +----^----+ +---^---+ +----^---+ | +---^---+ +----^----+
// +-----^-----+ | Details | | Flags | | Target | | | Entry | |
// Defines | | Arguments | Synthetic Symbols
// +---------+ +-------+ +--------+ | +-------+ +---------+
// +-----------+
// |
// |
// +---------------+------------+----+-----+-------------+-----------+
// | | | | | |
// +-----^-----+ +-----^-----+ +--^--+ +---^--+ +---^--+ +--^--+
// | Function0 | | Function1 | | ... | | UDT0 | | UDT1 | | ... |
// Source Symbols
// +-----+-----+ +-----+-----+ +-----+ +---+--+ +---+--+ +-----+
// | | | |
// +----^----+ +----^----+ +----^----+ +----^----+
// | Locals0 | | Locals1 | | Fields0 | | Fields1 |
// +---------+ +---------+ +---------+ +---------+
static const std::string &DxilEntryName(Session *pSession);
template <
typename S, typename... C,
typename = typename std::enable_if<!std::is_same<Symbol, S>::value>::type>
HRESULT AllocAndInit(IMalloc *pMalloc, Session *pSession, DWORD dwIndex,
DWORD dwSymTag, S **ppSymbol, C... ctorArgs) {
*ppSymbol = S::Alloc(pMalloc, ctorArgs...);
if (*ppSymbol == nullptr) {
return E_OUTOFMEMORY;
}
(*ppSymbol)->AddRef();
(*ppSymbol)->Init(pSession, dwIndex, dwSymTag);
return S_OK;
}
template <typename T, typename R> T *dyn_cast_to_ditype(R ref) {
return llvm::dyn_cast<T>((llvm::Metadata *)ref);
}
template <typename T, typename R> T *dyn_cast_to_ditype_or_null(R ref) {
return llvm::dyn_cast_or_null<T>((llvm::Metadata *)ref);
}
template <typename N> struct DISymbol : public Symbol {
DISymbol(IMalloc *M, N Node) : Symbol(M), m_pNode(Node) {}
N m_pNode;
};
template <typename N> struct TypedSymbol : public DISymbol<N> {
TypedSymbol(IMalloc *M, N Node, DWORD dwTypeID, llvm::DIType *Type)
: DISymbol<N>(M, Node), m_dwTypeID(dwTypeID), m_pType(Type) {}
STDMETHODIMP get_type(
/* [retval][out] */ IDiaSymbol **ppRetVal) override {
if (ppRetVal == nullptr) {
return E_INVALIDARG;
}
*ppRetVal = nullptr;
if (m_pType == nullptr) {
return S_FALSE;
}
Symbol *ret;
IFR(this->m_pSession->SymMgr().GetSymbolByID(m_dwTypeID, &ret));
*ppRetVal = ret;
return S_OK;
}
const DWORD m_dwTypeID;
llvm::DIType *m_pType;
};
struct GlobalScopeSymbol : public Symbol {
DXC_MICROCOM_TM_ALLOC(GlobalScopeSymbol)
explicit GlobalScopeSymbol(IMalloc *M) : Symbol(M) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class GlobalScope final : public SymbolManager::SymbolFactory {
public:
GlobalScope(DWORD ID, DWORD ParentID)
: SymbolManager::SymbolFactory(ID, ParentID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
return hlsl_symbols::GlobalScopeSymbol::Create(pMalloc, pSession, ppRet);
}
};
} // namespace symbol_factory
struct CompilandSymbol : public DISymbol<llvm::DICompileUnit *> {
DXC_MICROCOM_TM_ALLOC(CompilandSymbol)
explicit CompilandSymbol(IMalloc *M, llvm::DICompileUnit *CU)
: DISymbol<llvm::DICompileUnit *>(M, CU) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession,
llvm::DICompileUnit *CU, Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class Compiland final : public SymbolManager::SymbolFactory {
public:
Compiland(DWORD ID, DWORD ParentID, llvm::DICompileUnit *CU)
: SymbolManager::SymbolFactory(ID, ParentID), m_CU(CU) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(hlsl_symbols::CompilandSymbol::Create(pMalloc, pSession, m_CU, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
private:
llvm::DICompileUnit *m_CU;
};
} // namespace symbol_factory
struct CompilandDetailsSymbol : public Symbol {
DXC_MICROCOM_TM_ALLOC(CompilandDetailsSymbol)
explicit CompilandDetailsSymbol(IMalloc *M) : Symbol(M) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
#pragma region IDiaSymbol implementation
// DEFINE_SIMPLE_GETTER is used to generate the boilerplate needed for the
// property getters needed by this symbol. name is the property name (as
// defined in IDiaSymbol::get_<name>. There should be a static (non-const OK)
// function defined in this class as
//
// <RetTy> <name>(CompilandDetailsSymbol * <this>)
//
// <RetTy> **must** match the property type in IDiaSymbol::get_<name>'s
// parameter; <this> is literally the this pointer. The function needs to
// be static (thus requiring the explicit <this> parameter) so that
// DEFINE_SIMPLE_GETTER can use decltype(name(nullptr)) in order to
// define the property parameter type.
#define DEFINE_SIMPLE_GETTER(name) \
STDMETHODIMP get_##name(decltype(name(nullptr)) *pValue) override { \
if (pValue == nullptr) { \
return E_INVALIDARG; \
} \
*pValue = name(this); \
return S_OK; \
}
static constexpr DWORD platform(CompilandDetailsSymbol *) { return 256; }
static constexpr DWORD language(CompilandDetailsSymbol *) { return 16; }
static constexpr BOOL hasDebugInfo(CompilandDetailsSymbol *) { return true; }
static BSTR compilerName(CompilandDetailsSymbol *) {
CComBSTR retval;
retval.Append("dxcompiler");
return retval.Detach();
}
static DWORD frontEndMajor(CompilandDetailsSymbol *self) {
return self->m_pSession->DxilModuleRef().GetShaderModel()->GetMajor();
}
static DWORD frontEndMinor(CompilandDetailsSymbol *self) {
return self->m_pSession->DxilModuleRef().GetShaderModel()->GetMinor();
}
DEFINE_SIMPLE_GETTER(platform);
DEFINE_SIMPLE_GETTER(language);
DEFINE_SIMPLE_GETTER(frontEndMajor);
DEFINE_SIMPLE_GETTER(frontEndMinor);
DEFINE_SIMPLE_GETTER(hasDebugInfo);
DEFINE_SIMPLE_GETTER(compilerName);
#undef DEFINE_SIMPLE_GETTER
#pragma endregion
};
namespace symbol_factory {
class CompilandDetails final : public SymbolManager::SymbolFactory {
public:
CompilandDetails(DWORD ID, DWORD ParentID)
: SymbolManager::SymbolFactory(ID, ParentID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(hlsl_symbols::CompilandDetailsSymbol::Create(pMalloc, pSession, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
};
} // namespace symbol_factory
struct CompilandEnvSymbol : public Symbol {
DXC_MICROCOM_TM_ALLOC(CompilandEnvSymbol)
explicit CompilandEnvSymbol(IMalloc *M) : Symbol(M) {}
static HRESULT CreateFlags(IMalloc *pMalloc, Session *pSession,
Symbol **ppSym);
static HRESULT CreateTarget(IMalloc *pMalloc, Session *pSession,
Symbol **ppSym);
static HRESULT CreateEntry(IMalloc *pMalloc, Session *pSession,
Symbol **ppSym);
static HRESULT CreateDefines(IMalloc *pMalloc, Session *pSession,
Symbol **pSym);
static HRESULT CreateArguments(IMalloc *pMalloc, Session *pSession,
Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
using CompilandEnvCreateFn = HRESULT(IMalloc *, Session *, Symbol **);
template <CompilandEnvCreateFn C>
class CompilandEnv final : public SymbolManager::SymbolFactory {
public:
CompilandEnv(DWORD ID, DWORD ParentID)
: SymbolManager::SymbolFactory(ID, ParentID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(C(pMalloc, pSession, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
};
} // namespace symbol_factory
struct FunctionSymbol : public TypedSymbol<llvm::DISubprogram *> {
DXC_MICROCOM_TM_ALLOC(FunctionSymbol)
FunctionSymbol(IMalloc *M, llvm::DISubprogram *Node, DWORD dwTypeID,
llvm::DIType *Type)
: TypedSymbol<llvm::DISubprogram *>(M, Node, dwTypeID, Type) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwID,
llvm::DISubprogram *Node, DWORD dwTypeID,
llvm::DIType *Type, Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class Function final : public SymbolManager::SymbolFactory {
public:
Function(DWORD ID, DWORD ParentID, llvm::DISubprogram *Node, DWORD TypeID)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_TypeID(TypeID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(FunctionSymbol::Create(pMalloc, pSession, m_ID, m_Node, m_TypeID,
m_Node->getType(), ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_Node->getName().str().c_str()));
return S_OK;
}
private:
llvm::DISubprogram *m_Node;
DWORD m_TypeID;
};
} // namespace symbol_factory
struct FunctionBlockSymbol : public Symbol {
DXC_MICROCOM_TM_ALLOC(FunctionBlockSymbol)
explicit FunctionBlockSymbol(IMalloc *M) : Symbol(M) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwID,
Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class FunctionBlock final : public SymbolManager::SymbolFactory {
public:
FunctionBlock(DWORD ID, DWORD ParentID)
: SymbolManager::SymbolFactory(ID, ParentID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(FunctionBlockSymbol::Create(pMalloc, pSession, m_ID, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
};
} // namespace symbol_factory
struct TypeSymbol : public DISymbol<llvm::DIType *> {
using LazySymbolName = std::function<HRESULT(Session *, std::string *)>;
DXC_MICROCOM_TM_ALLOC(TypeSymbol)
TypeSymbol(IMalloc *M, llvm::DIType *Node, LazySymbolName LazySymbolName)
: DISymbol<llvm::DIType *>(M, Node), m_lazySymbolName(LazySymbolName) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwParentID,
DWORD dwID, DWORD st, llvm::DIType *Node,
LazySymbolName LazySymbolName, Symbol **ppSym);
STDMETHODIMP get_name(
/* [retval][out] */ BSTR *pRetVal) override;
STDMETHODIMP get_baseType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_length(
/* [retval][out] */ ULONGLONG *pRetVal) override;
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
LazySymbolName m_lazySymbolName;
};
namespace symbol_factory {
class Type final : public SymbolManager::SymbolFactory {
public:
Type(DWORD ID, DWORD ParentID, DWORD st, llvm::DIType *Node,
TypeSymbol::LazySymbolName LazySymbolName)
: SymbolManager::SymbolFactory(ID, ParentID), m_st(st), m_Node(Node),
m_LazySymbolName(LazySymbolName) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(TypeSymbol::Create(pMalloc, pSession, m_ParentID, m_ID, m_st, m_Node,
m_LazySymbolName, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
private:
DWORD m_st;
llvm::DIType *m_Node;
TypeSymbol::LazySymbolName m_LazySymbolName;
};
} // namespace symbol_factory
struct TypedefTypeSymbol : public TypeSymbol {
DXC_MICROCOM_TM_ALLOC(TypedefTypeSymbol)
TypedefTypeSymbol(IMalloc *M, llvm::DIType *Node, DWORD dwBaseTypeID)
: TypeSymbol(M, Node, nullptr), m_dwBaseTypeID(dwBaseTypeID) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwParentID,
DWORD dwID, llvm::DIType *Node, DWORD dwBaseTypeID,
Symbol **ppSym);
STDMETHODIMP get_type(
/* [retval][out] */ IDiaSymbol **ppRetVal) override;
const DWORD m_dwBaseTypeID;
};
namespace symbol_factory {
class TypedefType final : public SymbolManager::SymbolFactory {
public:
TypedefType(DWORD ID, DWORD ParentID, llvm::DIType *Node, DWORD BaseTypeID)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_BaseTypeID(BaseTypeID) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(TypedefTypeSymbol::Create(pMalloc, pSession, m_ParentID, m_ID, m_Node,
m_BaseTypeID, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_Node->getName().str().c_str()));
return S_OK;
}
private:
llvm::DIType *m_Node;
DWORD m_BaseTypeID;
};
} // namespace symbol_factory
struct VectorTypeSymbol : public TypeSymbol {
DXC_MICROCOM_TM_ALLOC(VectorTypeSymbol)
VectorTypeSymbol(IMalloc *M, llvm::DIType *Node, DWORD dwElemTyID,
std::uint32_t NumElts)
: TypeSymbol(M, Node, nullptr), m_ElemTyID(dwElemTyID),
m_NumElts(NumElts) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwParentID,
DWORD dwID, llvm::DIType *Node, DWORD dwElemTyID,
std::uint32_t NumElts, Symbol **ppSym);
STDMETHODIMP get_count(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_type(
/* [retval][out] */ IDiaSymbol **ppRetVal) override;
std::uint32_t m_ElemTyID;
std::uint32_t m_NumElts;
};
namespace symbol_factory {
class VectorType final : public SymbolManager::SymbolFactory {
public:
VectorType(DWORD ID, DWORD ParentID, llvm::DIType *Node, DWORD ElemTyID,
std::uint32_t NumElts)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_ElemTyID(ElemTyID), m_NumElts(NumElts) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(VectorTypeSymbol::Create(pMalloc, pSession, m_ParentID, m_ID, m_Node,
m_ElemTyID, m_NumElts, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_Node->getName().str().c_str()));
return S_OK;
}
private:
llvm::DIType *m_Node;
DWORD m_ElemTyID;
std::uint32_t m_NumElts;
};
} // namespace symbol_factory
struct UDTSymbol : public TypeSymbol {
DXC_MICROCOM_TM_ALLOC(UDTSymbol)
UDTSymbol(IMalloc *M, llvm::DICompositeType *Node, LazySymbolName LazyName)
: TypeSymbol(M, Node, LazyName) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwParentID,
DWORD dwID, llvm::DICompositeType *Node,
LazySymbolName LazySymbolName, Symbol **ppSym);
};
namespace symbol_factory {
class UDT final : public SymbolManager::SymbolFactory {
public:
UDT(DWORD ID, DWORD ParentID, llvm::DICompositeType *Node,
TypeSymbol::LazySymbolName LazySymbolName)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_LazySymbolName(LazySymbolName) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(UDTSymbol::Create(pMalloc, pSession, m_ParentID, m_ID, m_Node,
m_LazySymbolName, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
return S_OK;
}
private:
llvm::DICompositeType *m_Node;
TypeSymbol::LazySymbolName m_LazySymbolName;
};
} // namespace symbol_factory
struct GlobalVariableSymbol : public TypedSymbol<llvm::DIGlobalVariable *> {
DXC_MICROCOM_TM_ALLOC(GlobalVariableSymbol)
GlobalVariableSymbol(IMalloc *M, llvm::DIGlobalVariable *GV, DWORD dwTypeID,
llvm::DIType *Type)
: TypedSymbol<llvm::DIGlobalVariable *>(M, GV, dwTypeID, Type) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwID,
llvm::DIGlobalVariable *GV, DWORD dwTypeID,
llvm::DIType *Type, Symbol **ppSym);
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class GlobalVariable final : public SymbolManager::SymbolFactory {
public:
GlobalVariable(DWORD ID, DWORD ParentID, llvm::DIGlobalVariable *GV,
DWORD TypeID, llvm::DIType *Type)
: SymbolManager::SymbolFactory(ID, ParentID), m_GV(GV), m_TypeID(TypeID),
m_Type(Type) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(GlobalVariableSymbol::Create(pMalloc, pSession, m_ID, m_GV, m_TypeID,
m_Type, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_GV->getName().str().c_str()));
(*ppRet)->SetIsHLSLData(true);
return S_OK;
}
private:
llvm::DIGlobalVariable *m_GV;
DWORD m_TypeID;
llvm::DIType *m_Type;
};
} // namespace symbol_factory
struct LocalVariableSymbol : public TypedSymbol<llvm::DIVariable *> {
DXC_MICROCOM_TM_ALLOC(LocalVariableSymbol)
LocalVariableSymbol(IMalloc *M, llvm::DIVariable *Node, DWORD dwTypeID,
llvm::DIType *Type, DWORD dwOffsetInUDT,
DWORD dwDxilRegNum)
: TypedSymbol<llvm::DIVariable *>(M, Node, dwTypeID, Type),
m_dwOffsetInUDT(dwOffsetInUDT), m_dwDxilRegNum(dwDxilRegNum) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwID,
llvm::DIVariable *Node, DWORD dwTypeID,
llvm::DIType *Type, DWORD dwOffsetInUDT,
DWORD m_dwDxilRegNum, Symbol **ppSym);
STDMETHODIMP get_locationType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_isAggregated(
/* [retval][out] */ BOOL *pRetVal) override;
STDMETHODIMP get_registerType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_offsetInUdt(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_sizeInUdt(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_numberOfRegisterIndices(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_numericProperties(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ DWORD *pProperties) override;
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
const DWORD m_dwOffsetInUDT;
const DWORD m_dwDxilRegNum;
};
namespace symbol_factory {
class LocalVarInfo {
public:
LocalVarInfo() = default;
LocalVarInfo(const LocalVarInfo &) = delete;
LocalVarInfo(LocalVarInfo &&) = default;
DWORD GetVarID() const { return m_dwVarID; }
DWORD GetOffsetInUDT() const { return m_dwOffsetInUDT; }
DWORD GetDxilRegister() const { return m_dwDxilRegister; }
void SetVarID(DWORD dwVarID) { m_dwVarID = dwVarID; }
void SetOffsetInUDT(DWORD dwOffsetInUDT) { m_dwOffsetInUDT = dwOffsetInUDT; }
void SetDxilRegister(DWORD dwDxilReg) { m_dwDxilRegister = dwDxilReg; }
private:
DWORD m_dwVarID = 0;
DWORD m_dwOffsetInUDT = 0;
DWORD m_dwDxilRegister = 0;
};
class LocalVariable final : public SymbolManager::SymbolFactory {
public:
LocalVariable(DWORD ID, DWORD ParentID, llvm::DIVariable *Node, DWORD TypeID,
llvm::DIType *Type, std::shared_ptr<LocalVarInfo> VI)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_TypeID(TypeID), m_Type(Type), m_VI(VI) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(LocalVariableSymbol::Create(pMalloc, pSession, m_ID, m_Node, m_TypeID,
m_Type, m_VI->GetOffsetInUDT(),
m_VI->GetDxilRegister(), ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_Node->getName().str().c_str()));
(*ppRet)->SetDataKind(m_Node->getTag() == llvm::dwarf::DW_TAG_arg_variable
? DataIsParam
: DataIsLocal);
return S_OK;
}
private:
llvm::DIVariable *m_Node;
DWORD m_TypeID;
llvm::DIType *m_Type;
std::shared_ptr<LocalVarInfo> m_VI;
};
} // namespace symbol_factory
struct UDTFieldSymbol : public TypedSymbol<llvm::DIDerivedType *> {
DXC_MICROCOM_TM_ALLOC(UDTFieldSymbol)
UDTFieldSymbol(IMalloc *M, llvm::DIDerivedType *Node, DWORD dwTypeID,
llvm::DIType *Type)
: TypedSymbol<llvm::DIDerivedType *>(M, Node, dwTypeID, Type) {}
static HRESULT Create(IMalloc *pMalloc, Session *pSession, DWORD dwID,
llvm::DIDerivedType *Node, DWORD dwTypeID,
llvm::DIType *Type, Symbol **ppSym);
STDMETHODIMP get_offset(
/* [retval][out] */ LONG *pRetVal) override;
HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) override;
};
namespace symbol_factory {
class UDTField final : public SymbolManager::SymbolFactory {
public:
UDTField(DWORD ID, DWORD ParentID, llvm::DIDerivedType *Node, DWORD TypeID,
llvm::DIType *Type)
: SymbolManager::SymbolFactory(ID, ParentID), m_Node(Node),
m_TypeID(TypeID), m_Type(Type) {}
virtual HRESULT Create(Session *pSession, Symbol **ppRet) override {
IMalloc *pMalloc = pSession->GetMallocNoRef();
IFR(UDTFieldSymbol::Create(pMalloc, pSession, m_ID, m_Node, m_TypeID,
m_Type, ppRet));
(*ppRet)->SetLexicalParent(m_ParentID);
(*ppRet)->SetName(CA2W(m_Node->getName().str().c_str()));
(*ppRet)->SetDataKind(m_Node->isStaticMember() ? DataIsStaticLocal
: DataIsMember);
return S_OK;
}
private:
llvm::DIDerivedType *m_Node;
DWORD m_TypeID;
llvm::DIType *m_Type;
};
} // namespace symbol_factory
class SymbolManagerInit {
public:
using SymbolCtor =
std::function<HRESULT(Session *pSession, DWORD ID, Symbol **ppSym)>;
using LazySymbolName = TypeSymbol::LazySymbolName;
class TypeInfo {
public:
TypeInfo() = delete;
TypeInfo(const TypeInfo &) = delete;
TypeInfo(TypeInfo &&) = default;
TypeInfo(DWORD dwTypeID, uint64_t alignInBits)
: m_dwTypeID(dwTypeID), m_alignInBytes(alignInBits / 8) {}
DWORD GetTypeID() const { return m_dwTypeID; }
DWORD GetCurrentSizeInBytes() const { return m_dwCurrentSizeInBytes; }
uint64_t GetAlignmentInBytes() const { return m_alignInBytes; }
const std::vector<llvm::DIType *> &GetLayout() const { return m_Layout; }
void Embed(const TypeInfo &TI);
void AddBasicType(llvm::DIBasicType *BT);
void AppendSize(uint64_t baseSize);
private:
DWORD m_dwTypeID;
std::vector<llvm::DIType *> m_Layout;
DWORD m_dwCurrentSizeInBytes = 0;
uint64_t m_alignInBytes;
};
using TypeToInfoMap =
llvm::DenseMap<llvm::DIType *, std::unique_ptr<TypeInfo>>;
// Because of the way the VarToID map is constructed, the
// vector<LocalVarInfo> may need to grow. The Symbol Constructor for local
// variable captures the LocalVarInfo for the local variable it creates, and
// it needs access to the information on this map (thus a by-value capture is
// not enough). We heap-allocate the VarInfos, and the local variables symbol
// constructors capture the pointer - meaning everything should be fine
// even if the vector is moved around.
using LocalVarToIDMap = llvm::DenseMap<
llvm::DILocalVariable *,
std::vector<std::shared_ptr<symbol_factory::LocalVarInfo>>>;
using UDTFieldToIDMap = llvm::DenseMap<llvm::DIDerivedType *, DWORD>;
SymbolManagerInit(
Session *pSession,
std::vector<std::unique_ptr<SymbolManager::SymbolFactory>> *pSymCtors,
SymbolManager::ScopeToIDMap *pScopeToSym,
SymbolManager::IDToLiveRangeMap *pSymToLR);
template <typename Factory, typename... Args>
HRESULT AddSymbol(DWORD dwParentID, DWORD *pNewSymID, Args &&...args) {
if (dwParentID > m_SymCtors.size()) {
return E_FAIL;
}
const DWORD dwNewSymID = m_SymCtors.size() + 1;
m_SymCtors.emplace_back(std::unique_ptr<Factory>(
new Factory(dwNewSymID, dwParentID, std::forward<Args>(args)...)));
*pNewSymID = dwNewSymID;
IFR(AddParent(dwParentID));
return S_OK;
}
HRESULT CreateFunctionsForAllCUs();
HRESULT CreateGlobalVariablesForAllCUs();
HRESULT CreateLocalVariables();
HRESULT CreateLiveRanges();
HRESULT IsDbgDeclareCall(llvm::Module *M, const llvm::Instruction *I,
DWORD *pReg, DWORD *pRegSize,
llvm::DILocalVariable **LV, uint64_t *pStartOffset,
uint64_t *pEndOffset,
dxil_dia::Session::RVA *pLowestUserRVA,
dxil_dia::Session::RVA *pHighestUserRVA);
HRESULT GetDxilAllocaRegister(llvm::Instruction *I, DWORD *pRegNum,
DWORD *pRegSize);
HRESULT PopulateParentToChildrenIDMap(
SymbolManager::ParentToChildrenMap *pParentToChildren);
private:
HRESULT GetTypeInfo(llvm::DIType *T, TypeInfo **TI);
template <typename Factory, typename... Args>
HRESULT AddType(DWORD dwParentID, llvm::DIType *T, DWORD *pNewSymID,
uint64_t alignment, Args &&...args) {
IFR(AddSymbol<Factory>(dwParentID, pNewSymID, std::forward<Args>(args)...));
if (!m_TypeToInfo
.insert(std::make_pair(
T, llvm::make_unique<TypeInfo>(*pNewSymID, alignment)))
.second) {
return E_FAIL;
}
return S_OK;
}
HRESULT AddParent(DWORD dwParentIndex);
HRESULT CreateFunctionBlockForLocalScope(llvm::DILocalScope *LS,
DWORD *pNewSymID);
HRESULT CreateFunctionBlockForInstruction(llvm::Instruction *I);
HRESULT CreateFunctionBlocksForFunction(llvm::Function *F);
HRESULT CreateFunctionsForCU(llvm::DICompileUnit *CU);
HRESULT CreateGlobalVariablesForCU(llvm::DICompileUnit *CU);
HRESULT GetScopeID(llvm::DIScope *S, DWORD *pScopeID);
HRESULT CreateType(llvm::DIType *T, DWORD *pNewTypeID);
HRESULT CreateSubroutineType(DWORD dwParentID, llvm::DISubroutineType *ST,
DWORD *pNewTypeID);
HRESULT CreateBasicType(DWORD dwParentID, llvm::DIBasicType *VT,
DWORD *pNewTypeID);
HRESULT CreateCompositeType(DWORD dwParentID, llvm::DICompositeType *CT,
DWORD *pNewTypeID);
HRESULT CreateHLSLType(llvm::DICompositeType *T, DWORD *pNewTypeID);
HRESULT IsHLSLVectorType(llvm::DICompositeType *T, DWORD *pEltTyID,
std::uint32_t *pElemCnt);
HRESULT CreateHLSLVectorType(llvm::DICompositeType *T, DWORD pEltTyID,
std::uint32_t pElemCnt, DWORD *pNewTypeID);
HRESULT HandleDerivedType(DWORD dwParentID, llvm::DIDerivedType *DT,
DWORD *pNewTypeID);
HRESULT CreateLocalVariable(DWORD dwParentID, llvm::DILocalVariable *LV);
HRESULT GetTypeLayout(llvm::DIType *Ty, std::vector<DWORD> *pRet);
HRESULT CreateUDTField(DWORD dwParentID, llvm::DIDerivedType *Field);
Session &m_Session;
std::vector<std::unique_ptr<SymbolManager::SymbolFactory>> &m_SymCtors;
SymbolManager::ScopeToIDMap &m_ScopeToSym;
SymbolManager::IDToLiveRangeMap &m_SymToLR;
// vector of parents, i.e., for each i in parents[i], parents[i] is the
// parent of m_symbol[i].
std::vector<std::uint32_t> m_Parent;
LocalVarToIDMap m_VarToID;
UDTFieldToIDMap m_FieldToID;
TypeToInfoMap m_TypeToInfo;
TypeInfo &CurrentUDTInfo() { return *m_pCurUDT; }
TypeInfo *m_pCurUDT = nullptr;
struct UDTScope {
UDTScope() = delete;
UDTScope(const UDTScope &) = delete;
UDTScope(UDTScope &&) = default;
UDTScope(TypeInfo **pCur, TypeInfo *pNext) : m_pCur(pCur), m_pPrev(*pCur) {
*pCur = pNext;
}
~UDTScope() { *m_pCur = m_pPrev; }
TypeInfo **m_pCur;
TypeInfo *m_pPrev;
};
UDTScope BeginUDTScope(TypeInfo *pNext) {
return UDTScope(&m_pCurUDT, pNext);
}
};
} // namespace hlsl_symbols
} // namespace dxil_dia
STDMETHODIMP dxil_dia::hlsl_symbols::TypeSymbol::get_baseType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = btNoType;
if (auto *BT = llvm::dyn_cast<llvm::DIBasicType>(m_pNode)) {
switch (BT->getEncoding()) {
case llvm::dwarf::DW_ATE_boolean:
*pRetVal = btBool;
break;
case llvm::dwarf::DW_ATE_unsigned:
*pRetVal = btUInt;
break;
case llvm::dwarf::DW_ATE_signed:
*pRetVal = btInt;
break;
case llvm::dwarf::DW_ATE_float:
*pRetVal = btFloat;
break;
}
}
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::TypeSymbol::get_length(
/* [retval][out] */ ULONGLONG *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
if (auto *BT = llvm::dyn_cast<llvm::DIBasicType>(m_pNode)) {
static constexpr DWORD kNumBitsPerByte = 8;
const DWORD SizeInBits = BT->getSizeInBits();
*pRetVal = SizeInBits / kNumBitsPerByte;
}
return S_OK;
}
static const std::string &
dxil_dia::hlsl_symbols::DxilEntryName(Session *pSession) {
return pSession->DxilModuleRef().GetEntryFunctionName();
}
HRESULT dxil_dia::hlsl_symbols::GlobalScopeSymbol::Create(IMalloc *pMalloc,
Session *pSession,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslProgramId, SymTagExe,
(GlobalScopeSymbol **)ppSym));
(*ppSym)->SetName(L"HLSL");
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::GlobalScopeSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
return m_pSession->SymMgr().ChildrenOf(this, children);
}
HRESULT dxil_dia::hlsl_symbols::CompilandSymbol::Create(IMalloc *pMalloc,
Session *pSession,
llvm::DICompileUnit *CU,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandId, SymTagCompiland,
(CompilandSymbol **)ppSym, CU));
(*ppSym)->SetName(L"main");
if (pSession->MainFileName()) {
llvm::StringRef strRef =
llvm::dyn_cast<llvm::MDString>(
pSession->MainFileName()->getOperand(0)->getOperand(0))
->getString();
std::string str(strRef.begin(),
strRef.size()); // To make sure str is null terminated
(*ppSym)->SetSourceFileName(
_bstr_t(Unicode::UTF8ToWideStringOrThrow(str.data()).c_str()));
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
return m_pSession->SymMgr().ChildrenOf(this, children);
}
HRESULT dxil_dia::hlsl_symbols::CompilandDetailsSymbol::Create(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandDetailsId,
SymTagCompilandDetails, (CompilandDetailsSymbol **)ppSym));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandDetailsSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
children->clear();
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::CreateFlags(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandEnvFlagsId,
SymTagCompilandEnv, (CompilandEnvSymbol **)ppSym));
(*ppSym)->SetName(L"hlslFlags");
const char *specialCases[] = {
"/T", "-T", "-D", "/D", "-E", "/E",
};
llvm::MDNode *argsNode = pSession->Arguments()->getOperand(0);
// Construct a double null terminated string for defines with L"\0" as a
// delimiter
CComBSTR pBSTR;
for (llvm::MDNode::op_iterator it = argsNode->op_begin();
it != argsNode->op_end(); ++it) {
llvm::StringRef strRef = llvm::dyn_cast<llvm::MDString>(*it)->getString();
bool skip = false;
bool skipTwice = false;
for (unsigned i = 0; i < _countof(specialCases); i++) {
if (strRef == specialCases[i]) {
skipTwice = true;
skip = true;
break;
} else if (strRef.startswith(specialCases[i])) {
skip = true;
break;
}
}
if (skip) {
if (skipTwice)
++it;
continue;
}
std::string str(strRef.begin(), strRef.size());
CA2W cv(str.c_str());
pBSTR.Append(cv);
pBSTR.Append(L"\0", 1);
}
pBSTR.Append(L"\0", 1);
VARIANT Variant;
Variant.bstrVal = pBSTR;
Variant.vt = VARENUM::VT_BSTR;
(*ppSym)->SetValue(&Variant);
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::CreateTarget(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandEnvTargetId,
SymTagCompilandEnv, (CompilandEnvSymbol **)ppSym));
(*ppSym)->SetName(L"hlslTarget");
(*ppSym)->SetValue(pSession->DxilModuleRef().GetShaderModel()->GetName());
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::CreateEntry(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandEnvEntryId,
SymTagCompilandEnv, (CompilandEnvSymbol **)ppSym));
(*ppSym)->SetName(L"hlslEntry");
(*ppSym)->SetValue(DxilEntryName(pSession).c_str());
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::CreateDefines(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandEnvDefinesId,
SymTagCompilandEnv, (CompilandEnvSymbol **)ppSym));
(*ppSym)->SetName(L"hlslDefines");
llvm::MDNode *definesNode = pSession->Defines()->getOperand(0);
// Construct a double null terminated string for defines with L"\0" as a
// delimiter
CComBSTR pBSTR;
for (llvm::MDNode::op_iterator it = definesNode->op_begin();
it != definesNode->op_end(); ++it) {
llvm::StringRef strRef = llvm::dyn_cast<llvm::MDString>(*it)->getString();
std::string str(strRef.begin(), strRef.size());
CA2W cv(str.c_str());
pBSTR.Append(cv);
pBSTR.Append(L"\0", 1);
}
pBSTR.Append(L"\0", 1);
VARIANT Variant;
Variant.bstrVal = pBSTR;
Variant.vt = VARENUM::VT_BSTR;
(*ppSym)->SetValue(&Variant);
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::CreateArguments(
IMalloc *pMalloc, Session *pSession, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, HlslCompilandEnvArgumentsId,
SymTagCompilandEnv, (CompilandEnvSymbol **)ppSym));
(*ppSym)->SetName(L"hlslArguments");
auto Arguments = pSession->Arguments()->getOperand(0);
auto NumArguments = Arguments->getNumOperands();
std::string args;
for (unsigned i = 0; i < NumArguments; ++i) {
llvm::StringRef strRef =
llvm::dyn_cast<llvm::MDString>(Arguments->getOperand(i))->getString();
if (!args.empty())
args.push_back(' ');
args = args + strRef.str();
}
(*ppSym)->SetValue(args.c_str());
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::CompilandEnvSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
children->clear();
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::FunctionSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwID, llvm::DISubprogram *Node,
DWORD dwTypeID, llvm::DIType *Type, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagFunction,
(FunctionSymbol **)ppSym, Node, dwTypeID, Type));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::FunctionSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
return m_pSession->SymMgr().ChildrenOf(this, children);
}
HRESULT dxil_dia::hlsl_symbols::FunctionBlockSymbol::Create(IMalloc *pMalloc,
Session *pSession,
DWORD dwID,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagBlock,
(FunctionBlockSymbol **)ppSym));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::FunctionBlockSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
return m_pSession->SymMgr().ChildrenOf(this, children);
}
HRESULT dxil_dia::hlsl_symbols::TypeSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwParentID, DWORD dwID, DWORD st,
llvm::DIType *Node, LazySymbolName LazySymbolName, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, st, (TypeSymbol **)ppSym, Node,
LazySymbolName));
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::TypeSymbol::get_name(
/* [retval][out] */ BSTR *pRetVal) {
DxcThreadMalloc TM(m_pSession->GetMallocNoRef());
if (m_lazySymbolName != nullptr) {
DXASSERT(!this->HasName(), "Setting type name multiple times.");
std::string Name;
IFR(m_lazySymbolName(m_pSession, &Name));
this->SetName(CA2W(Name.c_str()));
m_lazySymbolName = nullptr;
}
return Symbol::get_name(pRetVal);
}
HRESULT dxil_dia::hlsl_symbols::TypeSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
return m_pSession->SymMgr().ChildrenOf(this, children);
}
HRESULT dxil_dia::hlsl_symbols::VectorTypeSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwParentID, DWORD dwID,
llvm::DIType *Node, DWORD dwElemTyID, std::uint32_t NumElts,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagVectorType,
(VectorTypeSymbol **)ppSym, Node, dwElemTyID, NumElts));
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::VectorTypeSymbol::get_count(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = m_NumElts;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::VectorTypeSymbol::get_type(
/* [retval][out] */ IDiaSymbol **ppRetVal) {
if (ppRetVal == nullptr) {
return E_INVALIDARG;
}
*ppRetVal = nullptr;
Symbol *ret;
IFR(m_pSession->SymMgr().GetSymbolByID(m_ElemTyID, &ret));
*ppRetVal = ret;
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::UDTSymbol::Create(IMalloc *pMalloc,
Session *pSession,
DWORD dwParentID, DWORD dwID,
llvm::DICompositeType *Node,
LazySymbolName LazySymbolName,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagUDT, (UDTSymbol **)ppSym,
Node, LazySymbolName));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::TypedefTypeSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwParentID, DWORD dwID,
llvm::DIType *Node, DWORD dwBaseTypeID, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagTypedef,
(TypedefTypeSymbol **)ppSym, Node, dwBaseTypeID));
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::TypedefTypeSymbol::get_type(
/* [retval][out] */ IDiaSymbol **ppRetVal) {
if (ppRetVal == nullptr) {
return E_INVALIDARG;
}
*ppRetVal = nullptr;
Symbol *ret = nullptr;
IFR(m_pSession->SymMgr().GetSymbolByID(m_dwBaseTypeID, &ret));
*ppRetVal = ret;
return S_FALSE;
}
HRESULT dxil_dia::hlsl_symbols::GlobalVariableSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwID, llvm::DIGlobalVariable *GV,
DWORD dwTypeID, llvm::DIType *Type, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagData,
(GlobalVariableSymbol **)ppSym, GV, dwTypeID, Type));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::GlobalVariableSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
children->clear();
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::LocalVariableSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwID, llvm::DIVariable *Node,
DWORD dwTypeID, llvm::DIType *Type, DWORD dwOffsetInUDT, DWORD dwDxilRegNum,
Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagData,
(LocalVariableSymbol **)ppSym, Node, dwTypeID, Type,
dwOffsetInUDT, dwDxilRegNum));
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_locationType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = LocIsEnregistered;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_isAggregated(
/* [retval][out] */ BOOL *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = m_pType->getTag() == llvm::dwarf::DW_TAG_member;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_registerType(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
static constexpr DWORD kPixTraceVirtualRegister = 0xfe;
*pRetVal = kPixTraceVirtualRegister;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_offsetInUdt(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = m_dwOffsetInUDT;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_sizeInUdt(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
// auto *DT = llvm::cast<llvm::DIDerivedType>(m_pType);
*pRetVal = 4; // DT->getSizeInBits() / kBitsPerByte;
return S_OK;
}
STDMETHODIMP
dxil_dia::hlsl_symbols::LocalVariableSymbol::get_numberOfRegisterIndices(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 1;
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::LocalVariableSymbol::get_numericProperties(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ DWORD *pProperties) {
if (pcnt == nullptr || pProperties == nullptr || cnt != 1) {
return E_INVALIDARG;
}
pProperties[0] = m_dwDxilRegNum;
*pcnt = 1;
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::LocalVariableSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
children->clear();
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::UDTFieldSymbol::Create(
IMalloc *pMalloc, Session *pSession, DWORD dwID, llvm::DIDerivedType *Node,
DWORD dwTypeID, llvm::DIType *Type, Symbol **ppSym) {
IFR(AllocAndInit(pMalloc, pSession, dwID, SymTagData,
(UDTFieldSymbol **)ppSym, Node, dwTypeID, Type));
return S_OK;
}
STDMETHODIMP dxil_dia::hlsl_symbols::UDTFieldSymbol::get_offset(
/* [retval][out] */ LONG *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
static constexpr DWORD kBitsPerByte = 8;
*pRetVal = m_pNode->getOffsetInBits() / kBitsPerByte;
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::UDTFieldSymbol::GetChildren(
std::vector<CComPtr<Symbol>> *children) {
children->clear();
return S_OK;
}
dxil_dia::hlsl_symbols::SymbolManagerInit::SymbolManagerInit(
Session *pSession,
std::vector<std::unique_ptr<SymbolManager::SymbolFactory>> *pSymCtors,
SymbolManager::ScopeToIDMap *pScopeToSym,
SymbolManager::IDToLiveRangeMap *pSymToLR)
: m_Session(*pSession), m_SymCtors(*pSymCtors), m_ScopeToSym(*pScopeToSym),
m_SymToLR(*pSymToLR) {
DXASSERT_ARGS(m_Parent.size() == m_SymCtors.size(),
"parent and symbol array size mismatch: %d vs %d",
m_Parent.size(), m_SymCtors.size());
}
void dxil_dia::hlsl_symbols::SymbolManagerInit::TypeInfo::Embed(
const TypeInfo &TI) {
for (const auto &E : TI.GetLayout()) {
m_Layout.emplace_back(E);
}
uint64_t alignmentInBytes = TI.GetAlignmentInBytes();
if (alignmentInBytes != 0) {
m_dwCurrentSizeInBytes =
llvm::RoundUpToAlignment(m_dwCurrentSizeInBytes, alignmentInBytes);
}
m_dwCurrentSizeInBytes += TI.m_dwCurrentSizeInBytes;
}
void dxil_dia::hlsl_symbols::SymbolManagerInit::TypeInfo::AppendSize(
uint64_t baseSize) {
static constexpr DWORD kNumBitsPerByte = 8;
m_dwCurrentSizeInBytes += baseSize / kNumBitsPerByte;
}
void dxil_dia::hlsl_symbols::SymbolManagerInit::TypeInfo::AddBasicType(
llvm::DIBasicType *BT) {
m_Layout.emplace_back(BT);
static constexpr DWORD kNumBitsPerByte = 8;
uint64_t alignmentInBytes = BT->getAlignInBits() / kNumBitsPerByte;
if (alignmentInBytes != 0) {
m_dwCurrentSizeInBytes =
llvm::RoundUpToAlignment(m_dwCurrentSizeInBytes, alignmentInBytes);
}
m_dwCurrentSizeInBytes += BT->getSizeInBits() / kNumBitsPerByte;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::GetTypeInfo(llvm::DIType *T,
TypeInfo **TI) {
auto tyInfoIt = m_TypeToInfo.find(T);
if (tyInfoIt == m_TypeToInfo.end()) {
return E_FAIL;
}
*TI = tyInfoIt->second.get();
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::AddParent(DWORD dwParentIndex) {
m_Parent.emplace_back(dwParentIndex);
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::CreateFunctionBlockForLocalScope(
llvm::DILocalScope *LS, DWORD *pNewSymID) {
if (LS == nullptr) {
return E_FAIL;
}
auto lsIT = m_ScopeToSym.find(LS);
if (lsIT != m_ScopeToSym.end()) {
*pNewSymID = lsIT->second;
return S_OK;
}
llvm::DILocalScope *ParentLS = nullptr;
if (auto *Location = llvm::dyn_cast<llvm::DILocation>(LS)) {
ParentLS = Location->getInlinedAtScope();
if (ParentLS == nullptr) {
ParentLS = Location->getScope();
}
} else if (auto *Block = llvm::dyn_cast<llvm::DILexicalBlock>(LS)) {
ParentLS = Block->getScope();
} else if (auto *BlockFile = llvm::dyn_cast<llvm::DILexicalBlockFile>(LS)) {
ParentLS = BlockFile->getScope();
}
if (ParentLS == nullptr) {
return E_FAIL;
}
DWORD dwParentID;
IFR(CreateFunctionBlockForLocalScope(ParentLS, &dwParentID));
IFR(AddSymbol<symbol_factory::FunctionBlock>(dwParentID, pNewSymID));
m_ScopeToSym.insert(std::make_pair(LS, *pNewSymID));
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::CreateFunctionBlockForInstruction(
llvm::Instruction *I) {
const llvm::DebugLoc &DL = I->getDebugLoc();
if (!DL) {
return S_OK;
}
llvm::MDNode *LocalScope = DL.getInlinedAtScope();
if (LocalScope == nullptr) {
LocalScope = DL.getScope();
}
if (LocalScope == nullptr) {
return S_OK;
}
auto *LS = llvm::dyn_cast<llvm::DILocalScope>(LocalScope);
if (LS == nullptr) {
return E_FAIL;
}
auto localScopeIt = m_ScopeToSym.find(LS);
if (localScopeIt == m_ScopeToSym.end()) {
DWORD dwUnusedNewSymID;
IFR(CreateFunctionBlockForLocalScope(LS, &dwUnusedNewSymID));
}
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::CreateFunctionBlocksForFunction(
llvm::Function *F) {
for (llvm::BasicBlock &BB : *F) {
for (llvm::Instruction &I : BB) {
IFR(CreateFunctionBlockForInstruction(&I));
}
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateFunctionsForCU(
llvm::DICompileUnit *CU) {
bool FoundFunctions = false;
for (llvm::DISubprogram *SubProgram : CU->getSubprograms()) {
DWORD dwNewFunID;
const DWORD dwParentID =
SubProgram->isLocalToUnit() ? HlslCompilandId : HlslProgramId;
DWORD dwSubprogramTypeID;
IFR(CreateType(SubProgram->getType(), &dwSubprogramTypeID));
IFR(AddSymbol<symbol_factory::Function>(dwParentID, &dwNewFunID, SubProgram,
dwSubprogramTypeID));
m_ScopeToSym.insert(std::make_pair(SubProgram, dwNewFunID));
}
for (llvm::DISubprogram *SubProgram : CU->getSubprograms()) {
if (llvm::Function *F = SubProgram->getFunction()) {
IFR(CreateFunctionBlocksForFunction(F));
FoundFunctions = true;
}
}
if (!FoundFunctions) {
// This works around an old bug in dxcompiler whose effects are still
// sometimes present in PIX users' traces. (The bug was that the
// subprogram(s) weren't pointing to their contained function.)
llvm::Module *M = &m_Session.ModuleRef();
auto &DM = M->GetDxilModule();
llvm::Function *EntryPoint = DM.GetEntryFunction();
IFR(CreateFunctionBlocksForFunction(EntryPoint));
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateFunctionsForAllCUs() {
for (llvm::DICompileUnit *pCU : m_Session.InfoRef().compile_units()) {
IFR(CreateFunctionsForCU(pCU));
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateGlobalVariablesForCU(
llvm::DICompileUnit *CU) {
for (llvm::DIGlobalVariable *GlobalVariable : CU->getGlobalVariables()) {
DWORD dwUnusedNewGVID;
const DWORD dwParentID =
GlobalVariable->isLocalToUnit() ? HlslCompilandId : HlslProgramId;
auto *GVType = dyn_cast_to_ditype<llvm::DIType>(GlobalVariable->getType());
DWORD dwGVTypeID;
IFR(CreateType(GVType, &dwGVTypeID));
IFR(AddSymbol<symbol_factory::GlobalVariable>(
dwParentID, &dwUnusedNewGVID, GlobalVariable, dwGVTypeID, GVType));
}
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::CreateGlobalVariablesForAllCUs() {
for (llvm::DICompileUnit *pCU : m_Session.InfoRef().compile_units()) {
IFR(CreateGlobalVariablesForCU(pCU));
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::GetScopeID(llvm::DIScope *S,
DWORD *pScopeID) {
auto ParentScopeIt = m_ScopeToSym.find(S);
if (ParentScopeIt != m_ScopeToSym.end()) {
*pScopeID = ParentScopeIt->second;
} else {
auto *ParentScopeTy = llvm::dyn_cast<llvm::DIType>(S);
if (!ParentScopeTy) {
// Any non-existing scope must be a type.
return E_FAIL;
}
IFR(CreateType(ParentScopeTy, pScopeID));
}
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::CreateType(llvm::DIType *Type,
DWORD *pNewTypeID) {
if (Type == nullptr) {
return E_FAIL;
}
auto lsIT = m_TypeToInfo.find(Type);
if (lsIT != m_TypeToInfo.end()) {
*pNewTypeID = lsIT->second->GetTypeID();
return S_OK;
}
if (auto *ST = llvm::dyn_cast<llvm::DISubroutineType>(Type)) {
IFR(CreateSubroutineType(HlslProgramId, ST, pNewTypeID));
return S_OK;
} else if (auto *BT = llvm::dyn_cast<llvm::DIBasicType>(Type)) {
IFR(CreateBasicType(HlslProgramId, BT, pNewTypeID));
return S_OK;
} else if (auto *CT = llvm::dyn_cast<llvm::DICompositeType>(Type)) {
DWORD dwParentID = HlslProgramId;
if (auto *ParentScope =
dyn_cast_to_ditype_or_null<llvm::DIScope>(CT->getScope())) {
IFR(GetScopeID(ParentScope, &dwParentID));
}
IFR(CreateCompositeType(dwParentID, CT, pNewTypeID));
return S_OK;
} else if (auto *DT = llvm::dyn_cast<llvm::DIDerivedType>(Type)) {
DWORD dwParentID = HlslProgramId;
if (auto *ParentScope =
dyn_cast_to_ditype_or_null<llvm::DIScope>(DT->getScope())) {
IFR(GetScopeID(ParentScope, &dwParentID));
}
IFR(HandleDerivedType(dwParentID, DT, pNewTypeID));
return S_OK;
}
return E_FAIL;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateSubroutineType(
DWORD dwParentID, llvm::DISubroutineType *ST, DWORD *pNewTypeID) {
LazySymbolName LazyName;
llvm::DITypeRefArray Types = ST->getTypeArray();
if (Types.size() > 0) {
std::vector<DWORD> TypeIDs;
TypeIDs.reserve(Types.size());
for (llvm::Metadata *M : Types) {
auto *Ty = dyn_cast_to_ditype_or_null<llvm::DIType>(M);
if (Ty == nullptr) {
TypeIDs.emplace_back(kNullSymbolID);
} else {
DWORD dwTyID;
IFR(CreateType(Ty, &dwTyID));
TypeIDs.emplace_back(dwTyID);
}
}
LazyName = [TypeIDs](Session *pSession, std::string *Name) -> HRESULT {
Name->clear();
llvm::raw_string_ostream OS(*Name);
OS.SetUnbuffered();
bool first = true;
bool firstArg = true;
auto &SM = pSession->SymMgr();
for (DWORD ID : TypeIDs) {
if (!first && !firstArg) {
OS << ", ";
}
if (ID == kNullSymbolID) {
OS << "void";
} else {
CComPtr<Symbol> SymTy;
IFR(SM.GetSymbolByID(ID, &SymTy));
CComBSTR name;
IFR(SymTy->get_name(&name));
if (!name) {
OS << "???";
} else {
OS << CW2A((BSTR)name);
}
}
if (first) {
OS << "(";
}
firstArg = first;
first = false;
}
OS << ")";
return S_OK;
};
}
IFR(AddType<symbol_factory::Type>(dwParentID, ST, pNewTypeID, 0 /*alignment*/,
SymTagFunctionType, ST, LazyName));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateBasicType(
DWORD dwParentID, llvm::DIBasicType *BT, DWORD *pNewTypeID) {
DXASSERT_ARGS(dwParentID == HlslProgramId, "%d vs %d", dwParentID,
HlslProgramId);
LazySymbolName LazyName = [BT](Session *pSession,
std::string *Name) -> HRESULT {
*Name = BT->getName();
return S_OK;
};
IFR(AddType<symbol_factory::Type>(dwParentID, BT, pNewTypeID,
BT->getAlignInBits(), SymTagBaseType, BT,
LazyName));
TypeInfo *TI;
IFR(GetTypeInfo(BT, &TI));
TI->AddBasicType(BT);
return S_OK;
}
static uint64_t getBaseClassSize(llvm::DIType *Ty) {
uint64_t sizeInBits = Ty->getSizeInBits();
auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty);
if (DerivedTy != nullptr) {
// Working around a bug where byte size is stored instead of bit size
if (sizeInBits == 4 && Ty->getSizeInBits() == 32) {
sizeInBits = 32;
}
if (sizeInBits == 0) {
const llvm::DITypeIdentifierMap EmptyMap;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef: {
llvm::DIType *baseType = DerivedTy->getBaseType().resolve(EmptyMap);
if (baseType != nullptr) {
return getBaseClassSize(baseType);
}
}
}
}
}
return sizeInBits;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateCompositeType(
DWORD dwParentID, llvm::DICompositeType *CT, DWORD *pNewTypeID) {
switch (CT->getTag()) {
case llvm::dwarf::DW_TAG_array_type: {
auto *BaseType =
dyn_cast_to_ditype_or_null<llvm::DIType>(CT->getBaseType());
if (BaseType == nullptr) {
return E_FAIL;
}
DWORD dwBaseTypeID = kNullSymbolID;
IFR(CreateType(BaseType, &dwBaseTypeID));
auto LazyName = [CT, dwBaseTypeID](Session *pSession,
std::string *Name) -> HRESULT {
auto &SM = pSession->SymMgr();
Name->clear();
llvm::raw_string_ostream OS(*Name);
OS.SetUnbuffered();
auto *BaseTy = llvm::dyn_cast<llvm::DIType>(CT->getBaseType());
if (BaseTy == nullptr) {
return E_FAIL;
}
CComPtr<Symbol> SymTy;
IFR(SM.GetSymbolByID(dwBaseTypeID, &SymTy));
CComBSTR name;
IFR(SymTy->get_name(&name));
if (!name) {
OS << "???";
} else {
OS << CW2A((BSTR)name);
}
OS << "[";
bool first = true;
for (llvm::DINode *N : CT->getElements()) {
if (!first) {
OS << "][";
}
first = false;
if (N != nullptr) {
if (auto *SubRange = llvm::dyn_cast<llvm::DISubrange>(N)) {
OS << SubRange->getCount();
} else {
OS << "???";
}
}
}
OS << "]";
return S_OK;
};
IFR(AddType<symbol_factory::Type>(dwParentID, CT, pNewTypeID,
BaseType->getAlignInBits(),
SymTagArrayType, CT, LazyName));
TypeInfo *ctTI;
IFR(GetTypeInfo(CT, &ctTI));
TypeInfo *baseTI;
IFR(GetTypeInfo(BaseType, &baseTI));
int64_t embedCount = 1;
for (llvm::DINode *N : CT->getElements()) {
if (N != nullptr) {
if (auto *SubRange = llvm::dyn_cast<llvm::DISubrange>(N)) {
embedCount *= SubRange->getCount();
} else {
return E_FAIL;
}
}
}
for (int64_t i = 0; i < embedCount; ++i) {
ctTI->Embed(*baseTI);
}
return S_OK;
}
case llvm::dwarf::DW_TAG_class_type: {
HRESULT hr;
IFR(hr = CreateHLSLType(CT, pNewTypeID));
if (hr == S_OK) {
return S_OK;
}
break;
}
}
auto LazyName = [CT](Session *pSession, std::string *Name) -> HRESULT {
*Name = CT->getName();
return S_OK;
};
IFR(AddType<symbol_factory::UDT>(dwParentID, CT, pNewTypeID,
CT->getAlignInBits(), CT, LazyName));
TypeInfo *udtTI;
IFR(GetTypeInfo(CT, &udtTI));
auto udtScope = BeginUDTScope(udtTI);
if (CT->getElements().size() == 0) {
// "Resources" (textures, samplers, etc.) are composite types without any
// elements, but they do have a size.
udtTI->AppendSize(CT->getSizeInBits());
} else {
for (llvm::DINode *N : CT->getElements()) {
if (auto *Field = llvm::dyn_cast<llvm::DIType>(N)) {
std::unique_ptr<UDTScope> UDTScopeOverride;
if (Field->isStaticMember()) {
// Static members do not contribute to sizes or offsets.
UDTScopeOverride.reset(new UDTScope(&m_pCurUDT, nullptr));
}
DWORD dwUnusedFieldID;
IFR(CreateType(Field, &dwUnusedFieldID));
if (Field->getTag() == llvm::dwarf::DW_TAG_inheritance) {
// The base class is a type of its own, so will have contributed to
// its own TypeInfo. But we still need to remember the size that it
// contributed to this type:
auto *DerivedType = llvm::cast<llvm::DIDerivedType>(Field);
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *BaseType = DerivedType->getBaseType().resolve(EmptyMap);
udtTI->AppendSize(getBaseClassSize(BaseType));
}
}
}
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateHLSLType(
llvm::DICompositeType *T, DWORD *pNewTypeID) {
DWORD dwEltTyID;
std::uint32_t ElemCnt;
HRESULT hr;
IFR(hr = IsHLSLVectorType(T, &dwEltTyID, &ElemCnt));
if (hr == S_OK) {
// e.g. float4, int2 etc
return CreateHLSLVectorType(T, dwEltTyID, ElemCnt, pNewTypeID);
}
return S_FALSE;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::IsHLSLVectorType(
llvm::DICompositeType *T, DWORD *pEltTyID, std::uint32_t *pElemCnt) {
llvm::StringRef Name = T->getName();
if (!Name.startswith("vector<")) {
return S_FALSE;
}
llvm::DITemplateParameterArray Args = T->getTemplateParams();
if (Args.size() != 2) {
return E_FAIL;
}
auto *ElemTyParam = llvm::dyn_cast<llvm::DITemplateTypeParameter>(Args[0]);
if (ElemTyParam == nullptr) {
return E_FAIL;
}
auto *ElemTy = dyn_cast_to_ditype<llvm::DIType>(ElemTyParam->getType());
if (ElemTy == nullptr) {
return E_FAIL;
}
DWORD dwEltTyID;
IFR(CreateType(ElemTy, &dwEltTyID));
auto *ElemCntParam = llvm::dyn_cast<llvm::DITemplateValueParameter>(Args[1]);
if (ElemCntParam == nullptr) {
return E_FAIL;
}
auto *ElemCntMD =
llvm::dyn_cast<llvm::ConstantAsMetadata>(ElemCntParam->getValue());
auto *ElemCnt =
llvm::dyn_cast_or_null<llvm::ConstantInt>(ElemCntMD->getValue());
if (ElemCnt == nullptr) {
return E_FAIL;
}
if (ElemCnt->getLimitedValue() > 4) {
return E_FAIL;
}
*pEltTyID = dwEltTyID;
*pElemCnt = ElemCnt->getLimitedValue();
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateHLSLVectorType(
llvm::DICompositeType *T, DWORD pEltTyID, std::uint32_t pElemCnt,
DWORD *pNewTypeID) {
llvm::DITemplateParameterArray Args = T->getTemplateParams();
if (Args.size() != 2) {
return E_FAIL;
}
auto *ElemTyParam = llvm::dyn_cast<llvm::DITemplateTypeParameter>(Args[0]);
if (ElemTyParam == nullptr) {
return E_FAIL;
}
auto *ElemTy = dyn_cast_to_ditype<llvm::DIType>(ElemTyParam->getType());
if (ElemTy == nullptr) {
return E_FAIL;
}
DWORD dwElemTyID;
IFT(CreateType(ElemTy, &dwElemTyID));
auto *ElemCntParam = llvm::dyn_cast<llvm::DITemplateValueParameter>(Args[1]);
if (ElemCntParam == nullptr) {
return E_FAIL;
}
auto *ElemCntMD =
llvm::dyn_cast<llvm::ConstantAsMetadata>(ElemCntParam->getValue());
auto *ElemCnt =
llvm::dyn_cast_or_null<llvm::ConstantInt>(ElemCntMD->getValue());
if (ElemCnt == nullptr) {
return E_FAIL;
}
if (ElemCnt->getLimitedValue() > 4) {
return E_FAIL;
}
const DWORD dwParentID = HlslProgramId;
IFR(AddType<symbol_factory::VectorType>(dwParentID, T, pNewTypeID,
T->getAlignInBits(), T, dwElemTyID,
ElemCnt->getLimitedValue()));
TypeInfo *vecTI;
IFR(GetTypeInfo(T, &vecTI));
TypeInfo *elemTI;
IFR(GetTypeInfo(ElemTy, &elemTI));
for (std::uint64_t i = 0; i < ElemCnt->getLimitedValue(); ++i) {
vecTI->Embed(*elemTI);
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::HandleDerivedType(
DWORD dwParentID, llvm::DIDerivedType *DT, DWORD *pNewTypeID) {
DWORD st;
LazySymbolName LazyName;
DWORD dwBaseTypeID = kNullSymbolID;
auto *BaseTy = llvm::dyn_cast_or_null<llvm::DIType>(DT->getBaseType());
if (BaseTy != nullptr) {
IFR(CreateType(BaseTy, &dwBaseTypeID));
}
auto LazyNameWithQualifier = [dwBaseTypeID,
DT](Session *pSession, std::string *Name,
const char *Qualifier) -> HRESULT {
auto &SM = pSession->SymMgr();
Name->clear();
llvm::raw_string_ostream OS(*Name);
OS.SetUnbuffered();
auto *BaseTy = llvm::dyn_cast<llvm::DIType>(DT->getBaseType());
if (BaseTy == nullptr) {
return E_FAIL;
}
CComPtr<Symbol> SymTy;
IFR(SM.GetSymbolByID(dwBaseTypeID, &SymTy));
CComBSTR name;
IFR(SymTy->get_name(&name));
if (!name) {
OS << "???";
} else {
OS << CW2A((BSTR)name);
}
OS << Qualifier;
return S_OK;
};
switch (DT->getTag()) {
case llvm::dwarf::DW_TAG_member: {
// Type is not really a type, but rather a struct member.
IFR(CreateUDTField(dwParentID, DT));
return S_OK;
}
default:
st = SymTagBlock;
LazyName = [](Session *pSession, std::string *Name) -> HRESULT {
Name->clear();
return S_OK;
};
break;
case llvm::dwarf::DW_TAG_typedef: {
if (dwBaseTypeID == kNullSymbolID) {
return E_FAIL;
}
IFR(AddType<symbol_factory::TypedefType>(dwParentID, DT, pNewTypeID,
BaseTy->getAlignInBits(), DT,
dwBaseTypeID));
TypeInfo *dtTI;
IFR(GetTypeInfo(DT, &dtTI));
TypeInfo *baseTI;
IFR(GetTypeInfo(BaseTy, &baseTI));
dtTI->Embed(*baseTI);
return S_OK;
}
case llvm::dwarf::DW_TAG_const_type: {
if (dwBaseTypeID == kNullSymbolID) {
return E_FAIL;
}
st = SymTagCustomType;
LazyName = std::bind(LazyNameWithQualifier, std::placeholders::_1,
std::placeholders::_2, " const");
break;
}
case llvm::dwarf::DW_TAG_pointer_type: {
if (dwBaseTypeID == kNullSymbolID) {
return E_FAIL;
}
st = SymTagPointerType;
LazyName = std::bind(LazyNameWithQualifier, std::placeholders::_1,
std::placeholders::_2, " *");
break;
}
case llvm::dwarf::DW_TAG_reference_type: {
if (dwBaseTypeID == kNullSymbolID) {
return E_FAIL;
}
st = SymTagCustomType;
LazyName = std::bind(LazyNameWithQualifier, std::placeholders::_1,
std::placeholders::_2, " &");
break;
}
}
IFR(AddType<symbol_factory::Type>(dwParentID, DT, pNewTypeID,
DT->getAlignInBits(), st, DT, LazyName));
if (DT->getTag() == llvm::dwarf::DW_TAG_const_type) {
TypeInfo *dtTI;
IFR(GetTypeInfo(DT, &dtTI));
TypeInfo *baseTI;
IFR(GetTypeInfo(BaseTy, &baseTI));
dtTI->Embed(*baseTI);
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateLocalVariable(
DWORD dwParentID, llvm::DILocalVariable *LV) {
auto *LVTy = dyn_cast_to_ditype<llvm::DIType>(LV->getType());
if (LVTy == nullptr) {
return E_FAIL;
}
if (m_VarToID.count(LV) != 0) {
return S_OK;
}
DWORD dwLVTypeID;
IFR(CreateType(LVTy, &dwLVTypeID));
TypeInfo *varTI;
IFR(GetTypeInfo(LVTy, &varTI));
DWORD dwOffsetInUDT = 0;
auto &newVars = m_VarToID[LV];
std::vector<llvm::DIType *> Tys = varTI->GetLayout();
for (llvm::DIType *Ty : Tys) {
TypeInfo *TI;
IFR(GetTypeInfo(Ty, &TI));
DWORD dwNewLVID;
newVars.emplace_back(std::make_shared<symbol_factory::LocalVarInfo>());
std::shared_ptr<symbol_factory::LocalVarInfo> VI = newVars.back();
IFR(AddSymbol<symbol_factory::LocalVariable>(dwParentID, &dwNewLVID, LV,
dwLVTypeID, LVTy, VI));
VI->SetVarID(dwNewLVID);
VI->SetOffsetInUDT(dwOffsetInUDT);
static constexpr DWORD kNumBitsPerByte = 8;
dwOffsetInUDT += Ty->getSizeInBits() / kNumBitsPerByte;
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::GetTypeLayout(
llvm::DIType *Ty, std::vector<DWORD> *pRet) {
pRet->clear();
TypeInfo *TI;
IFR(GetTypeInfo(Ty, &TI));
for (llvm::DIType *T : TI->GetLayout()) {
TypeInfo *eTI;
IFR(GetTypeInfo(T, &eTI));
pRet->emplace_back(eTI->GetTypeID());
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateUDTField(
DWORD dwParentID, llvm::DIDerivedType *Field) {
auto *FieldTy = dyn_cast_to_ditype<llvm::DIType>(Field->getBaseType());
if (FieldTy == nullptr) {
return E_FAIL;
}
if (m_FieldToID.count(Field) != 0) {
return S_OK;
}
DWORD dwLVTypeID;
IFR(CreateType(FieldTy, &dwLVTypeID));
if (m_pCurUDT != nullptr) {
TypeInfo *lvTI;
IFR(GetTypeInfo(FieldTy, &lvTI));
#ifndef NDEBUG
const DWORD dwOffsetInBytes =
(lvTI->GetAlignmentInBytes() == 0)
? CurrentUDTInfo().GetCurrentSizeInBytes()
: llvm::RoundUpToAlignment(CurrentUDTInfo().GetCurrentSizeInBytes(),
lvTI->GetAlignmentInBytes());
DXASSERT_ARGS(dwOffsetInBytes == (unsigned)(Field->getOffsetInBits() / 8),
"%d vs %d", dwOffsetInBytes,
(unsigned)(Field->getOffsetInBits() / 8));
#endif
CurrentUDTInfo().Embed(*lvTI);
}
DWORD dwNewLVID;
IFR(AddSymbol<symbol_factory::UDTField>(dwParentID, &dwNewLVID, Field,
dwLVTypeID, FieldTy));
m_FieldToID.insert(std::make_pair(Field, dwNewLVID));
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateLocalVariables() {
llvm::Module *M = &m_Session.ModuleRef();
llvm::Function *DbgDeclare =
llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::dbg_declare);
for (llvm::Value *U : DbgDeclare->users()) {
auto *CI = llvm::dyn_cast<llvm::CallInst>(U);
auto *LS = llvm::dyn_cast_or_null<llvm::DILocalScope>(
CI->getDebugLoc()->getInlinedAtScope());
auto SymIt = m_ScopeToSym.find(LS);
if (SymIt == m_ScopeToSym.end()) {
continue;
}
auto *LocalNameMetadata =
llvm::dyn_cast<llvm::MetadataAsValue>(CI->getArgOperand(1));
if (auto *LV = llvm::dyn_cast<llvm::DILocalVariable>(
LocalNameMetadata->getMetadata())) {
const DWORD dwParentID = SymIt->second;
if (FAILED(CreateLocalVariable(dwParentID, LV))) {
continue;
}
}
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::CreateLiveRanges() {
// Simple algorithm:
// live_range = map from SymbolID to SymbolManager.LiveRange
// end_of_scope = map from Scope to RVA
// for each I in reverse(pSession.InstructionsRef):
// scope = I.scope
// if scope not in end_of_scope:
// end_of_scope[scope] = rva(I)
// if I is dbg.declare:
// live_range[symbol of I] = SymbolManager.LiveRange[FirstUseRVA,
// end_of_scope[scope]]
llvm::Module *M = &m_Session.ModuleRef();
m_SymToLR.clear();
const auto &Instrs = m_Session.InstructionsRef();
llvm::DenseMap<llvm::DILocalScope *, Session::RVA> EndOfScope;
for (auto It = Instrs.rbegin(); It != Instrs.rend(); ++It) {
const Session::RVA RVA = It->first;
const auto *I = It->second;
const llvm::DebugLoc &DL = I->getDebugLoc();
if (!DL) {
continue;
}
llvm::MDNode *LocalScope = DL.getScope();
if (LocalScope == nullptr) {
continue;
}
auto *LS = llvm::dyn_cast<llvm::DILocalScope>(LocalScope);
if (LS == nullptr) {
return E_FAIL;
}
if (EndOfScope.count(LS) == 0) {
EndOfScope.insert(std::make_pair(LS, RVA + 1));
}
auto endOfScopeRVA = EndOfScope.find(LS)->second;
DWORD Reg;
DWORD RegSize;
llvm::DILocalVariable *LV;
uint64_t StartOffset;
uint64_t EndOffset;
Session::RVA FirstUseRVA;
Session::RVA LastUseRVA;
HRESULT hr = IsDbgDeclareCall(M, I, &Reg, &RegSize, &LV, &StartOffset,
&EndOffset, &FirstUseRVA, &LastUseRVA);
if (hr != S_OK) {
continue;
}
endOfScopeRVA = std::max<Session::RVA>(endOfScopeRVA, LastUseRVA);
auto varIt = m_VarToID.find(LV);
if (varIt == m_VarToID.end()) {
// All variables should already have been seen and created.
return E_FAIL;
}
for (auto &Var : varIt->second) {
const DWORD dwOffsetInUDT = Var->GetOffsetInUDT();
if (dwOffsetInUDT < StartOffset || dwOffsetInUDT >= EndOffset) {
continue;
}
DXASSERT_ARGS((dwOffsetInUDT - StartOffset) % 4 == 0,
"Invalid byte offset %d into variable",
(dwOffsetInUDT - StartOffset));
const DWORD dwRegIndex = (dwOffsetInUDT - StartOffset) / 4;
if (dwRegIndex >= RegSize) {
continue;
}
Var->SetDxilRegister(Reg + dwRegIndex);
m_SymToLR[Var->GetVarID()] = SymbolManager::LiveRange{
static_cast<uint32_t>(FirstUseRVA),
endOfScopeRVA - static_cast<uint32_t>(FirstUseRVA)};
}
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::IsDbgDeclareCall(
llvm::Module *M, const llvm::Instruction *I, DWORD *pReg, DWORD *pRegSize,
llvm::DILocalVariable **LV, uint64_t *pStartOffset, uint64_t *pEndOffset,
dxil_dia::Session::RVA *pLowestUserRVA,
dxil_dia::Session::RVA *pHighestUserRVA) {
auto *CI = llvm::dyn_cast<llvm::CallInst>(I);
if (CI == nullptr) {
return S_FALSE;
}
llvm::Function *DbgDeclare =
llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::dbg_declare);
if (CI->getCalledFunction() != DbgDeclare) {
return S_FALSE;
}
*LV = nullptr;
*pReg = *pRegSize = 0;
*pStartOffset = *pEndOffset = 0;
*pLowestUserRVA = 0;
*pHighestUserRVA = 0;
std::vector<dxil_dia::Session::RVA> usesRVAs;
bool HasRegister = false;
if (auto *RegMV =
llvm::dyn_cast<llvm::MetadataAsValue>(CI->getArgOperand(0))) {
if (auto *RegVM =
llvm::dyn_cast<llvm::ValueAsMetadata>(RegMV->getMetadata())) {
if (auto *Reg = llvm::dyn_cast<llvm::Instruction>(RegVM->getValue())) {
HRESULT hr;
IFR(hr = GetDxilAllocaRegister(Reg, pReg, pRegSize));
if (hr != S_OK) {
return hr;
}
HasRegister = true;
llvm::iterator_range<llvm::Value::user_iterator> users = Reg->users();
for (llvm::User *user : users) {
auto *inst = llvm::dyn_cast<llvm::Instruction>(user);
if (inst != nullptr) {
auto rva = m_Session.RvaMapRef().find(inst);
usesRVAs.push_back(rva->second);
}
}
}
}
}
if (!HasRegister) {
return E_FAIL;
}
if (!usesRVAs.empty()) {
*pLowestUserRVA = *std::min_element(usesRVAs.begin(), usesRVAs.end());
*pHighestUserRVA = *std::max_element(usesRVAs.begin(), usesRVAs.end());
}
if (auto *LVMV =
llvm::dyn_cast<llvm::MetadataAsValue>(CI->getArgOperand(1))) {
*LV = llvm::dyn_cast<llvm::DILocalVariable>(LVMV->getMetadata());
if (*LV == nullptr) {
return E_FAIL;
}
}
if (auto *FieldsMV =
llvm::dyn_cast<llvm::MetadataAsValue>(CI->getArgOperand(2))) {
auto *Fields = llvm::dyn_cast<llvm::DIExpression>(FieldsMV->getMetadata());
if (Fields == nullptr) {
return E_FAIL;
}
static constexpr uint64_t kNumBytesPerDword = 4;
if (Fields->isBitPiece()) {
const uint64_t BitPieceOffset = Fields->getBitPieceOffset();
const uint64_t BitPieceSize = Fields->getBitPieceSize();
// dxcompiler had a bug (fixed in
// 4870297404a37269e24ddce7db3bd94a8110fff8) where the BitPieceSize
// was defined in bytes, not bits. We use the register size in bits to
// verify if Size is bits or bytes.
if (*pRegSize * kNumBytesPerDword == BitPieceSize) {
// Size is bytes.
*pStartOffset = BitPieceOffset;
*pEndOffset = *pStartOffset + BitPieceSize;
} else {
// Size is (should be) bits; pStartOffset/pEndOffset should be bytes.
// We don't expect to encounter bit pieces more granular than bytes.
static constexpr uint64_t kNumBitsPerByte = 8;
(void)kNumBitsPerByte;
assert(BitPieceOffset % kNumBitsPerByte == 0);
assert(BitPieceSize % kNumBitsPerByte == 0);
*pStartOffset = BitPieceOffset / kNumBitsPerByte;
*pEndOffset = *pStartOffset + (BitPieceSize / kNumBitsPerByte);
}
} else {
*pStartOffset = 0;
*pEndOffset = *pRegSize * kNumBytesPerDword;
}
}
return S_OK;
}
HRESULT dxil_dia::hlsl_symbols::SymbolManagerInit::GetDxilAllocaRegister(
llvm::Instruction *I, DWORD *pRegNum, DWORD *pRegSize) {
auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(I);
if (Alloca == nullptr) {
return S_FALSE;
}
std::uint32_t uRegNum;
std::uint32_t uRegSize;
if (!pix_dxil::PixAllocaReg::FromInst(Alloca, &uRegNum, &uRegSize)) {
return S_FALSE;
}
*pRegNum = uRegNum;
*pRegSize = uRegSize;
return S_OK;
}
HRESULT
dxil_dia::hlsl_symbols::SymbolManagerInit::PopulateParentToChildrenIDMap(
SymbolManager::ParentToChildrenMap *pParentToChildren) {
DXASSERT_ARGS(
m_SymCtors.size() == m_Parent.size(),
"parents vector must be the same size of symbols ctor vector: %d vs %d",
m_SymCtors.size(), m_Parent.size());
for (size_t i = 0; i < m_Parent.size(); ++i) {
#ifndef NDEBUG
{
CComPtr<Symbol> S;
IFT(m_SymCtors[i]->Create(&m_Session, &S));
DXASSERT_ARGS(S->GetID() == i + 1, "Invalid symbol index %d for %d",
S->GetID(), i + 1);
}
#endif // !NDEBUG
DXASSERT_ARGS(m_Parent[i] != kNullSymbolID || (i + 1) == HlslProgramId,
"Parentless symbol %d", i + 1);
if (m_Parent[i] != kNullSymbolID) {
pParentToChildren->emplace(m_Parent[i], i + 1);
}
}
return S_OK;
}
dxil_dia::SymbolManager::SymbolFactory::SymbolFactory(DWORD ID, DWORD ParentID)
: m_ID(ID), m_ParentID(ParentID) {}
dxil_dia::SymbolManager::SymbolFactory::~SymbolFactory() = default;
dxil_dia::SymbolManager::SymbolManager() = default;
dxil_dia::SymbolManager::~SymbolManager() { m_pSession = nullptr; }
void dxil_dia::SymbolManager::Init(Session *pSes) {
DXASSERT(m_pSession == nullptr, "SymbolManager already initialized");
m_pSession = pSes;
m_symbolCtors.clear();
m_parentToChildren.clear();
llvm::DebugInfoFinder &DIFinder = pSes->InfoRef();
if (DIFinder.compile_unit_count() != 1) {
throw hlsl::Exception(E_FAIL);
}
llvm::DICompileUnit *ShaderCU = *DIFinder.compile_units().begin();
hlsl_symbols::SymbolManagerInit SMI(pSes, &m_symbolCtors, &m_scopeToID,
&m_symbolToLiveRange);
DWORD dwHlslProgramID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::GlobalScope>(
kNullSymbolID, &dwHlslProgramID));
DXASSERT_ARGS(dwHlslProgramID == HlslProgramId, "%d vs %d", dwHlslProgramID,
HlslProgramId);
DWORD dwHlslCompilandID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::Compiland>(
dwHlslProgramID, &dwHlslCompilandID, ShaderCU));
m_scopeToID.insert(std::make_pair(ShaderCU, dwHlslCompilandID));
DXASSERT_ARGS(dwHlslCompilandID == HlslCompilandId, "%d vs %d",
dwHlslCompilandID, HlslCompilandId);
DWORD dwHlslCompilandDetailsId;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandDetails>(
dwHlslCompilandID, &dwHlslCompilandDetailsId));
DXASSERT_ARGS(dwHlslCompilandDetailsId == HlslCompilandDetailsId, "%d vs %d",
dwHlslCompilandDetailsId, HlslCompilandDetailsId);
DWORD dwHlslCompilandEnvFlagsID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandEnv<
hlsl_symbols::CompilandEnvSymbol::CreateFlags>>(
dwHlslCompilandID, &dwHlslCompilandEnvFlagsID));
DXASSERT_ARGS(dwHlslCompilandEnvFlagsID == HlslCompilandEnvFlagsId,
"%d vs %d", dwHlslCompilandEnvFlagsID, HlslCompilandEnvFlagsId);
DWORD dwHlslCompilandEnvTargetID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandEnv<
hlsl_symbols::CompilandEnvSymbol::CreateTarget>>(
dwHlslCompilandID, &dwHlslCompilandEnvTargetID));
DXASSERT_ARGS(dwHlslCompilandEnvTargetID == HlslCompilandEnvTargetId,
"%d vs %d", dwHlslCompilandEnvTargetID,
HlslCompilandEnvTargetId);
DWORD dwHlslCompilandEnvEntryID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandEnv<
hlsl_symbols::CompilandEnvSymbol::CreateEntry>>(
dwHlslCompilandID, &dwHlslCompilandEnvEntryID));
DXASSERT_ARGS(dwHlslCompilandEnvEntryID == HlslCompilandEnvEntryId,
"%d vs %d", dwHlslCompilandEnvEntryID, HlslCompilandEnvEntryId);
DWORD dwHlslCompilandEnvDefinesID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandEnv<
hlsl_symbols::CompilandEnvSymbol::CreateDefines>>(
dwHlslCompilandID, &dwHlslCompilandEnvDefinesID));
DXASSERT_ARGS(dwHlslCompilandEnvDefinesID == HlslCompilandEnvDefinesId,
"%d vs %d", dwHlslCompilandEnvDefinesID,
HlslCompilandEnvDefinesId);
DWORD dwHlslCompilandEnvArgumentsID;
IFT(SMI.AddSymbol<hlsl_symbols::symbol_factory::CompilandEnv<
hlsl_symbols::CompilandEnvSymbol::CreateArguments>>(
dwHlslCompilandID, &dwHlslCompilandEnvArgumentsID));
DXASSERT_ARGS(dwHlslCompilandEnvArgumentsID == HlslCompilandEnvArgumentsId,
"%d vs %d", dwHlslCompilandEnvArgumentsID,
HlslCompilandEnvArgumentsId);
IFT(SMI.CreateFunctionsForAllCUs());
IFT(SMI.CreateGlobalVariablesForAllCUs());
IFT(SMI.CreateLocalVariables());
IFT(SMI.CreateLiveRanges());
IFT(SMI.PopulateParentToChildrenIDMap(&m_parentToChildren));
}
HRESULT dxil_dia::SymbolManager::GetSymbolByID(size_t id,
Symbol **ppSym) const {
if (ppSym == nullptr) {
return E_INVALIDARG;
}
*ppSym = nullptr;
if (m_pSession == nullptr) {
return E_FAIL;
}
if (id <= 0) {
return E_INVALIDARG;
}
if (id > m_symbolCtors.size()) {
return S_FALSE;
}
DxcThreadMalloc TM(m_pSession->GetMallocNoRef());
IFR(m_symbolCtors[id - 1]->Create(m_pSession, ppSym));
return S_OK;
}
HRESULT dxil_dia::SymbolManager::GetLiveRangeOf(Symbol *pSym,
LiveRange *LR) const {
const DWORD dwSymID = pSym->GetID();
if (dwSymID <= 0 || dwSymID > m_symbolCtors.size()) {
return E_INVALIDARG;
}
auto symIt = m_symbolToLiveRange.find(dwSymID);
if (symIt == m_symbolToLiveRange.end()) {
return S_FALSE;
}
*LR = symIt->second;
return S_OK;
}
HRESULT dxil_dia::SymbolManager::GetGlobalScope(Symbol **ppSym) const {
return GetSymbolByID(HlslProgramId, ppSym);
}
HRESULT dxil_dia::SymbolManager::ChildrenOf(
DWORD ID, std::vector<CComPtr<Symbol>> *pChildren) const {
pChildren->clear();
auto childrenList = m_parentToChildren.equal_range(ID);
for (auto it = childrenList.first; it != childrenList.second; ++it) {
CComPtr<Symbol> Child;
IFR(GetSymbolByID(it->second, &Child));
pChildren->emplace_back(Child);
}
return S_OK;
}
HRESULT dxil_dia::SymbolManager::ChildrenOf(
Symbol *pSym, std::vector<CComPtr<Symbol>> *pChildren) const {
const std::uint32_t pSymID = pSym->GetID();
IFR(ChildrenOf(pSymID, pChildren));
return S_OK;
}
HRESULT
dxil_dia::SymbolManager::DbgScopeOf(const llvm::Instruction *instr,
SymbolChildrenEnumerator **ppRet) const {
*ppRet = nullptr;
const llvm::DebugLoc &DL = instr->getDebugLoc();
if (!DL) {
return S_FALSE;
}
llvm::MDNode *LocalScope = DL.getInlinedAtScope();
if (LocalScope == nullptr) {
LocalScope = DL.getScope();
}
if (LocalScope == nullptr) {
return S_FALSE;
}
auto *LS = llvm::dyn_cast<llvm::DILocalScope>(LocalScope);
if (LS == nullptr) {
// This is a failure as instructions should always live in a DILocalScope
return E_FAIL;
}
auto scopeIt = m_scopeToID.find(LS);
if (scopeIt == m_scopeToID.end()) {
// This is a failure because all scopes should already exist in the symbol
// manager.
return E_FAIL;
}
CComPtr<SymbolChildrenEnumerator> ret =
SymbolChildrenEnumerator::Alloc(m_pSession->GetMallocNoRef());
if (!ret) {
return E_OUTOFMEMORY;
}
CComPtr<Symbol> s;
IFR(GetSymbolByID(scopeIt->second, &s));
std::vector<CComPtr<Symbol>> children{s};
ret->Init(std::move(children));
*ppRet = ret.Detach();
return S_OK;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaEnumTables.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaEnumTable.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <array>
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class EnumTables : public IDiaEnumTables {
private:
DXC_MICROCOM_TM_REF_FIELDS()
protected:
CComPtr<Session> m_pSession;
unsigned m_next;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaEnumTables>(this, iid, ppvObject);
}
EnumTables(IMalloc *pMalloc, Session *pSession)
: m_dwRef(0), m_pMalloc(pMalloc), m_pSession(pSession), m_next(0) {
m_tables.fill(nullptr);
}
STDMETHODIMP get__NewEnum(
/* [retval][out] */ IUnknown **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_Count(LONG *pRetVal) override;
STDMETHODIMP Item(
/* [in] */ VARIANT index,
/* [retval][out] */ IDiaTable **table) override;
STDMETHODIMP Next(ULONG celt, IDiaTable **rgelt,
ULONG *pceltFetched) override;
STDMETHODIMP Skip(
/* [in] */ ULONG celt) override {
return ENotImpl();
}
STDMETHODIMP Reset(void) override;
STDMETHODIMP Clone(
/* [out] */ IDiaEnumTables **ppenum) override {
return ENotImpl();
}
static HRESULT Create(Session *pSession, IDiaEnumTables **ppEnumTables);
private:
std::array<CComPtr<IDiaTable>, (int)Table::LastKind + 1> m_tables;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/CMakeLists.txt | # Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
if (MSVC)
find_package(DiaSDK REQUIRED) # Used for constants and declarations.
endif (MSVC)
if (MSVC)
add_llvm_library(LLVMDxilDia
DxcPixCompilationInfo.cpp
DxcPixDxilDebugInfo.cpp
DxcPixDxilStorage.cpp
DxcPixEntrypoints.cpp
DxcPixLiveVariables.cpp
DxcPixLiveVariables_FragmentIterator.cpp
DxcPixTypes.cpp
DxcPixVariables.cpp
DxilDia.cpp
DxilDiaDataSource.cpp
DxilDiaEnumTables.cpp
DxilDiaSession.cpp
DxilDiaSymbolManager.cpp
DxilDiaTable.cpp
DxilDiaTableFrameData.cpp
DxilDiaTableInjectedSources.cpp
DxilDiaTableInputAssemblyFile.cpp
DxilDiaTableLineNumbers.cpp
DxilDiaTableSections.cpp
DxilDiaTableSegmentMap.cpp
DxilDiaTableSourceFiles.cpp
DxilDiaTableSymbols.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
else(MSVC)
# DxcPixLiveVariables_FragmentIterator is not dependent on dia.
# It is used by PixTest.
set(HLSL_IGNORE_SOURCES
DxcPixCompilationInfo.cpp
DxcPixDxilDebugInfo.cpp
DxcPixDxilStorage.cpp
DxcPixEntrypoints.cpp
DxcPixLiveVariables.cpp
DxcPixTypes.cpp
DxcPixVariables.cpp
DxilDia.cpp
DxilDiaDataSource.cpp
DxilDiaEnumTables.cpp
DxilDiaSession.cpp
DxilDiaSymbolManager.cpp
DxilDiaTable.cpp
DxilDiaTableFrameData.cpp
DxilDiaTableInjectedSources.cpp
DxilDiaTableInputAssemblyFile.cpp
DxilDiaTableLineNumbers.cpp
DxilDiaTableSections.cpp
DxilDiaTableSegmentMap.cpp
DxilDiaTableSourceFiles.cpp
DxilDiaTableSymbols.cpp
)
add_llvm_library(LLVMDxilDia
DxcPixLiveVariables_FragmentIterator.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
endif(MSVC)
if (MSVC)
target_link_libraries(LLVMDxilDia PRIVATE ${LIBRARIES} ${DIASDK_LIBRARIES})
include_directories(AFTER ${LLVM_INCLUDE_DIR}/dxc/Tracing ${DIASDK_INCLUDE_DIRS})
endif (MSVC)
add_dependencies(LLVMDxilDia LLVMDxilPIXPasses intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableInjectedSources.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableInjectedSources.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <vector>
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Metadata.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class InjectedSource : public IDiaInjectedSource {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<Session> m_pSession;
DWORD m_index;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaInjectedSource>(this, iid, ppvObject);
}
InjectedSource(IMalloc *pMalloc, Session *pSession, DWORD index)
: m_pMalloc(pMalloc), m_pSession(pSession), m_index(index) {}
llvm::MDTuple *NameContent();
llvm::StringRef Name();
llvm::StringRef Content();
STDMETHODIMP get_crc(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_length(ULONGLONG *pRetVal) override;
STDMETHODIMP get_filename(BSTR *pRetVal) override;
STDMETHODIMP get_objectFilename(BSTR *pRetVal) override;
STDMETHODIMP get_virtualFilename(BSTR *pRetVal) override;
STDMETHODIMP get_sourceCompression(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_source(
/* [in] */ DWORD cbData,
/* [out] */ DWORD *pcbData,
/* [size_is][out] */ BYTE *pbData) override;
};
class InjectedSourcesTable
: public impl::TableBase<IDiaEnumInjectedSources, IDiaInjectedSource> {
public:
InjectedSourcesTable(IMalloc *pMalloc, Session *pSession);
HRESULT GetItem(DWORD index, IDiaInjectedSource **ppItem) override;
void Init(llvm::StringRef filename);
private:
std::vector<unsigned> m_indexList;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixLiveVariables_FragmentIterator.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixLiveVariables_FragmentIterator.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Declares the FragmentIterator API. This API is used to traverse //
// DIVariables and assign alloca registers to DIBasicTypes. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <memory>
namespace llvm {
class AllocaInst;
class DataLayout;
class DbgDeclareInst;
class DIExpression;
} // namespace llvm
namespace dxil_debug_info {
class MemberIterator {
public:
virtual ~MemberIterator() = default;
virtual bool Next(unsigned *Index) = 0;
virtual unsigned SizeInBits(unsigned Index) const = 0;
virtual unsigned OffsetInBits(unsigned Index) = 0;
};
std::unique_ptr<MemberIterator>
CreateMemberIterator(llvm::DbgDeclareInst *DbgDeclare,
const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca, llvm::DIExpression *Expression);
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableLineNumbers.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableLineNumbers.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableLineNumbers.h"
#include <utility>
#include "llvm/IR/DebugInfoMetadata.h"
#include "DxilDiaSession.h"
dxil_dia::LineNumber::LineNumber(
/* [in] */ IMalloc *pMalloc,
/* [in] */ Session *pSession,
/* [in] */ const llvm::Instruction *inst)
: m_pMalloc(pMalloc), m_pSession(pSession), m_inst(inst) {}
const llvm::DebugLoc &dxil_dia::LineNumber::DL() const {
DXASSERT(bool(m_inst->getDebugLoc()),
"Trying to read line info from invalid debug location");
return m_inst->getDebugLoc();
}
STDMETHODIMP dxil_dia::LineNumber::get_sourceFile(
/* [retval][out] */ IDiaSourceFile **pRetVal) {
DWORD id;
HRESULT hr = get_sourceFileId(&id);
if (hr != S_OK)
return hr;
return m_pSession->findFileById(id, pRetVal);
}
STDMETHODIMP dxil_dia::LineNumber::get_lineNumber(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = DL().getLine();
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_lineNumberEnd(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = DL().getLine();
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_columnNumber(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = DL().getCol();
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_columnNumberEnd(
/* [retval][out] */ DWORD *pRetVal) {
*pRetVal = DL().getCol();
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_addressOffset(
/* [retval][out] */ DWORD *pRetVal) {
return get_relativeVirtualAddress(pRetVal);
}
STDMETHODIMP dxil_dia::LineNumber::get_relativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 0;
const auto &rvaMap = m_pSession->RvaMapRef();
auto it = rvaMap.find(m_inst);
if (it == rvaMap.end()) {
return E_FAIL;
}
*pRetVal = it->second;
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_length(
/* [retval][out] */ DWORD *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = 1;
if (llvm::DebugLoc DL = m_inst->getDebugLoc()) {
const auto &LineToColumn = m_pSession->LineToColumnStartMapRef();
auto it = LineToColumn.find(DL.getLine());
if (it != LineToColumn.end()) {
*pRetVal = it->second.Last - it->second.First;
}
}
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_statement(
/* [retval][out] */ BOOL *pRetVal) {
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = FALSE;
if (llvm::DebugLoc DL = m_inst->getDebugLoc()) {
const auto &LineToColumn = m_pSession->LineToColumnStartMapRef();
auto it = LineToColumn.find(DL.getLine());
if (it != LineToColumn.end()) {
*pRetVal = it->second.StartCol == DL.getCol();
}
}
return S_OK;
}
STDMETHODIMP dxil_dia::LineNumber::get_sourceFileId(
/* [retval][out] */ DWORD *pRetVal) {
llvm::MDNode *pScope = DL().getScope();
auto *pBlock = llvm::dyn_cast_or_null<llvm::DILexicalBlock>(pScope);
if (pBlock != nullptr) {
return m_pSession->getSourceFileIdByName(pBlock->getFile()->getFilename(),
pRetVal);
}
auto *pSubProgram = llvm::dyn_cast_or_null<llvm::DISubprogram>(pScope);
if (pSubProgram != nullptr) {
return m_pSession->getSourceFileIdByName(
pSubProgram->getFile()->getFilename(), pRetVal);
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::LineNumber::get_compilandId(
/* [retval][out] */ DWORD *pRetVal) {
// Single compiland for now, so pretty simple.
*pRetVal = HlslCompilandId;
return S_OK;
}
dxil_dia::LineNumbersTable::LineNumbersTable(IMalloc *pMalloc,
Session *pSession)
: impl::TableBase<IDiaEnumLineNumbers, IDiaLineNumber>(
pMalloc, pSession, Table::Kind::LineNumbers),
m_instructions(pSession->InstructionLinesRef()) {
m_count = m_instructions.size();
}
dxil_dia::LineNumbersTable::LineNumbersTable(
IMalloc *pMalloc, Session *pSession,
std::vector<const llvm::Instruction *> &&instructions)
: impl::TableBase<IDiaEnumLineNumbers, IDiaLineNumber>(
pMalloc, pSession, Table::Kind::LineNumbers),
m_instructions(m_instructionsStorage),
m_instructionsStorage(std::move(instructions)) {
m_count = m_instructions.size();
}
HRESULT dxil_dia::LineNumbersTable::GetItem(DWORD index,
IDiaLineNumber **ppItem) {
if (index >= m_instructions.size())
return E_INVALIDARG;
*ppItem =
CreateOnMalloc<LineNumber>(m_pMalloc, m_pSession, m_instructions[index]);
if (*ppItem == nullptr)
return E_OUTOFMEMORY;
(*ppItem)->AddRef();
return S_OK;
} |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableInjectedSources.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableInjectedSources.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableInjectedSources.h"
#include "DxilDia.h"
#include "DxilDiaSession.h"
#include "DxilDiaTable.h"
llvm::MDTuple *dxil_dia::InjectedSource::NameContent() {
return llvm::cast<llvm::MDTuple>(m_pSession->Contents()->getOperand(m_index));
}
llvm::StringRef dxil_dia::InjectedSource::Name() {
return llvm::dyn_cast<llvm::MDString>(NameContent()->getOperand(0))
->getString();
}
llvm::StringRef dxil_dia::InjectedSource::Content() {
return llvm::dyn_cast<llvm::MDString>(NameContent()->getOperand(1))
->getString();
}
STDMETHODIMP dxil_dia::InjectedSource::get_length(ULONGLONG *pRetVal) {
*pRetVal = Content().size();
return S_OK;
}
STDMETHODIMP dxil_dia::InjectedSource::get_filename(BSTR *pRetVal) {
DxcThreadMalloc TM(m_pMalloc);
return StringRefToBSTR(Name(), pRetVal);
}
STDMETHODIMP dxil_dia::InjectedSource::get_objectFilename(BSTR *pRetVal) {
*pRetVal = nullptr;
return S_OK;
}
STDMETHODIMP dxil_dia::InjectedSource::get_virtualFilename(BSTR *pRetVal) {
return get_filename(pRetVal);
}
STDMETHODIMP dxil_dia::InjectedSource::get_source(
/* [in] */ DWORD cbData,
/* [out] */ DWORD *pcbData,
/* [size_is][out] */ BYTE *pbData) {
if (pbData == nullptr) {
if (pcbData != nullptr) {
*pcbData = Content().size();
}
return S_OK;
}
cbData = std::min((DWORD)Content().size(), cbData);
memcpy(pbData, Content().begin(), cbData);
if (pcbData) {
*pcbData = cbData;
}
return S_OK;
}
dxil_dia::InjectedSourcesTable::InjectedSourcesTable(IMalloc *pMalloc,
Session *pSession)
: impl::TableBase<IDiaEnumInjectedSources, IDiaInjectedSource>(
pMalloc, pSession, Table::Kind::InjectedSource) {
// Count the number of source files available.
// m_count = m_pSession->InfoRef().compile_unit_count();
m_count = (m_pSession->Contents() == nullptr)
? 0
: m_pSession->Contents()->getNumOperands();
}
HRESULT dxil_dia::InjectedSourcesTable::GetItem(DWORD index,
IDiaInjectedSource **ppItem) {
if (index >= m_count)
return E_INVALIDARG;
unsigned itemIndex = index;
if (m_count == m_indexList.size())
itemIndex = m_indexList[index];
*ppItem = CreateOnMalloc<InjectedSource>(m_pMalloc, m_pSession, itemIndex);
if (*ppItem == nullptr)
return E_OUTOFMEMORY;
(*ppItem)->AddRef();
return S_OK;
}
void dxil_dia::InjectedSourcesTable::Init(llvm::StringRef filename) {
for (unsigned i = 0; i < m_pSession->Contents()->getNumOperands(); ++i) {
llvm::StringRef fn =
llvm::dyn_cast<llvm::MDString>(
m_pSession->Contents()->getOperand(i)->getOperand(0))
->getString();
if (fn.equals(filename)) {
m_indexList.emplace_back(i);
}
}
m_count = m_indexList.size();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/LLVMBuild.txt | ; Copyright (C) Microsoft Corporation. All rights reserved.
; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DxilDia
parent = Libraries
required_libraries = Core DxilPIXPasses DxcSupport Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSections.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSections.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableSections.h"
#include "DxilDiaSession.h"
dxil_dia::SectionsTable::SectionsTable(IMalloc *pMalloc, Session *pSession)
: impl::TableBase<IDiaEnumSectionContribs, IDiaSectionContrib>(
pMalloc, pSession, Table::Kind::Sections) {}
HRESULT dxil_dia::SectionsTable::GetItem(DWORD index,
IDiaSectionContrib **ppItem) {
*ppItem = nullptr;
return E_FAIL;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixEntrypoints.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixEntrypoints.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines all of the entrypoints for DXC's PIX interfaces for dealing with //
// debug info. These entrypoints are responsible for setting up a common, //
// sane environment -- e.g., exceptions are caught and returned as an //
// HRESULT -- deferring to the real implementations defined elsewhere in //
// this library. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "DxilDiaSession.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcpix.h"
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "DxcPixBase.h"
#include "DxcPixCompilationInfo.h"
#include "DxcPixDxilDebugInfo.h"
#include <functional>
namespace dxil_debug_info {
namespace entrypoints {
// OutParam/OutParamImpl provides a mechanism that entrypoints
// use to tag method arguments as OutParams. OutParams are
// automatically zero-initialized.
template <typename T> class OutParamImpl {
public:
OutParamImpl(T *V) : m_V(V) {
if (m_V != nullptr) {
*m_V = T();
}
}
operator T *() const { return m_V; }
private:
T *m_V;
};
template <typename T> OutParamImpl<T> OutParam(T *V) {
return OutParamImpl<T>(V);
}
// InParam/InParamImpl provides a mechanism that entrypoints
// use to tag method arguments as InParams. InParams are
// not zero-initialized.
template <typename T> struct InParamImpl {
public:
InParamImpl(const T *V) : m_V(V) {}
operator const T *() const { return m_V; }
private:
const T *m_V;
};
template <typename T> InParamImpl<T> InParam(T *V) { return InParamImpl<T>(V); }
// ThisPtr/ThisPtrImpl provides a mechanism that entrypoints
// use to tag method arguments as c++'s this. This values
// are not checked/initialized.
template <typename T> struct ThisPtrImpl {
public:
ThisPtrImpl(T *V) : m_V(V) {}
operator T *() const { return m_V; }
private:
T *m_V;
};
template <typename T> ThisPtrImpl<T> ThisPtr(T *V) { return ThisPtrImpl<T>(V); }
// CheckNotNull/CheckNotNullImpl provide a mechanism that entrypoints
// can use for automatic parameter validation. They will throw an
// exception if the given parameter is null.
template <typename T> class CheckNotNullImpl;
template <typename T> class CheckNotNullImpl<OutParamImpl<T>> {
public:
explicit CheckNotNullImpl(OutParamImpl<T> V) : m_V(V) {}
operator T *() const {
if (m_V == nullptr) {
throw hlsl::Exception(E_POINTER);
}
return m_V;
}
private:
T *m_V;
};
template <typename T> class CheckNotNullImpl<InParamImpl<T>> {
public:
explicit CheckNotNullImpl(InParamImpl<T> V) : m_V(V) {}
operator T *() const {
if (m_V == nullptr) {
throw hlsl::Exception(E_POINTER);
}
return m_V;
}
private:
T *m_V;
};
template <typename T> CheckNotNullImpl<T> CheckNotNull(T V) {
return CheckNotNullImpl<T>(V);
}
// WrapOutParams will wrap any OutParams<T> that the
// entrypoints provide to SetupAndRun -- which is essentially
// the method that runs the actual methods.
void WrapOutParams(IMalloc *) {}
template <typename T> struct EntrypointWrapper;
// WrapOutParams' specialization that detects OutParams that
// inherit from IUnknown. Any OutParams inheriting from IUnknown
// should be wrapped by one of the classes in this file so that
// user calls will be safely run.
template <typename T,
typename = typename std::enable_if<
std::is_base_of<IUnknown, T>::value>::type,
typename... O>
void WrapOutParams(IMalloc *M, CheckNotNullImpl<OutParamImpl<T *>> ppOut,
O... Others) {
if (*ppOut) {
NewDxcPixDxilDebugInfoObjectOrThrow<typename EntrypointWrapper<T *>::type>(
(T **)ppOut, M, *ppOut);
}
WrapOutParams(M, Others...);
}
template <typename T, typename... O>
void WrapOutParams(IMalloc *M, T, O... Others) {
WrapOutParams(M, Others...);
}
// DEFINE_ENTRYPOINT_WRAPPER_TRAIT is a helper macro that every entrypoint
// should use in order to define the EntrypointWrapper traits class for
// the interface it implements.
#define DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IInterface) \
template <> struct EntrypointWrapper<IInterface *> { \
using type = IInterface##Entrypoint; \
};
// IsValidArgType exposes a static method named check(), which returns
// true if <T> is a valid type for a method argument, and false otherwise.
// This is trying to ensure all pointers are checked, and all out params
// are default-initialized.
template <typename T> struct IsValidArgType {
static void check() {}
};
template <typename T> struct IsValidArgType<T *> {
static void check() {
static_assert(false, "Pointer arguments should be checked and wrapped"
" with InParam/OutParam, or marked with ThisPtr()");
}
};
template <typename T> struct IsValidArgType<InParamImpl<T>> {
static void check() {
static_assert(false, "InParams should be checked for nullptrs");
}
};
template <typename T> struct IsValidArgType<OutParamImpl<T>> {
static void check() {
static_assert(false, "InParams should be checked for nullptrs");
}
};
void EnsureAllPointersAreChecked() {}
template <typename T, typename... O>
void EnsureAllPointersAreChecked(T, O... o) {
IsValidArgType<T>::check();
EnsureAllPointersAreChecked(o...);
}
// SetupAndRun is the function that sets up the environment
// in which all of the user requests to the DxcPix library
// run under.
template <typename H, typename... A>
HRESULT SetupAndRun(IMalloc *M, H Handler, A... Args) {
DxcThreadMalloc TM(M);
HRESULT hr = E_FAIL;
try {
::llvm::sys::fs::MSFileSystem *msfPtr;
IFT(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
EnsureAllPointersAreChecked(Args...);
hr = Handler(Args...);
WrapOutParams(M, Args...);
} catch (const hlsl::Exception &e) {
hr = e.hr;
} catch (const std::bad_alloc &) {
hr = E_OUTOFMEMORY;
} catch (const std::exception &) {
hr = E_FAIL;
}
return hr;
}
HRESULT CreateEntrypointWrapper(IMalloc *pMalloc, IUnknown *pReal, REFIID iid,
void **ppvObject);
// Entrypoint is the base class for all entrypoints, providing
// the default QueryInterface implementation, as well as a
// more convenient way of calling SetupAndRun.
template <typename I, typename IParent = I> class Entrypoint : public I {
protected:
using IInterface = I;
Entrypoint(IMalloc *pMalloc, IInterface *pI)
: m_pMalloc(pMalloc), m_pReal(pI) {}
DXC_MICROCOM_TM_REF_FIELDS();
CComPtr<IInterface> m_pReal;
template <typename F, typename... A> HRESULT InvokeOnReal(F pFn, A... Args) {
return SetupAndRun(m_pMalloc, std::mem_fn(pFn), m_pReal, Args...);
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL();
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override final {
return SetupAndRun(
m_pMalloc,
std::mem_fn(&Entrypoint<IInterface, IParent>::QueryInterfaceImpl),
ThisPtr(this), iid, CheckNotNull(OutParam(ppvObject)));
}
HRESULT STDMETHODCALLTYPE QueryInterfaceImpl(REFIID iid, void **ppvObject) {
// Special-casing so we don't need to create a new wrapper.
if (iid == __uuidof(IInterface) || iid == __uuidof(IParent) ||
iid == __uuidof(IUnknown) || iid == __uuidof(INoMarshal)) {
this->AddRef();
*ppvObject = this;
return S_OK;
}
CComPtr<IUnknown> RealQI;
IFR(m_pReal->QueryInterface(iid, (void **)&RealQI));
return CreateEntrypointWrapper(m_pMalloc, RealQI, iid, ppvObject);
}
};
#define DEFINE_ENTRYPOINT_BOILERPLATE(Name) \
Name(IMalloc *M, IInterface *pI) : Entrypoint<IInterface>(M, pI) {} \
DXC_MICROCOM_TM_ALLOC(Name)
#define DEFINE_ENTRYPOINT_BOILERPLATE2(Name, ParentIFace) \
Name(IMalloc *M, IInterface *pI) \
: Entrypoint<IInterface, ParentIFace>(M, pI) {} \
DXC_MICROCOM_TM_ALLOC(Name)
struct IUnknownEntrypoint : public Entrypoint<IUnknown> {
DEFINE_ENTRYPOINT_BOILERPLATE(IUnknownEntrypoint);
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IUnknown);
struct IDxcPixTypeEntrypoint : public Entrypoint<IDxcPixType> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixTypeEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixType);
struct IDxcPixConstTypeEntrypoint : public Entrypoint<IDxcPixConstType> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixConstTypeEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixConstType);
struct IDxcPixTypedefTypeEntrypoint : public Entrypoint<IDxcPixTypedefType> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixTypedefTypeEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixTypedefType);
struct IDxcPixScalarTypeEntrypoint : public Entrypoint<IDxcPixScalarType> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixScalarTypeEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixScalarType);
struct IDxcPixArrayTypeEntrypoint : public Entrypoint<IDxcPixArrayType> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixArrayTypeEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
STDMETHODIMP GetNumElements(DWORD *ppNumElements) override {
return InvokeOnReal(&IInterface::GetNumElements,
CheckNotNull(OutParam(ppNumElements)));
}
STDMETHODIMP GetIndexedType(IDxcPixType **ppElementType) override {
return InvokeOnReal(&IInterface::GetIndexedType,
CheckNotNull(OutParam(ppElementType)));
}
STDMETHODIMP GetElementType(IDxcPixType **ppElementType) override {
return InvokeOnReal(&IInterface::GetElementType,
CheckNotNull(OutParam(ppElementType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixArrayType);
struct IDxcPixStructFieldEntrypoint
: public Entrypoint<IDxcPixStructField, IDxcPixStructField0> {
DEFINE_ENTRYPOINT_BOILERPLATE2(IDxcPixStructFieldEntrypoint,
IDxcPixStructField0);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetType(IDxcPixType **ppType) override {
return InvokeOnReal(&IInterface::GetType, CheckNotNull(OutParam(ppType)));
}
STDMETHODIMP GetFieldSizeInBits(DWORD *pFieldSizeInBits) override {
return InvokeOnReal(&IInterface::GetFieldSizeInBits,
CheckNotNull(OutParam(pFieldSizeInBits)));
}
STDMETHODIMP GetOffsetInBits(DWORD *pOffsetInBits) override {
return InvokeOnReal(&IInterface::GetOffsetInBits,
CheckNotNull(OutParam(pOffsetInBits)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixStructField);
struct IDxcPixStructType2Entrypoint : public Entrypoint<IDxcPixStructType2> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixStructType2Entrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetSizeInBits(DWORD *SizeInBits) override {
return InvokeOnReal(&IInterface::GetSizeInBits,
CheckNotNull(OutParam(SizeInBits)));
}
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override {
return InvokeOnReal(&IInterface::UnAlias,
CheckNotNull(OutParam(ppBaseType)));
}
STDMETHODIMP GetNumFields(DWORD *ppNumFields) override {
return InvokeOnReal(&IInterface::GetNumFields,
CheckNotNull(OutParam(ppNumFields)));
}
STDMETHODIMP GetFieldByIndex(DWORD dwIndex,
IDxcPixStructField **ppField) override {
return InvokeOnReal(&IInterface::GetFieldByIndex, dwIndex,
CheckNotNull(OutParam(ppField)));
}
STDMETHODIMP GetFieldByName(LPCWSTR lpName,
IDxcPixStructField **ppField) override {
return InvokeOnReal(&IInterface::GetFieldByName,
CheckNotNull(InParam(lpName)),
CheckNotNull(OutParam(ppField)));
}
STDMETHODIMP GetBaseType(IDxcPixType **ppType) override {
return InvokeOnReal(&IInterface::GetBaseType,
CheckNotNull(OutParam(ppType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixStructType2);
struct IDxcPixDxilStorageEntrypoint : public Entrypoint<IDxcPixDxilStorage> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixDxilStorageEntrypoint);
STDMETHODIMP AccessField(LPCWSTR Name,
IDxcPixDxilStorage **ppResult) override {
return InvokeOnReal(&IInterface::AccessField, CheckNotNull(InParam(Name)),
CheckNotNull(OutParam(ppResult)));
}
STDMETHODIMP Index(DWORD Index, IDxcPixDxilStorage **ppResult) override {
return InvokeOnReal(&IInterface::Index, Index,
CheckNotNull(OutParam(ppResult)));
}
STDMETHODIMP GetRegisterNumber(DWORD *pRegNum) override {
return InvokeOnReal(&IInterface::GetRegisterNumber,
CheckNotNull(OutParam(pRegNum)));
}
STDMETHODIMP GetIsAlive() override {
return InvokeOnReal(&IInterface::GetIsAlive);
}
STDMETHODIMP GetType(IDxcPixType **ppType) override {
return InvokeOnReal(&IInterface::GetType, CheckNotNull(OutParam(ppType)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixDxilStorage);
struct IDxcPixVariableEntrypoint : public Entrypoint<IDxcPixVariable> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixVariableEntrypoint);
STDMETHODIMP GetName(BSTR *Name) override {
return InvokeOnReal(&IInterface::GetName, CheckNotNull(OutParam(Name)));
}
STDMETHODIMP GetType(IDxcPixType **ppType) override {
return InvokeOnReal(&IInterface::GetType, CheckNotNull(OutParam(ppType)));
}
STDMETHODIMP GetStorage(IDxcPixDxilStorage **ppStorage) override {
return InvokeOnReal(&IInterface::GetStorage,
CheckNotNull(OutParam(ppStorage)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixVariable);
struct IDxcPixDxilLiveVariablesEntrypoint
: public Entrypoint<IDxcPixDxilLiveVariables> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixDxilLiveVariablesEntrypoint);
STDMETHODIMP GetCount(DWORD *dwSize) override {
return InvokeOnReal(&IInterface::GetCount, CheckNotNull(OutParam(dwSize)));
}
STDMETHODIMP GetVariableByIndex(DWORD Index,
IDxcPixVariable **ppVariable) override {
return InvokeOnReal(&IInterface::GetVariableByIndex, Index,
CheckNotNull(OutParam(ppVariable)));
}
STDMETHODIMP GetVariableByName(LPCWSTR Name,
IDxcPixVariable **ppVariable) override {
return InvokeOnReal(&IInterface::GetVariableByName,
CheckNotNull(InParam(Name)),
CheckNotNull(OutParam(ppVariable)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixDxilLiveVariables);
struct IDxcPixDxilDebugInfoEntrypoint
: public Entrypoint<IDxcPixDxilDebugInfo> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixDxilDebugInfoEntrypoint);
STDMETHODIMP
GetLiveVariablesAt(DWORD InstructionOffset,
IDxcPixDxilLiveVariables **ppLiveVariables) override {
return InvokeOnReal(&IInterface::GetLiveVariablesAt, InstructionOffset,
CheckNotNull(OutParam(ppLiveVariables)));
}
STDMETHODIMP IsVariableInRegister(DWORD InstructionOffset,
const wchar_t *VariableName) override {
return InvokeOnReal(&IInterface::IsVariableInRegister, InstructionOffset,
CheckNotNull(InParam(VariableName)));
}
STDMETHODIMP GetFunctionName(DWORD InstructionOffset,
BSTR *ppFunctionName) override {
return InvokeOnReal(&IInterface::GetFunctionName, InstructionOffset,
CheckNotNull(OutParam(ppFunctionName)));
}
STDMETHODIMP GetStackDepth(DWORD InstructionOffset,
DWORD *StackDepth) override {
return InvokeOnReal(&IInterface::GetStackDepth, InstructionOffset,
CheckNotNull(OutParam(StackDepth)));
}
STDMETHODIMP InstructionOffsetsFromSourceLocation(
const wchar_t *FileName, DWORD SourceLine, DWORD SourceColumn,
IDxcPixDxilInstructionOffsets **ppOffsets) override {
return InvokeOnReal(&IInterface::InstructionOffsetsFromSourceLocation,
CheckNotNull(InParam(FileName)), SourceLine,
SourceColumn, CheckNotNull(OutParam(ppOffsets)));
}
STDMETHODIMP SourceLocationsFromInstructionOffset(
DWORD InstructionOffset,
IDxcPixDxilSourceLocations **ppSourceLocations) override {
return InvokeOnReal(&IInterface::SourceLocationsFromInstructionOffset,
InstructionOffset,
CheckNotNull(OutParam(ppSourceLocations)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixDxilDebugInfo);
struct IDxcPixDxilInstructionOffsetsEntrypoint
: public Entrypoint<IDxcPixDxilInstructionOffsets> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixDxilInstructionOffsetsEntrypoint);
STDMETHODIMP_(DWORD) GetCount() override {
return InvokeOnReal(&IInterface::GetCount);
}
STDMETHODIMP_(DWORD) GetOffsetByIndex(DWORD Index) override {
return InvokeOnReal(&IInterface::GetOffsetByIndex, Index);
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixDxilInstructionOffsets);
struct IDxcPixDxilSourceLocationsEntrypoint
: public Entrypoint<IDxcPixDxilSourceLocations> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixDxilSourceLocationsEntrypoint);
STDMETHODIMP_(DWORD) GetCount() override {
return InvokeOnReal(&IInterface::GetCount);
}
STDMETHODIMP_(DWORD) GetLineNumberByIndex(DWORD Index) override {
return InvokeOnReal(&IInterface::GetLineNumberByIndex, Index);
}
STDMETHODIMP_(DWORD) GetColumnByIndex(DWORD Index) override {
return InvokeOnReal(&IInterface::GetColumnByIndex, Index);
}
STDMETHODIMP GetFileNameByIndex(DWORD Index, BSTR *Name) override {
return InvokeOnReal(&IInterface::GetFileNameByIndex, Index,
CheckNotNull(OutParam(Name)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixDxilSourceLocations);
struct IDxcPixCompilationInfoEntrypoint
: public Entrypoint<IDxcPixCompilationInfo> {
DEFINE_ENTRYPOINT_BOILERPLATE(IDxcPixCompilationInfoEntrypoint);
virtual STDMETHODIMP GetSourceFile(DWORD SourceFileOrdinal, BSTR *pSourceName,
BSTR *pSourceContents) override {
return InvokeOnReal(&IInterface::GetSourceFile, SourceFileOrdinal,
CheckNotNull(OutParam(pSourceName)),
CheckNotNull(OutParam(pSourceContents)));
}
virtual STDMETHODIMP GetArguments(BSTR *pArguments) override {
return InvokeOnReal(&IInterface::GetArguments,
CheckNotNull(OutParam(pArguments)));
}
virtual STDMETHODIMP GetMacroDefinitions(BSTR *pMacroDefinitions) override {
return InvokeOnReal(&IInterface::GetMacroDefinitions,
CheckNotNull(OutParam(pMacroDefinitions)));
}
virtual STDMETHODIMP GetEntryPointFile(BSTR *pEntryPointFile) override {
return InvokeOnReal(&IInterface::GetEntryPointFile,
CheckNotNull(OutParam(pEntryPointFile)));
}
virtual STDMETHODIMP GetHlslTarget(BSTR *pHlslTarget) override {
return InvokeOnReal(&IInterface::GetHlslTarget,
CheckNotNull(OutParam(pHlslTarget)));
}
virtual STDMETHODIMP GetEntryPoint(BSTR *pEntryPoint) override {
return InvokeOnReal(&IInterface::GetEntryPoint,
CheckNotNull(OutParam(pEntryPoint)));
}
};
DEFINE_ENTRYPOINT_WRAPPER_TRAIT(IDxcPixCompilationInfo);
HRESULT CreateEntrypointWrapper(IMalloc *pMalloc, IUnknown *pReal, REFIID riid,
void **ppvObject) {
#define HANDLE_INTERFACE(IInterface, ImplInterface) \
if (__uuidof(IInterface) == riid) { \
return NewDxcPixDxilDebugInfoObjectOrThrow<ImplInterface##Entrypoint>( \
(IInterface **)ppvObject, pMalloc, (ImplInterface *)pReal); \
} \
(void)0
HANDLE_INTERFACE(IUnknown, IUnknown);
HANDLE_INTERFACE(IDxcPixType, IDxcPixType);
HANDLE_INTERFACE(IDxcPixConstType, IDxcPixConstType);
HANDLE_INTERFACE(IDxcPixTypedefType, IDxcPixTypedefType);
HANDLE_INTERFACE(IDxcPixScalarType, IDxcPixScalarType);
HANDLE_INTERFACE(IDxcPixArrayType, IDxcPixArrayType);
HANDLE_INTERFACE(IDxcPixStructField, IDxcPixStructField);
HANDLE_INTERFACE(IDxcPixStructType, IDxcPixStructType2);
HANDLE_INTERFACE(IDxcPixStructType2, IDxcPixStructType2);
HANDLE_INTERFACE(IDxcPixDxilStorage, IDxcPixDxilStorage);
HANDLE_INTERFACE(IDxcPixVariable, IDxcPixVariable);
HANDLE_INTERFACE(IDxcPixDxilLiveVariables, IDxcPixDxilLiveVariables);
HANDLE_INTERFACE(IDxcPixDxilDebugInfo, IDxcPixDxilDebugInfo);
HANDLE_INTERFACE(IDxcPixCompilationInfo, IDxcPixCompilationInfo);
return E_FAIL;
}
} // namespace entrypoints
} // namespace dxil_debug_info
#include "DxilDiaSession.h"
using namespace dxil_debug_info::entrypoints;
static STDMETHODIMP
NewDxcPixDxilDebugInfoImpl(IMalloc *pMalloc, dxil_dia::Session *pSession,
IDxcPixDxilDebugInfo **ppDxilDebugInfo) {
return dxil_debug_info::NewDxcPixDxilDebugInfoObjectOrThrow<
dxil_debug_info::DxcPixDxilDebugInfo>(ppDxilDebugInfo, pMalloc, pSession);
}
STDMETHODIMP dxil_dia::Session::NewDxcPixDxilDebugInfo(
IDxcPixDxilDebugInfo **ppDxilDebugInfo) {
return SetupAndRun(m_pMalloc, &NewDxcPixDxilDebugInfoImpl, m_pMalloc,
ThisPtr(this), CheckNotNull(OutParam(ppDxilDebugInfo)));
}
static STDMETHODIMP
NewDxcPixCompilationInfoImpl(IMalloc *pMalloc, dxil_dia::Session *pSession,
IDxcPixCompilationInfo **ppCompilationInfo) {
return dxil_debug_info::CreateDxilCompilationInfo(pMalloc, pSession,
ppCompilationInfo);
}
STDMETHODIMP dxil_dia::Session::NewDxcPixCompilationInfo(
IDxcPixCompilationInfo **ppCompilationInfo) {
return SetupAndRun(m_pMalloc, &NewDxcPixCompilationInfoImpl, m_pMalloc,
ThisPtr(this), CheckNotNull(OutParam(ppCompilationInfo)));
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDia.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDia.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "llvm/ADT/StringRef.h"
namespace dxil_dia {
// Single program, single compiland allows for some simplifications.
static constexpr DWORD HlslProgramId = 1;
static constexpr DWORD HlslCompilandId = 2;
static constexpr DWORD HlslCompilandDetailsId = 3;
static constexpr DWORD HlslCompilandEnvFlagsId = 4;
static constexpr DWORD HlslCompilandEnvTargetId = 5;
static constexpr DWORD HlslCompilandEnvEntryId = 6;
static constexpr DWORD HlslCompilandEnvDefinesId = 7;
static constexpr DWORD HlslCompilandEnvArgumentsId = 8;
HRESULT ENotImpl();
HRESULT StringRefToBSTR(llvm::StringRef value, BSTR *pRetVal);
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaSession.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaSession.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
#include "dia2.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/dxcpix.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaSymbolManager.h"
namespace dxil_dia {
class Session : public IDiaSession, public IDxcPixDxilDebugInfoFactory {
public:
using RVA = unsigned;
using RVAMap = std::map<RVA, const llvm::Instruction *>;
struct LineInfo {
LineInfo(std::uint32_t start_col, RVA first, RVA last)
: StartCol(start_col), First(first), Last(last) {}
std::uint32_t StartCol = 0;
RVA First = 0;
RVA Last = 0;
};
using LineToInfoMap = std::unordered_map<std::uint32_t, LineInfo>;
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_CTOR(Session)
IMalloc *GetMallocNoRef() { return m_pMalloc.p; }
void Init(std::shared_ptr<llvm::LLVMContext> context,
std::shared_ptr<llvm::Module> mod,
std::shared_ptr<llvm::DebugInfoFinder> finder);
llvm::NamedMDNode *Contents() { return m_contents; }
llvm::NamedMDNode *Defines() { return m_defines; }
llvm::NamedMDNode *MainFileName() { return m_mainFileName; }
llvm::NamedMDNode *Arguments() { return m_arguments; }
hlsl::DxilModule &DxilModuleRef() { return *m_dxilModule.get(); }
llvm::Module &ModuleRef() { return *m_module.get(); }
llvm::DebugInfoFinder &InfoRef() { return *m_finder.get(); }
const SymbolManager &SymMgr();
const RVAMap &InstructionsRef() const { return m_instructions; }
const std::vector<const llvm::Instruction *> &InstructionLinesRef() const {
return m_instructionLines;
}
const std::unordered_map<const llvm::Instruction *, RVA> &RvaMapRef() const {
return m_rvaMap;
}
const LineToInfoMap &LineToColumnStartMapRef() const {
return m_lineToInfoMap;
}
HRESULT getSourceFileIdByName(llvm::StringRef fileName, DWORD *pRetVal);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaSession, IDxcPixDxilDebugInfoFactory>(
this, iid, ppvObject);
}
STDMETHODIMP get_loadAddress(
/* [retval][out] */ ULONGLONG *pRetVal) override;
STDMETHODIMP put_loadAddress(
/* [in] */ ULONGLONG NewVal) override {
return ENotImpl();
}
STDMETHODIMP get_globalScope(
/* [retval][out] */ IDiaSymbol **pRetVal) override;
STDMETHODIMP getEnumTables(IDiaEnumTables **ppEnumTables) override;
STDMETHODIMP getSymbolsByAddr(
/* [out] */ IDiaEnumSymbolsByAddr **ppEnumbyAddr) override {
return ENotImpl();
}
STDMETHODIMP findChildren(
/* [in] */ IDiaSymbol *parent,
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenEx(
/* [in] */ IDiaSymbol *parent,
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenExByAddr(
/* [in] */ IDiaSymbol *parent,
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenExByVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ ULONGLONG va,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenExByRVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByAddr(
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByRVA(
/* [in] */ DWORD rva,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByVA(
/* [in] */ ULONGLONG va,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByToken(
/* [in] */ ULONG token,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol) override {
return ENotImpl();
}
STDMETHODIMP symsAreEquiv(
/* [in] */ IDiaSymbol *symbolA,
/* [in] */ IDiaSymbol *symbolB) override {
return ENotImpl();
}
STDMETHODIMP symbolById(
/* [in] */ DWORD id,
/* [out] */ IDiaSymbol **ppSymbol) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByRVAEx(
/* [in] */ DWORD rva,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol,
/* [out] */ long *displacement) override {
return ENotImpl();
}
STDMETHODIMP findSymbolByVAEx(
/* [in] */ ULONGLONG va,
/* [in] */ enum SymTagEnum symtag,
/* [out] */ IDiaSymbol **ppSymbol,
/* [out] */ long *displacement) override {
return ENotImpl();
}
STDMETHODIMP findFile(
/* [in] */ IDiaSymbol *pCompiland,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSourceFiles **ppResult) override;
STDMETHODIMP findFileById(
/* [in] */ DWORD uniqueId,
/* [out] */ IDiaSourceFile **ppResult) override;
STDMETHODIMP findLines(
/* [in] */ IDiaSymbol *compiland,
/* [in] */ IDiaSourceFile *file,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findLinesByAddr(
/* [in] */ DWORD seg,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override;
STDMETHODIMP findLinesByRVA(
/* [in] */ DWORD rva,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override;
STDMETHODIMP findLinesByVA(
/* [in] */ ULONGLONG va,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findLinesByLinenum(
/* [in] */ IDiaSymbol *compiland,
/* [in] */ IDiaSourceFile *file,
/* [in] */ DWORD linenum,
/* [in] */ DWORD column,
/* [out] */ IDiaEnumLineNumbers **ppResult) override;
STDMETHODIMP findInjectedSource(
/* [in] */ LPCOLESTR srcFile,
/* [out] */ IDiaEnumInjectedSources **ppResult) override;
STDMETHODIMP getEnumDebugStreams(
/* [out] */ IDiaEnumDebugStreams **ppEnumDebugStreams) override {
return ENotImpl();
}
STDMETHODIMP findInlineFramesByAddr(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [out] */ IDiaEnumSymbols **ppResult) override;
STDMETHODIMP findInlineFramesByRVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineFramesByVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ ULONGLONG va,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLines(
/* [in] */ IDiaSymbol *parent,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByAddr(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override;
STDMETHODIMP findInlineeLinesByRVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD rva,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByVA(
/* [in] */ IDiaSymbol *parent,
/* [in] */ ULONGLONG va,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByLinenum(
/* [in] */ IDiaSymbol *compiland,
/* [in] */ IDiaSourceFile *file,
/* [in] */ DWORD linenum,
/* [in] */ DWORD column,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineesByName(
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD option,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findAcceleratorInlineeLinesByLinenum(
/* [in] */ IDiaSymbol *parent,
/* [in] */ IDiaSourceFile *file,
/* [in] */ DWORD linenum,
/* [in] */ DWORD column,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findSymbolsForAcceleratorPointerTag(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD tagValue,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findSymbolsByRVAForAcceleratorPointerTag(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD tagValue,
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findAcceleratorInlineesByName(
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD option,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP addressForVA(
/* [in] */ ULONGLONG va,
/* [out] */ DWORD *pISect,
/* [out] */ DWORD *pOffset) override {
return ENotImpl();
}
STDMETHODIMP addressForRVA(
/* [in] */ DWORD rva,
/* [out] */ DWORD *pISect,
/* [out] */ DWORD *pOffset) override {
return ENotImpl();
}
STDMETHODIMP findILOffsetsByAddr(
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findILOffsetsByRVA(
/* [in] */ DWORD rva,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findILOffsetsByVA(
/* [in] */ ULONGLONG va,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInputAssemblyFiles(
/* [out] */ IDiaEnumInputAssemblyFiles **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInputAssembly(
/* [in] */ DWORD index,
/* [out] */ IDiaInputAssemblyFile **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInputAssemblyById(
/* [in] */ DWORD uniqueId,
/* [out] */ IDiaInputAssemblyFile **ppResult) override {
return ENotImpl();
}
STDMETHODIMP getFuncMDTokenMapSize(
/* [out] */ DWORD *pcb) override {
return ENotImpl();
}
STDMETHODIMP getFuncMDTokenMap(
/* [in] */ DWORD cb,
/* [out] */ DWORD *pcb,
/* [size_is][out] */ BYTE *pb) override {
return ENotImpl();
}
STDMETHODIMP getTypeMDTokenMapSize(
/* [out] */ DWORD *pcb) override {
return ENotImpl();
}
STDMETHODIMP getTypeMDTokenMap(
/* [in] */ DWORD cb,
/* [out] */ DWORD *pcb,
/* [size_is][out] */ BYTE *pb) override {
return ENotImpl();
}
STDMETHODIMP getNumberOfFunctionFragments_VA(
/* [in] */ ULONGLONG vaFunc,
/* [in] */ DWORD cbFunc,
/* [out] */ DWORD *pNumFragments) override {
return ENotImpl();
}
STDMETHODIMP getNumberOfFunctionFragments_RVA(
/* [in] */ DWORD rvaFunc,
/* [in] */ DWORD cbFunc,
/* [out] */ DWORD *pNumFragments) override {
return ENotImpl();
}
STDMETHODIMP getFunctionFragments_VA(
/* [in] */ ULONGLONG vaFunc,
/* [in] */ DWORD cbFunc,
/* [in] */ DWORD cFragments,
/* [size_is][out] */ ULONGLONG *pVaFragment,
/* [size_is][out] */ DWORD *pLenFragment) override {
return ENotImpl();
}
STDMETHODIMP getFunctionFragments_RVA(
/* [in] */ DWORD rvaFunc,
/* [in] */ DWORD cbFunc,
/* [in] */ DWORD cFragments,
/* [size_is][out] */ DWORD *pRvaFragment,
/* [size_is][out] */ DWORD *pLenFragment) override {
return ENotImpl();
}
STDMETHODIMP getExports(
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP getHeapAllocationSites(
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInputAssemblyFile(
/* [in] */ IDiaSymbol *pSymbol,
/* [out] */ IDiaInputAssemblyFile **ppResult) override {
return ENotImpl();
}
STDMETHODIMP
NewDxcPixDxilDebugInfo(IDxcPixDxilDebugInfo **ppDxilDebugInfo) override;
STDMETHODIMP
NewDxcPixCompilationInfo(IDxcPixCompilationInfo **ppCompilationInfo) override;
private:
DXC_MICROCOM_TM_REF_FIELDS()
std::shared_ptr<llvm::LLVMContext> m_context;
std::shared_ptr<llvm::Module> m_module;
std::shared_ptr<llvm::DebugInfoFinder> m_finder;
std::unique_ptr<hlsl::DxilModule> m_dxilModule;
llvm::NamedMDNode *m_contents;
llvm::NamedMDNode *m_defines;
llvm::NamedMDNode *m_mainFileName;
llvm::NamedMDNode *m_arguments;
RVAMap m_instructions;
std::vector<const llvm::Instruction *>
m_instructionLines; // Instructions with line info.
std::unordered_map<const llvm::Instruction *, RVA>
m_rvaMap; // Map instruction to its RVA.
LineToInfoMap m_lineToInfoMap;
std::unique_ptr<SymbolManager> m_symsMgr;
private:
CComPtr<IDiaEnumTables> m_pEnumTables;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTable.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTable.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTable.h"
#include "DxilDiaSession.h"
#include "DxilDiaTableFrameData.h"
#include "DxilDiaTableInjectedSources.h"
#include "DxilDiaTableInputAssemblyFile.h"
#include "DxilDiaTableLineNumbers.h"
#include "DxilDiaTableSections.h"
#include "DxilDiaTableSegmentMap.h"
#include "DxilDiaTableSourceFiles.h"
#include "DxilDiaTableSymbols.h"
HRESULT dxil_dia::Table::Create(
/* [in] */ Session *pSession,
/* [in] */ Table::Kind kind,
/* [out] */ IDiaTable **ppTable) {
try {
*ppTable = nullptr;
IMalloc *pMalloc = pSession->GetMallocNoRef();
switch (kind) {
case Table::Kind::Symbols:
*ppTable = CreateOnMalloc<SymbolsTable>(pMalloc, pSession);
break;
case Table::Kind::SourceFiles:
*ppTable = CreateOnMalloc<SourceFilesTable>(pMalloc, pSession);
break;
case Table::Kind::LineNumbers:
*ppTable = CreateOnMalloc<LineNumbersTable>(pMalloc, pSession);
break;
case Table::Kind::Sections:
*ppTable = CreateOnMalloc<SectionsTable>(pMalloc, pSession);
break;
case Table::Kind::SegmentMap:
*ppTable = CreateOnMalloc<SegmentMapTable>(pMalloc, pSession);
break;
case Table::Kind::InjectedSource:
*ppTable = CreateOnMalloc<InjectedSourcesTable>(pMalloc, pSession);
break;
case Table::Kind::FrameData:
*ppTable = CreateOnMalloc<FrameDataTable>(pMalloc, pSession);
break;
case Table::Kind::InputAssemblyFile:
*ppTable = CreateOnMalloc<InputAssemblyFilesTable>(pMalloc, pSession);
break;
default:
return E_FAIL;
}
if (*ppTable == nullptr)
return E_OUTOFMEMORY;
(*ppTable)->AddRef();
return S_OK;
}
CATCH_CPP_RETURN_HRESULT();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableFrameData.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableFrameData.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaTableFrameData.h"
#include "DxilDiaSession.h"
dxil_dia::FrameDataTable::FrameDataTable(IMalloc *pMalloc, Session *pSession)
: impl::TableBase<IDiaEnumFrameData, IDiaFrameData>(
pMalloc, pSession, Table::Kind::FrameData) {}
HRESULT dxil_dia::FrameDataTable::GetItem(DWORD index, IDiaFrameData **ppItem) {
*ppItem = nullptr;
return E_FAIL;
} |
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixLiveVariables_FragmentIterator.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixLiveVariables_FragmentIterator.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Implements the FragmentIterator. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "DxcPixLiveVariables_FragmentIterator.h"
#include "dxc/DXIL/DxilMetadataHelper.h"
#include "dxc/Support/exception.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include <vector>
///////////////////////////////////////////////////////////////////////////////
class FragmentIteratorBase : public dxil_debug_info::MemberIterator {
public:
virtual ~FragmentIteratorBase() {}
virtual unsigned SizeInBits(unsigned) const override;
virtual bool Next(unsigned *FragmentIndex) override;
protected:
FragmentIteratorBase(unsigned NumFragments, unsigned FragmentSizeInBits,
unsigned InitialOffsetInBits);
unsigned m_CurrFragment = 0;
unsigned m_NumFragments = 0;
unsigned m_FragmentSizeInBits = 0;
unsigned m_InitialOffsetInBits = 0;
};
unsigned FragmentIteratorBase::SizeInBits(unsigned) const {
return m_FragmentSizeInBits;
}
bool FragmentIteratorBase::Next(unsigned *FragmentIndex) {
if (m_CurrFragment >= m_NumFragments) {
return false;
}
*FragmentIndex = m_CurrFragment++;
return true;
}
FragmentIteratorBase::FragmentIteratorBase(unsigned NumFragments,
unsigned FragmentSizeInBits,
unsigned InitialOffsetInBits)
: m_NumFragments(NumFragments), m_FragmentSizeInBits(FragmentSizeInBits),
m_InitialOffsetInBits(InitialOffsetInBits) {}
///////////////////////////////////////////////////////////////////////////////
static unsigned NumAllocaElements(llvm::AllocaInst *Alloca) {
llvm::Type *FragmentTy = Alloca->getAllocatedType();
if (auto *ArrayTy = llvm::dyn_cast<llvm::ArrayType>(FragmentTy)) {
return ArrayTy->getNumElements();
}
const unsigned NumElements = 1;
return NumElements;
}
static unsigned FragmentSizeInBitsFromAlloca(const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca) {
llvm::Type *FragmentTy = Alloca->getAllocatedType();
if (auto *ArrayTy = llvm::dyn_cast<llvm::ArrayType>(FragmentTy)) {
FragmentTy = ArrayTy->getElementType();
}
const unsigned FragmentSizeInBits =
DataLayout.getTypeAllocSizeInBits(FragmentTy);
return FragmentSizeInBits;
}
static unsigned
InitialOffsetInBitsFromDIExpression(const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca,
llvm::DIExpression *Expression) {
unsigned FragmentOffsetInBits = 0;
if (Expression->getNumElements() > 0) {
if (Expression->getNumElements() == 1 &&
Expression->expr_op_begin()->getOp() == llvm::dwarf::DW_OP_deref) {
return 0;
} else if (!Expression->isBitPiece()) {
assert(!"Unhandled DIExpression");
throw hlsl::Exception(E_FAIL, "Unhandled DIExpression");
}
FragmentOffsetInBits = Expression->getBitPieceOffset();
assert(Expression->getBitPieceSize() <=
DataLayout.getTypeAllocSizeInBits(Alloca->getAllocatedType()));
}
return FragmentOffsetInBits;
}
///////////////////////////////////////////////////////////////////////////////
class DILayoutFragmentIterator : public FragmentIteratorBase {
public:
DILayoutFragmentIterator(const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca,
llvm::DIExpression *Expression);
virtual unsigned OffsetInBits(unsigned Index) override;
};
DILayoutFragmentIterator::DILayoutFragmentIterator(
const llvm::DataLayout &DataLayout, llvm::AllocaInst *Alloca,
llvm::DIExpression *Expression)
: FragmentIteratorBase(
NumAllocaElements(Alloca),
FragmentSizeInBitsFromAlloca(DataLayout, Alloca),
InitialOffsetInBitsFromDIExpression(DataLayout, Alloca, Expression)) {
}
unsigned DILayoutFragmentIterator::OffsetInBits(unsigned Index) {
return m_InitialOffsetInBits + Index * m_FragmentSizeInBits;
}
///////////////////////////////////////////////////////////////////////////////
static unsigned
NumFragmentsFromArrayDims(const std::vector<hlsl::DxilDIArrayDim> &ArrayDims) {
unsigned TotalNumFragments = 1;
for (const hlsl::DxilDIArrayDim &ArrayDim : ArrayDims) {
TotalNumFragments *= ArrayDim.NumElements;
}
return TotalNumFragments;
}
static unsigned FragmentSizeInBitsFrom(const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca,
unsigned TotalNumFragments) {
const unsigned TotalSizeInBits =
DataLayout.getTypeAllocSizeInBits(Alloca->getAllocatedType());
if (TotalNumFragments == 0 || TotalSizeInBits % TotalNumFragments != 0) {
assert(!"Malformed variable debug layout metadata.");
throw hlsl::Exception(E_FAIL, "Malformed variable debug layout metadata.");
}
const unsigned FragmentSizeInBits = TotalSizeInBits / TotalNumFragments;
return FragmentSizeInBits;
}
///////////////////////////////////////////////////////////////////////////////
class DebugLayoutFragmentIterator : public FragmentIteratorBase {
public:
DebugLayoutFragmentIterator(
const llvm::DataLayout &DataLayout, llvm::AllocaInst *Alloca,
unsigned InitialOffsetInBits,
const std::vector<hlsl::DxilDIArrayDim> &ArrayDims);
virtual unsigned OffsetInBits(unsigned Index) override;
private:
std::vector<hlsl::DxilDIArrayDim> m_ArrayDims;
};
DebugLayoutFragmentIterator::DebugLayoutFragmentIterator(
const llvm::DataLayout &DataLayout, llvm::AllocaInst *Alloca,
unsigned InitialOffsetInBits,
const std::vector<hlsl::DxilDIArrayDim> &ArrayDims)
: FragmentIteratorBase(
NumFragmentsFromArrayDims(ArrayDims),
FragmentSizeInBitsFrom(DataLayout, Alloca,
NumFragmentsFromArrayDims(ArrayDims)),
InitialOffsetInBits),
m_ArrayDims(ArrayDims) {}
unsigned DebugLayoutFragmentIterator::OffsetInBits(unsigned Index) {
// Figure out the offset of this fragment in the original
unsigned FragmentOffsetInBits = m_InitialOffsetInBits;
unsigned RemainingIndex = Index;
for (const hlsl::DxilDIArrayDim &ArrayDim : m_ArrayDims) {
FragmentOffsetInBits +=
(RemainingIndex % ArrayDim.NumElements) * ArrayDim.StrideInBits;
RemainingIndex /= ArrayDim.NumElements;
}
assert(RemainingIndex == 0);
return FragmentOffsetInBits;
}
///////////////////////////////////////////////////////////////////////////////
class CompositeTypeFragmentIterator : public dxil_debug_info::MemberIterator {
public:
CompositeTypeFragmentIterator(llvm::DICompositeType *CT);
virtual unsigned SizeInBits(unsigned Index) const override;
virtual unsigned OffsetInBits(unsigned Index) override;
virtual bool Next(unsigned *FragmentIndex) override;
private:
struct FragmentSizeAndOffset {
unsigned Size;
unsigned Offset;
};
std::vector<FragmentSizeAndOffset> m_fragmentLocations;
unsigned m_currentFragment = 0;
void DetermineStructMemberSizesAndOffsets(llvm::DIType const *,
uint64_t BaseOffset);
};
unsigned SizeIfBaseType(llvm::DIType const *diType) {
if (auto *BT = llvm::dyn_cast<llvm::DIBasicType>(diType)) {
return BT->getSizeInBits();
}
if (auto *DT = llvm::dyn_cast<llvm::DIDerivedType>(diType)) {
const llvm::DITypeIdentifierMap EmptyMap;
return SizeIfBaseType(DT->getBaseType().resolve(EmptyMap));
}
return 0;
}
void CompositeTypeFragmentIterator::DetermineStructMemberSizesAndOffsets(
llvm::DIType const *diType, uint64_t BaseOffset) {
assert(diType->getTag() != llvm::dwarf::DW_TAG_subroutine_type);
if (diType->getTag() == llvm::dwarf::DW_TAG_member) {
BaseOffset += diType->getOffsetInBits();
}
unsigned MemberSize = SizeIfBaseType(diType);
if (MemberSize != 0) {
m_fragmentLocations.push_back(
{MemberSize, static_cast<unsigned>(BaseOffset)});
} else {
if (auto *CT = llvm::dyn_cast<llvm::DICompositeType>(diType)) {
switch (diType->getTag()) {
case llvm::dwarf::DW_TAG_array_type: {
llvm::DINodeArray elements = CT->getElements();
unsigned arraySize = 1;
for (auto const &node : elements) {
if (llvm::DISubrange *SR = llvm::dyn_cast<llvm::DISubrange>(node)) {
arraySize *= SR->getCount();
}
}
if (arraySize != 0) {
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *BT = CT->getBaseType().resolve(EmptyMap);
unsigned elementSize =
static_cast<unsigned>(CT->getSizeInBits()) / arraySize;
for (unsigned i = 0; i < arraySize; ++i) {
DetermineStructMemberSizesAndOffsets(BT,
BaseOffset + i * elementSize);
}
}
} break;
case llvm::dwarf::DW_TAG_class_type:
case llvm::dwarf::DW_TAG_structure_type:
for (auto const &node : CT->getElements()) {
if (llvm::DIType *subType = llvm::dyn_cast<llvm::DIType>(node)) {
DetermineStructMemberSizesAndOffsets(
subType, BaseOffset /*TODO: plus member offset*/);
}
}
break;
default:
diType->dump();
break;
}
} else if (auto *DT = llvm::dyn_cast<llvm::DIDerivedType>(diType)) {
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *BT = DT->getBaseType().resolve(EmptyMap);
DetermineStructMemberSizesAndOffsets(BT, BaseOffset);
}
}
}
CompositeTypeFragmentIterator::CompositeTypeFragmentIterator(
llvm::DICompositeType *CT) {
DetermineStructMemberSizesAndOffsets(CT, 0);
}
unsigned CompositeTypeFragmentIterator::SizeInBits(unsigned Index) const {
return m_fragmentLocations[Index].Size;
}
unsigned CompositeTypeFragmentIterator::OffsetInBits(unsigned Index) {
return m_fragmentLocations[Index].Offset;
}
bool CompositeTypeFragmentIterator::Next(unsigned *FragmentIndex) {
*FragmentIndex = m_currentFragment;
m_currentFragment++;
return m_currentFragment <= static_cast<unsigned>(m_fragmentLocations.size());
}
///////////////////////////////////////////////////////////////////////////////
std::unique_ptr<dxil_debug_info::MemberIterator>
dxil_debug_info::CreateMemberIterator(llvm::DbgDeclareInst *DbgDeclare,
const llvm::DataLayout &DataLayout,
llvm::AllocaInst *Alloca,
llvm::DIExpression *Expression) {
bool HasVariableDebugLayout = false;
unsigned FirstFragmentOffsetInBits;
std::vector<hlsl::DxilDIArrayDim> ArrayDims;
std::unique_ptr<dxil_debug_info::MemberIterator> Iter;
try {
HasVariableDebugLayout = hlsl::DxilMDHelper::GetVariableDebugLayout(
DbgDeclare, FirstFragmentOffsetInBits, ArrayDims);
if (HasVariableDebugLayout) {
Iter.reset(new DebugLayoutFragmentIterator(
DataLayout, Alloca, FirstFragmentOffsetInBits, ArrayDims));
} else {
llvm::DICompositeType *CT = llvm::dyn_cast<llvm::DICompositeType>(
DbgDeclare->getVariable()->getType());
if (CT != nullptr && Expression->getNumElements() == 0) {
if (CT->getTag() != llvm::dwarf::DW_TAG_subroutine_type) {
Iter.reset(new CompositeTypeFragmentIterator(CT));
}
} else {
Iter.reset(
new DILayoutFragmentIterator(DataLayout, Alloca, Expression));
}
}
} catch (const hlsl::Exception &) {
return nullptr;
}
return Iter;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaEnumTables.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaEnumTables.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaEnumTables.h"
#include "DxilDia.h"
#include "DxilDiaSession.h"
#include "DxilDiaTable.h"
STDMETHODIMP dxil_dia::EnumTables::get_Count(LONG *pRetVal) {
*pRetVal = ((unsigned)Table::LastKind - (unsigned)Table::FirstKind) + 1;
return S_OK;
}
STDMETHODIMP dxil_dia::EnumTables::Item(
/* [in] */ VARIANT index,
/* [retval][out] */ IDiaTable **table) {
// Avoid pulling in additional variant support (could have used
// VariantChangeType instead).
DWORD indexVal;
switch (index.vt) {
case VT_UI4:
indexVal = index.uintVal;
break;
case VT_I4:
IFR(IntToDWord(index.intVal, &indexVal));
break;
default:
return E_INVALIDARG;
}
if (indexVal > (unsigned)Table::LastKind) {
return E_INVALIDARG;
}
HRESULT hr = S_OK;
if (!m_tables[indexVal]) {
DxcThreadMalloc TM(m_pMalloc);
hr = Table::Create(m_pSession, (Table::Kind)indexVal, &m_tables[indexVal]);
}
m_tables[indexVal].p->AddRef();
*table = m_tables[indexVal];
return hr;
}
STDMETHODIMP dxil_dia::EnumTables::Next(ULONG celt, IDiaTable **rgelt,
ULONG *pceltFetched) {
DxcThreadMalloc TM(m_pMalloc);
ULONG fetched = 0;
while (fetched < celt && m_next <= (unsigned)Table::LastKind) {
HRESULT hr = S_OK;
if (!m_tables[m_next]) {
DxcThreadMalloc TM(m_pMalloc);
hr = Table::Create(m_pSession, (Table::Kind)m_next, &m_tables[m_next]);
if (FAILED(hr)) {
return hr; // TODO: this leaks prior tables.
}
}
m_tables[m_next].p->AddRef();
rgelt[fetched] = m_tables[m_next];
++m_next, ++fetched;
}
if (pceltFetched != nullptr)
*pceltFetched = fetched;
return (fetched == celt) ? S_OK : S_FALSE;
}
STDMETHODIMP dxil_dia::EnumTables::Reset() {
m_next = 0;
return S_OK;
}
HRESULT dxil_dia::EnumTables::Create(
/* [in] */ dxil_dia::Session *pSession,
/* [out] */ IDiaEnumTables **ppEnumTables) {
*ppEnumTables =
CreateOnMalloc<EnumTables>(pSession->GetMallocNoRef(), pSession);
if (*ppEnumTables == nullptr)
return E_OUTOFMEMORY;
(*ppEnumTables)->AddRef();
return S_OK;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixBase.h | #pragma once
#include "dxc/Support/WinIncludes.h"
#include <stdexcept>
namespace dxil_debug_info {
template <typename T> T *Initialize(T *Obj) {
if (Obj != nullptr) {
Obj->AddRef();
}
return Obj;
}
template <typename T, typename O, typename... A>
HRESULT NewDxcPixDxilDebugInfoObjectOrThrow(O **pOut, A... args) {
if ((*pOut = Initialize(T::Alloc(args...))) == nullptr) {
throw std::bad_alloc();
}
return S_OK;
}
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDia.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDia.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDia.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/Unicode.h"
HRESULT dxil_dia::StringRefToBSTR(llvm::StringRef value, BSTR *pRetVal) {
try {
wchar_t *wide;
size_t sideSize;
if (!Unicode::UTF8BufferToWideBuffer(value.data(), value.size(), &wide,
&sideSize))
return E_FAIL;
*pRetVal = SysAllocString(wide);
delete[] wide;
}
CATCH_CPP_RETURN_HRESULT();
return S_OK;
}
HRESULT dxil_dia::ENotImpl() { return E_NOTIMPL; }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixDxilDebugInfo.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixDxilDebugInfo.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Declares the main class for dxcompiler's API for PIX support. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcpix.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include <memory>
#include <vector>
namespace dxil_dia {
class Session;
} // namespace dxil_dia
namespace llvm {
class Instruction;
class Module;
} // namespace llvm
namespace dxil_debug_info {
class LiveVariables;
class DxcPixDxilDebugInfo : public IDxcPixDxilDebugInfo {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<dxil_dia::Session> m_pSession;
std::unique_ptr<LiveVariables> m_LiveVars;
DxcPixDxilDebugInfo(IMalloc *pMalloc, dxil_dia::Session *pSession);
llvm::Instruction *FindInstruction(DWORD InstructionOffset) const;
public:
~DxcPixDxilDebugInfo();
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilDebugInfo)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilDebugInfo>(this, iid, ppvObject);
}
STDMETHODIMP
GetLiveVariablesAt(DWORD InstructionOffset,
IDxcPixDxilLiveVariables **ppLiveVariables) override;
STDMETHODIMP IsVariableInRegister(DWORD InstructionOffset,
const wchar_t *VariableName) override;
STDMETHODIMP GetFunctionName(DWORD InstructionOffset,
BSTR *ppFunctionName) override;
STDMETHODIMP GetStackDepth(DWORD InstructionOffset,
DWORD *StackDepth) override;
STDMETHODIMP InstructionOffsetsFromSourceLocation(
const wchar_t *FileName, DWORD SourceLine, DWORD SourceColumn,
IDxcPixDxilInstructionOffsets **ppOffsets) override;
STDMETHODIMP SourceLocationsFromInstructionOffset(
DWORD InstructionOffset,
IDxcPixDxilSourceLocations **ppSourceLocations) override;
llvm::Module *GetModuleRef();
IMalloc *GetMallocNoRef() { return m_pMalloc; }
};
class DxcPixDxilInstructionOffsets : public IDxcPixDxilInstructionOffsets {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<dxil_dia::Session> m_pSession;
DxcPixDxilInstructionOffsets(IMalloc *pMalloc, dxil_dia::Session *pSession,
const wchar_t *FileName, DWORD SourceLine,
DWORD SourceColumn);
std::vector<DWORD> m_offsets;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilInstructionOffsets)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilInstructionOffsets>(this, iid,
ppvObject);
}
virtual STDMETHODIMP_(DWORD) GetCount() override;
virtual STDMETHODIMP_(DWORD) GetOffsetByIndex(DWORD Index) override;
};
class DxcPixDxilSourceLocations : public IDxcPixDxilSourceLocations {
private:
DXC_MICROCOM_TM_REF_FIELDS()
DxcPixDxilSourceLocations(IMalloc *pMalloc, dxil_dia::Session *pSession,
llvm::Instruction *IP);
struct Location {
CComBSTR Filename;
DWORD Line;
DWORD Column;
};
std::vector<Location> m_locations;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixDxilSourceLocations)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixDxilSourceLocations>(this, iid,
ppvObject);
}
virtual STDMETHODIMP_(DWORD) GetCount() override;
virtual STDMETHODIMP_(DWORD) GetLineNumberByIndex(DWORD Index) override;
virtual STDMETHODIMP_(DWORD) GetColumnByIndex(DWORD Index) override;
virtual STDMETHODIMP GetFileNameByIndex(DWORD Index, BSTR *Name) override;
};
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSections.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSections.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class SectionsTable
: public impl::TableBase<IDiaEnumSectionContribs, IDiaSectionContrib> {
public:
SectionsTable(IMalloc *pMalloc, Session *pSession);
HRESULT GetItem(DWORD index, IDiaSectionContrib **ppItem) override;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaTableSymbols.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaTableSymbols.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <vector>
#include "dia2.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class Symbol : public IDiaSymbol {
DXC_MICROCOM_TM_REF_FIELDS()
protected:
DXC_MICROCOM_TM_CTOR_ONLY(Symbol)
CComPtr<Session> m_pSession;
private:
DWORD m_ID;
DWORD m_symTag;
bool m_hasLexicalParent = false;
DWORD m_lexicalParent = 0;
bool m_hasIsHLSLData = false;
bool m_isHLSLData = false;
bool m_hasDataKind = false;
DWORD m_dataKind = 0;
bool m_hasSourceFileName = false;
CComBSTR m_sourceFileName;
bool m_hasName = false;
CComBSTR m_name;
bool m_hasValue = false;
CComVariant m_value;
public:
virtual ~Symbol();
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) final {
return DoBasicQueryInterface<IDiaSymbol>(this, iid, ppvObject);
}
void Init(Session *pSession, DWORD index, DWORD symTag);
DWORD GetID() const { return m_ID; }
void SetDataKind(DWORD value) {
m_hasDataKind = true;
m_dataKind = value;
}
void SetLexicalParent(DWORD value) {
m_hasLexicalParent = true;
m_lexicalParent = value;
}
bool HasName() const { return m_hasName; }
void SetName(LPCWSTR value) {
m_hasName = true;
m_name = value;
}
void SetValue(LPCSTR value) {
m_hasValue = true;
m_value = value;
}
void SetValue(VARIANT *pValue) {
m_hasValue = true;
m_value.Copy(pValue);
}
void SetValue(unsigned value) {
m_hasValue = true;
m_value = value;
}
void SetSourceFileName(BSTR value) {
m_hasSourceFileName = true;
m_sourceFileName = value;
}
void SetIsHLSLData(bool value) {
m_hasIsHLSLData = true;
m_isHLSLData = value;
}
virtual HRESULT GetChildren(std::vector<CComPtr<Symbol>> *children) = 0;
#pragma region IDiaSymbol implementation.
STDMETHODIMP get_symIndexId(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_symTag(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_name(
/* [retval][out] */ BSTR *pRetVal) override;
STDMETHODIMP get_lexicalParent(
/* [retval][out] */ IDiaSymbol **pRetVal) override;
STDMETHODIMP get_classParent(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_type(
/* [retval][out] */ IDiaSymbol **pRetVal) override;
STDMETHODIMP get_dataKind(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_locationType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_addressSection(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_addressOffset(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_relativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualAddress(
/* [retval][out] */ ULONGLONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_registerId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_offset(
/* [retval][out] */ LONG *pRetVal) override;
STDMETHODIMP get_length(
/* [retval][out] */ ULONGLONG *pRetVal) override;
STDMETHODIMP get_slot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_volatileType(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_constType(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_unalignedType(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_access(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_libraryName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_platform(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_language(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_editAndContinueEnabled(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_frontEndMajor(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_frontEndMinor(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_frontEndBuild(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_backEndMajor(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_backEndMinor(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_backEndBuild(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_sourceFileName(
/* [retval][out] */ BSTR *pRetVal) override;
STDMETHODIMP get_unused(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_thunkOrdinal(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_thisAdjust(
/* [retval][out] */ LONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualBaseOffset(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtual(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_intro(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_pure(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_callingConvention(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_value(
/* [retval][out] */ VARIANT *pRetVal) override;
STDMETHODIMP get_baseType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_token(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_timeStamp(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_guid(
/* [retval][out] */ GUID *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_symbolsFileName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_reference(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_count(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_bitPosition(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_arrayIndexType(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_packed(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_constructor(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_overloadedOperator(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_nested(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasNestedTypes(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasAssignmentOperator(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasCastOperator(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_scoped(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualBaseClass(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_indirectVirtualBaseClass(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualBasePointerOffset(
/* [retval][out] */ LONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualTableShape(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_lexicalParentId(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_classParentId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_typeId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_arrayIndexTypeId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualTableShapeId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_code(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_function(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_managed(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_msil(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualBaseDispIndex(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_undecoratedName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_age(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_signature(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_compilerGenerated(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_addressTaken(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_rank(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_lowerBound(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_upperBound(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_lowerBoundId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_upperBoundId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_dataBytes(
/* [in] */ DWORD cbData,
/* [out] */ DWORD *pcbData,
/* [size_is][out] */ BYTE *pbData) override {
return ENotImpl();
}
STDMETHODIMP findChildren(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) override;
STDMETHODIMP findChildrenEx(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSymbols **ppResult) override;
STDMETHODIMP findChildrenExByAddr(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenExByVA(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ ULONGLONG va,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findChildrenExByRVA(
/* [in] */ enum SymTagEnum symtag,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP get_targetSection(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_targetOffset(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_targetRelativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_targetVirtualAddress(
/* [retval][out] */ ULONGLONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_machineType(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_oemId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_oemSymbolId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_types(
/* [in] */ DWORD cTypes,
/* [out] */ DWORD *pcTypes,
/* [size_is][size_is][out] */ IDiaSymbol **pTypes) override {
return ENotImpl();
}
STDMETHODIMP get_typeIds(
/* [in] */ DWORD cTypeIds,
/* [out] */ DWORD *pcTypeIds,
/* [size_is][out] */ DWORD *pdwTypeIds) override {
return ENotImpl();
}
STDMETHODIMP get_objectPointerType(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_udtKind(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_undecoratedNameEx(
/* [in] */ DWORD undecorateOptions,
/* [out] */ BSTR *name) override {
return ENotImpl();
}
STDMETHODIMP get_noReturn(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_customCallingConvention(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_noInline(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_optimizedCodeDebugInfo(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_notReached(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_interruptReturn(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_farReturn(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isStatic(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasDebugInfo(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isLTCG(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isDataAligned(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasSecurityChecks(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_compilerName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasAlloca(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasSetJump(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasLongJump(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasInlAsm(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasEH(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasSEH(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasEHa(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isNaked(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isAggregated(
/* [retval][out] */ BOOL *pRetVal) override;
STDMETHODIMP get_isSplitted(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_container(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_inlSpec(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_noStackOrdering(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_virtualBaseTableType(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasManagedCode(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isHotpatchable(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isCVTCIL(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isMSILNetmodule(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isCTypes(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isStripped(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_frontEndQFE(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_backEndQFE(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_wasInlined(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_strictGSCheck(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isCxxReturnUdt(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isConstructorVirtualBase(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_RValueReference(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_unmodifiedType(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_framePointerPresent(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isSafeBuffers(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_intrinsic(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_sealed(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hfaFloat(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hfaDouble(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_liveRangeStartAddressSection(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_liveRangeStartAddressOffset(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_liveRangeStartRelativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_countLiveRanges(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_liveRangeLength(
/* [retval][out] */ ULONGLONG *pRetVal) override;
STDMETHODIMP get_offsetInUdt(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_paramBasePointerRegisterId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_localBasePointerRegisterId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isLocationControlFlowDependent(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_stride(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numberOfRows(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numberOfColumns(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isMatrixRowMajor(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numericProperties(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ DWORD *pProperties) override;
STDMETHODIMP get_modifierValues(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ WORD *pModifiers) override {
return ENotImpl();
}
STDMETHODIMP get_isReturnValue(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isOptimizedAway(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_builtInKind(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_registerType(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_baseDataSlot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_baseDataOffset(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_textureSlot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_samplerSlot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_uavSlot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_sizeInUdt(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_memorySpaceKind(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_unmodifiedTypeId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_subTypeId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_subType(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numberOfModifiers(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numberOfRegisterIndices(
/* [retval][out] */ DWORD *pRetVal) override;
STDMETHODIMP get_isHLSLData(
/* [retval][out] */ BOOL *pRetVal) override;
STDMETHODIMP get_isPointerToDataMember(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isPointerToMemberFunction(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isSingleInheritance(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isMultipleInheritance(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isVirtualInheritance(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_restrictedType(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isPointerBasedOnSymbolValue(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_baseSymbol(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_baseSymbolId(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_objectFileName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isAcceleratorGroupSharedLocal(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isAcceleratorPointerTagLiveRange(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isAcceleratorStubFunction(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_numberOfAcceleratorPointerTags(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isSdl(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isWinRTPointer(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isRefUdt(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isValueUdt(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isInterfaceUdt(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP findInlineFramesByAddr(
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineFramesByRVA(
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineFramesByVA(
/* [in] */ ULONGLONG va,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLines(
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByAddr(
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByRVA(
/* [in] */ DWORD rva,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findInlineeLinesByVA(
/* [in] */ ULONGLONG va,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findSymbolsForAcceleratorPointerTag(
/* [in] */ DWORD tagValue,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP findSymbolsByRVAForAcceleratorPointerTag(
/* [in] */ DWORD tagValue,
/* [in] */ DWORD rva,
/* [out] */ IDiaEnumSymbols **ppResult) override {
return ENotImpl();
}
STDMETHODIMP get_acceleratorPointerTags(
/* [in] */ DWORD cnt,
/* [out] */ DWORD *pcnt,
/* [size_is][out] */ DWORD *pPointerTags) override {
return ENotImpl();
}
STDMETHODIMP getSrcLineOnTypeDefn(
/* [out] */ IDiaLineNumber **ppResult) override {
return ENotImpl();
}
STDMETHODIMP get_isPGO(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasValidPGOCounts(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_isOptimizedForSpeed(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_PGOEntryCount(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_PGOEdgeCount(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_PGODynamicInstructionCount(
/* [retval][out] */ ULONGLONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_staticSize(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_finalLiveStaticSize(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_phaseName(
/* [retval][out] */ BSTR *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_hasControlFlowCheck(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_constantExport(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_dataExport(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_privateExport(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_noNameExport(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exportHasExplicitlyAssignedOrdinal(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exportIsForwarder(
/* [retval][out] */ BOOL *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_ordinal(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_frameSize(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exceptionHandlerAddressSection(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exceptionHandlerAddressOffset(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exceptionHandlerRelativeVirtualAddress(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_exceptionHandlerVirtualAddress(
/* [retval][out] */ ULONGLONG *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP findInputAssemblyFile(
/* [out] */ IDiaInputAssemblyFile **ppResult) override {
return ENotImpl();
}
STDMETHODIMP get_characteristics(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_coffGroup(
/* [retval][out] */ IDiaSymbol **pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_bindID(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_bindSpace(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
STDMETHODIMP get_bindSlot(
/* [retval][out] */ DWORD *pRetVal) override {
return ENotImpl();
}
#pragma endregion
};
class SymbolChildrenEnumerator : public IDiaEnumSymbols {
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_CTOR(SymbolChildrenEnumerator)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDiaEnumSymbols>(this, iid, ppvObject);
}
void Init(std::vector<CComPtr<Symbol>> &&syms);
#pragma region IDiaEnumSymbols implementation
/* [id][helpstring][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum(
/* [retval][out] */ IUnknown **pRetVal) override {
return ENotImpl();
}
/* [id][helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count(
/* [retval][out] */ LONG *pRetVal) override;
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Item(
/* [in] */ DWORD index,
/* [retval][out] */ IDiaSymbol **symbol) override;
HRESULT STDMETHODCALLTYPE Next(
/* [in] */ ULONG celt,
/* [out] */ IDiaSymbol **rgelt,
/* [out] */ ULONG *pceltFetched) override;
HRESULT STDMETHODCALLTYPE Skip(
/* [in] */ ULONG celt) override {
return ENotImpl();
}
HRESULT STDMETHODCALLTYPE Reset(void) override;
HRESULT STDMETHODCALLTYPE Clone(
/* [out] */ IDiaEnumSymbols **ppenum) override {
return ENotImpl();
}
#pragma endregion
private:
DXC_MICROCOM_TM_REF_FIELDS()
std::vector<CComPtr<Symbol>> m_symbols;
std::vector<CComPtr<Symbol>>::iterator m_pos;
};
class SymbolsTable : public impl::TableBase<IDiaEnumSymbols, IDiaSymbol> {
public:
SymbolsTable(IMalloc *pMalloc, Session *pSession);
HRESULT GetItem(DWORD index, IDiaSymbol **ppItem) override;
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxcPixTypes.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixTypes.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Declares the classes implementing DxcPixType and its subinterfaces. These //
// classes are used to interpret llvm::DITypes from the debug metadata. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "DxcPixDxilDebugInfo.h"
#include "DxcPixTypes.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/microcom.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
namespace dxil_debug_info {
HRESULT CreateDxcPixType(DxcPixDxilDebugInfo *ppDxilDebugInfo,
llvm::DIType *diType, IDxcPixType **ppResult);
class DxcPixConstType : public IDxcPixConstType {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DIDerivedType *m_pType;
llvm::DIType *m_pBaseType;
DxcPixConstType(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIDerivedType *pType)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo), m_pType(pType) {
const llvm::DITypeIdentifierMap EmptyMap;
m_pBaseType = m_pType->getBaseType().resolve(EmptyMap);
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixConstType)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixConstType, IDxcPixType>(this, iid,
ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetSizeInBits(DWORD *pSizeInBits) override;
STDMETHODIMP UnAlias(IDxcPixType **ppType) override;
};
class DxcPixTypedefType : public IDxcPixTypedefType {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DIDerivedType *m_pType;
llvm::DIType *m_pBaseType;
DxcPixTypedefType(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIDerivedType *pType)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo), m_pType(pType) {
const llvm::DITypeIdentifierMap EmptyMap;
m_pBaseType = m_pType->getBaseType().resolve(EmptyMap);
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixTypedefType)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixTypedefType, IDxcPixType>(this, iid,
ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetSizeInBits(DWORD *pSizeInBits) override;
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override;
};
class DxcPixScalarType : public IDxcPixScalarType {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DIBasicType *m_pType;
DxcPixScalarType(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIBasicType *pType)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo), m_pType(pType) {}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixScalarType)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixScalarType, IDxcPixType>(this, iid,
ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetSizeInBits(DWORD *pSizeInBits) override;
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override;
};
class DxcPixArrayType : public IDxcPixArrayType {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DICompositeType *m_pArray;
llvm::DIType *m_pBaseType;
unsigned m_DimNum;
DxcPixArrayType(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DICompositeType *pArray, unsigned DimNum)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo), m_pArray(pArray),
m_DimNum(DimNum) {
const llvm::DITypeIdentifierMap EmptyMap;
m_pBaseType = m_pArray->getBaseType().resolve(EmptyMap);
#ifndef NDEBUG
assert(m_DimNum < m_pArray->getElements().size());
for (auto *Dims : m_pArray->getElements()) {
assert(llvm::isa<llvm::DISubrange>(Dims));
}
#endif // !NDEBUG
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixArrayType)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixArrayType, IDxcPixType>(this, iid,
ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetSizeInBits(DWORD *pSizeInBits) override;
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override;
STDMETHODIMP GetNumElements(DWORD *ppNumElements) override;
STDMETHODIMP GetIndexedType(IDxcPixType **ppElementType) override;
STDMETHODIMP GetElementType(IDxcPixType **ppElementType) override;
};
class DxcPixStructType : public IDxcPixStructType2 {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DICompositeType *m_pStruct;
DxcPixStructType(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DICompositeType *pStruct)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo),
m_pStruct(pStruct) {
#ifndef NDEBUG
for (auto *Node : m_pStruct->getElements()) {
assert(llvm::isa<llvm::DIDerivedType>(Node) ||
llvm::isa<llvm::DISubprogram>(Node));
}
#endif // !NDEBUG
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixStructType)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcPixStructType2, IDxcPixStructType,
IDxcPixType>(this, iid, ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetSizeInBits(DWORD *pSizeInBits) override;
STDMETHODIMP UnAlias(IDxcPixType **ppBaseType) override;
STDMETHODIMP GetNumFields(DWORD *ppNumFields) override;
STDMETHODIMP GetFieldByIndex(DWORD dwIndex,
IDxcPixStructField **ppField) override;
STDMETHODIMP GetFieldByName(LPCWSTR lpName,
IDxcPixStructField **ppField) override;
STDMETHODIMP GetBaseType(IDxcPixType **ppType) override;
};
struct __declspec(uuid("6c707d08-7995-4a84-bae5-e6d8291f3b78"))
PreviousDxcPixStructField {};
class DxcPixStructField : public IDxcPixStructField {
private:
DXC_MICROCOM_TM_REF_FIELDS()
CComPtr<DxcPixDxilDebugInfo> m_pDxilDebugInfo;
llvm::DIDerivedType *m_pField;
llvm::DIType *m_pType;
DxcPixStructField(IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm::DIDerivedType *pField)
: m_pMalloc(pMalloc), m_pDxilDebugInfo(pDxilDebugInfo), m_pField(pField) {
const llvm::DITypeIdentifierMap EmptyMap;
m_pType = m_pField->getBaseType().resolve(EmptyMap);
}
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
DXC_MICROCOM_TM_ALLOC(DxcPixStructField)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
if (IsEqualIID(iid, __uuidof(PreviousDxcPixStructField))) {
*(IDxcPixStructField **)ppvObject = this;
this->AddRef();
return S_OK;
}
return DoBasicQueryInterface<IDxcPixStructField>(this, iid, ppvObject);
}
STDMETHODIMP GetName(BSTR *Name) override;
STDMETHODIMP GetType(IDxcPixType **ppType) override;
STDMETHODIMP GetOffsetInBits(DWORD *pOffsetInBits) override;
STDMETHODIMP GetFieldSizeInBits(DWORD *pFieldSizeInBits) override;
};
} // namespace dxil_debug_info
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaSession.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaSession.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "DxilDiaSession.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "../DxilPIXPasses/PixPassHelpers.h"
#include "DxilDia.h"
#include "DxilDiaEnumTables.h"
#include "DxilDiaTable.h"
#include "DxilDiaTableInjectedSources.h"
#include "DxilDiaTableLineNumbers.h"
#include "DxilDiaTableSourceFiles.h"
#include "DxilDiaTableSymbols.h"
void dxil_dia::Session::Init(std::shared_ptr<llvm::LLVMContext> context,
std::shared_ptr<llvm::Module> mod,
std::shared_ptr<llvm::DebugInfoFinder> finder) {
m_pEnumTables = nullptr;
m_module = mod;
m_context = context;
m_finder = finder;
m_dxilModule = llvm::make_unique<hlsl::DxilModule>(mod.get());
// Extract HLSL metadata.
m_dxilModule->LoadDxilMetadata();
// Get file contents.
m_contents =
m_module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceContentsMDName);
if (!m_contents)
m_contents = m_module->getNamedMetadata("llvm.dbg.contents");
m_defines =
m_module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceDefinesMDName);
if (!m_defines)
m_defines = m_module->getNamedMetadata("llvm.dbg.defines");
m_mainFileName = m_module->getNamedMetadata(
hlsl::DxilMDHelper::kDxilSourceMainFileNameMDName);
if (!m_mainFileName)
m_mainFileName = m_module->getNamedMetadata("llvm.dbg.mainFileName");
m_arguments =
m_module->getNamedMetadata(hlsl::DxilMDHelper::kDxilSourceArgsMDName);
if (!m_arguments)
m_arguments = m_module->getNamedMetadata("llvm.dbg.args");
// Build up a linear list of instructions. The index will be used as the
// RVA.
std::vector<llvm::Function *> allInstrumentableFunctions =
PIXPassHelpers::GetAllInstrumentableFunctions(*m_dxilModule.get());
for (auto fn : allInstrumentableFunctions) {
for (llvm::inst_iterator it = inst_begin(fn), end = inst_end(fn); it != end;
++it) {
llvm::Instruction &i = *it;
RVA rva;
if (!pix_dxil::PixDxilInstNum::FromInst(&i, &rva)) {
continue;
}
m_rvaMap.insert({&i, rva});
m_instructions.insert({rva, &i});
if (llvm::DebugLoc DL = i.getDebugLoc()) {
auto result = m_lineToInfoMap.emplace(
DL.getLine(), LineInfo(DL.getCol(), rva, rva + 1));
if (!result.second) {
result.first->second.StartCol =
std::min(result.first->second.StartCol, DL.getCol());
result.first->second.Last = rva + 1;
}
m_instructionLines.push_back(&i);
}
}
}
// Sanity check to make sure rva map is same as instruction index.
for (auto It = m_instructions.begin(); It != m_instructions.end(); ++It) {
DXASSERT(m_rvaMap.find(It->second) != m_rvaMap.end(),
"instruction not mapped to rva");
DXASSERT(m_rvaMap[It->second] == It->first,
"instruction mapped to wrong rva");
}
}
const dxil_dia::SymbolManager &dxil_dia::Session::SymMgr() {
if (!m_symsMgr) {
try {
m_symsMgr.reset(new dxil_dia::SymbolManager());
m_symsMgr->Init(this);
} catch (const hlsl::Exception &) {
m_symsMgr.reset(new dxil_dia::SymbolManager());
}
}
return *m_symsMgr;
}
HRESULT dxil_dia::Session::getSourceFileIdByName(llvm::StringRef fileName,
DWORD *pRetVal) {
if (Contents() != nullptr) {
for (unsigned i = 0; i < Contents()->getNumOperands(); ++i) {
llvm::StringRef fn = llvm::dyn_cast<llvm::MDString>(
Contents()->getOperand(i)->getOperand(0))
->getString();
if (fn.equals(fileName)) {
*pRetVal = i;
return S_OK;
}
}
}
*pRetVal = 0;
return S_FALSE;
}
STDMETHODIMP dxil_dia::Session::get_loadAddress(
/* [retval][out] */ ULONGLONG *pRetVal) {
*pRetVal = 0;
return S_OK;
}
STDMETHODIMP dxil_dia::Session::get_globalScope(
/* [retval][out] */ IDiaSymbol **pRetVal) {
DxcThreadMalloc TM(m_pMalloc);
if (pRetVal == nullptr) {
return E_INVALIDARG;
}
*pRetVal = nullptr;
Symbol *ret;
IFR(SymMgr().GetGlobalScope(&ret));
*pRetVal = ret;
return S_OK;
}
STDMETHODIMP dxil_dia::Session::getEnumTables(IDiaEnumTables **ppEnumTables) {
if (!m_pEnumTables) {
DxcThreadMalloc TM(m_pMalloc);
IFR(EnumTables::Create(this, &m_pEnumTables));
}
m_pEnumTables.p->AddRef();
*ppEnumTables = m_pEnumTables;
return S_OK;
}
STDMETHODIMP dxil_dia::Session::findFileById(
/* [in] */ DWORD uniqueId,
/* [out] */ IDiaSourceFile **ppResult) {
if (!m_pEnumTables) {
return E_INVALIDARG;
}
CComPtr<IDiaTable> pTable;
VARIANT vtIndex;
vtIndex.vt = VT_UI4;
vtIndex.uintVal = (int)Table::Kind::SourceFiles;
IFR(m_pEnumTables->Item(vtIndex, &pTable));
CComPtr<IUnknown> pElt;
IFR(pTable->Item(uniqueId, &pElt));
return pElt->QueryInterface(ppResult);
}
STDMETHODIMP dxil_dia::Session::findFile(
/* [in] */ IDiaSymbol *pCompiland,
/* [in] */ LPCOLESTR name,
/* [in] */ DWORD compareFlags,
/* [out] */ IDiaEnumSourceFiles **ppResult) {
if (!m_pEnumTables) {
return E_INVALIDARG;
}
// TODO: properly support compareFlags.
auto namecmp = &_wcsicmp;
if (compareFlags & nsCaseSensitive) {
namecmp = &wcscmp;
}
DxcThreadMalloc TM(m_pMalloc);
CComPtr<IDiaTable> pTable;
VARIANT vtIndex;
vtIndex.vt = VT_UI4;
vtIndex.uintVal = (int)Table::Kind::SourceFiles;
IFR(m_pEnumTables->Item(vtIndex, &pTable));
CComPtr<IDiaEnumSourceFiles> pSourceTable;
IFR(pTable->QueryInterface(&pSourceTable));
HRESULT hr;
CComPtr<IDiaSourceFile> src;
ULONG cnt;
std::vector<CComPtr<IDiaSourceFile>> sources;
pSourceTable->Reset();
while (SUCCEEDED(hr = pSourceTable->Next(1, &src, &cnt)) && hr == S_OK &&
cnt == 1) {
CComBSTR currName;
IFR(src->get_fileName(&currName));
if (namecmp(name, currName) == 0) {
sources.emplace_back(src);
}
src.Release();
}
*ppResult = CreateOnMalloc<SourceFilesTable>(GetMallocNoRef(), this,
std::move(sources));
if (*ppResult == nullptr) {
return E_OUTOFMEMORY;
}
(*ppResult)->AddRef();
return S_OK;
}
namespace dxil_dia {
static HRESULT DxcDiaFindLineNumbersByRVA(Session *pSession, DWORD rva,
DWORD length,
IDiaEnumLineNumbers **ppResult) {
if (!ppResult)
return E_POINTER;
std::vector<const llvm::Instruction *> instructions;
auto &allInstructions = pSession->InstructionsRef();
// Gather the list of insructions that map to the given rva range.
for (DWORD i = rva; i < rva + length; ++i) {
auto It = allInstructions.find(i);
if (It == allInstructions.end())
return E_INVALIDARG;
// Only include the instruction if it has debug info for line mappings.
const llvm::Instruction *inst = It->second;
if (inst->getDebugLoc())
instructions.push_back(inst);
}
// Create line number table from explicit instruction list.
IMalloc *pMalloc = pSession->GetMallocNoRef();
*ppResult = CreateOnMalloc<LineNumbersTable>(pMalloc, pSession,
std::move(instructions));
if (*ppResult == nullptr)
return E_OUTOFMEMORY;
(*ppResult)->AddRef();
return S_OK;
}
} // namespace dxil_dia
STDMETHODIMP dxil_dia::Session::findLinesByAddr(
/* [in] */ DWORD seg,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) {
DxcThreadMalloc TM(m_pMalloc);
return DxcDiaFindLineNumbersByRVA(this, offset, length, ppResult);
}
STDMETHODIMP dxil_dia::Session::findLinesByRVA(
/* [in] */ DWORD rva,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) {
DxcThreadMalloc TM(m_pMalloc);
return DxcDiaFindLineNumbersByRVA(this, rva, length, ppResult);
}
STDMETHODIMP dxil_dia::Session::findInlineeLinesByAddr(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [in] */ DWORD length,
/* [out] */ IDiaEnumLineNumbers **ppResult) {
DxcThreadMalloc TM(m_pMalloc);
return DxcDiaFindLineNumbersByRVA(this, offset, length, ppResult);
}
STDMETHODIMP dxil_dia::Session::findLinesByLinenum(
/* [in] */ IDiaSymbol *compiland,
/* [in] */ IDiaSourceFile *file,
/* [in] */ DWORD linenum,
/* [in] */ DWORD column,
/* [out] */ IDiaEnumLineNumbers **ppResult) {
if (!m_pEnumTables) {
return E_INVALIDARG;
}
*ppResult = nullptr;
DxcThreadMalloc TM(m_pMalloc);
CComPtr<IDiaTable> pTable;
VARIANT vtIndex;
vtIndex.vt = VT_UI4;
vtIndex.uintVal = (int)Table::Kind::LineNumbers;
IFR(m_pEnumTables->Item(vtIndex, &pTable));
CComPtr<IDiaEnumLineNumbers> pLineTable;
IFR(pTable->QueryInterface(&pLineTable));
HRESULT hr;
CComPtr<IDiaLineNumber> line;
ULONG cnt;
std::vector<const llvm::Instruction *> lines;
std::function<bool(DWORD, DWORD)> column_matches =
[](DWORD colStart, DWORD colEnd) -> bool { return true; };
if (column != 0) {
column_matches = [column](DWORD colStart, DWORD colEnd) -> bool {
return colStart < column && column < colEnd;
};
}
pLineTable->Reset();
while (SUCCEEDED(hr = pLineTable->Next(1, &line, &cnt)) && hr == S_OK &&
cnt == 1) {
CComPtr<IDiaSourceFile> f;
DWORD ln, lnEnd, cn, cnEnd;
IFR(line->get_lineNumber(&ln));
IFR(line->get_lineNumberEnd(&lnEnd));
IFR(line->get_columnNumber(&cn));
IFR(line->get_columnNumberEnd(&cnEnd));
IFR(line->get_sourceFile(&f));
if (file == f && (ln <= linenum && linenum <= lnEnd) &&
column_matches(cn, cnEnd)) {
lines.emplace_back(reinterpret_cast<LineNumber *>(line.p)->Inst());
}
line.Release();
}
HRESULT result = lines.empty() ? S_FALSE : S_OK;
*ppResult = CreateOnMalloc<LineNumbersTable>(GetMallocNoRef(), this,
std::move(lines));
if (*ppResult == nullptr) {
return E_OUTOFMEMORY;
}
(*ppResult)->AddRef();
return result;
}
STDMETHODIMP dxil_dia::Session::findInjectedSource(
/* [in] */ LPCOLESTR srcFile,
/* [out] */ IDiaEnumInjectedSources **ppResult) {
if (Contents() != nullptr) {
CW2A pUtf8FileName(srcFile);
DxcThreadMalloc TM(m_pMalloc);
IDiaTable *pTable;
IFT(Table::Create(this, Table::Kind::InjectedSource, &pTable));
auto *pInjectedSource = reinterpret_cast<InjectedSourcesTable *>(pTable);
pInjectedSource->Init(pUtf8FileName.m_psz);
*ppResult = pInjectedSource;
return S_OK;
}
return S_FALSE;
}
static constexpr DWORD kD3DCodeSection = 1;
STDMETHODIMP dxil_dia::Session::findInlineFramesByAddr(
/* [in] */ IDiaSymbol *parent,
/* [in] */ DWORD isect,
/* [in] */ DWORD offset,
/* [out] */ IDiaEnumSymbols **ppResult) {
if (parent != nullptr || isect != kD3DCodeSection || ppResult == nullptr) {
return E_INVALIDARG;
}
*ppResult = nullptr;
DxcThreadMalloc TM(m_pMalloc);
auto &allInstructions = InstructionsRef();
auto It = allInstructions.find(offset);
if (It == allInstructions.end()) {
return E_INVALIDARG;
}
HRESULT hr;
SymbolChildrenEnumerator *ChildrenEnum;
IFR(hr = SymMgr().DbgScopeOf(It->second, &ChildrenEnum));
*ppResult = ChildrenEnum;
return hr;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilDia/DxilDiaDataSource.h | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDiaDataSource.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// DIA API implementation for DXIL modules. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include <memory>
#include "dia2.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/Support/Global.h"
#include "DxilDia.h"
#include "DxilDiaTable.h"
namespace dxil_dia {
class Session;
class DataSource : public IDiaDataSource {
private:
DXC_MICROCOM_TM_REF_FIELDS()
std::shared_ptr<llvm::Module> m_module;
std::shared_ptr<llvm::LLVMContext> m_context;
std::shared_ptr<llvm::DebugInfoFinder> m_finder;
public:
DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
STDMETHODIMP QueryInterface(REFIID iid, void **ppvObject) override {
return DoBasicQueryInterface<IDiaDataSource>(this, iid, ppvObject);
}
DataSource(IMalloc *pMalloc);
~DataSource();
STDMETHODIMP get_lastError(BSTR *pRetVal) override;
STDMETHODIMP loadDataFromPdb(LPCOLESTR pdbPath) override {
return ENotImpl();
}
STDMETHODIMP loadAndValidateDataFromPdb(LPCOLESTR pdbPath, GUID *pcsig70,
DWORD sig, DWORD age) override {
return ENotImpl();
}
STDMETHODIMP loadDataForExe(LPCOLESTR executable, LPCOLESTR searchPath,
IUnknown *pCallback) override {
return ENotImpl();
}
STDMETHODIMP loadDataFromIStream(IStream *pIStream) override;
STDMETHODIMP openSession(IDiaSession **ppSession) override;
HRESULT STDMETHODCALLTYPE loadDataFromCodeViewInfo(
LPCOLESTR executable, LPCOLESTR searchPath, DWORD cbCvInfo,
BYTE *pbCvInfo, IUnknown *pCallback) override {
return ENotImpl();
}
HRESULT STDMETHODCALLTYPE loadDataFromMiscInfo(
LPCOLESTR executable, LPCOLESTR searchPath, DWORD timeStampExe,
DWORD timeStampDbg, DWORD sizeOfExe, DWORD cbMiscInfo, BYTE *pbMiscInfo,
IUnknown *pCallback) override {
return ENotImpl();
}
};
} // namespace dxil_dia
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilPIXMeshShaderOutputInstrumentation.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilAddPixelHitInstrumentation.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to add instrumentation to retrieve mesh shader output. //
// Used by PIX. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <deque>
#ifdef _WIN32
#include <winerror.h>
#endif
#include "PixPassHelpers.h"
// Keep these in sync with the same-named value in the debugger application's
// WinPixShaderUtils.h
constexpr uint64_t DebugBufferDumpingGroundSize = 64 * 1024;
// The actual max size per record is much smaller than this, but it never
// hurts to be generous.
constexpr size_t CounterOffsetBeyondUsefulData =
DebugBufferDumpingGroundSize / 2;
// Keep these in sync with the same-named values in PIX's MeshShaderOutput.cpp
constexpr uint32_t triangleIndexIndicator = 0x1;
constexpr uint32_t int32ValueIndicator = 0x2;
constexpr uint32_t floatValueIndicator = 0x3;
constexpr uint32_t int16ValueIndicator = 0x4;
constexpr uint32_t float16ValueIndicator = 0x5;
using namespace llvm;
using namespace hlsl;
using namespace PIXPassHelpers;
class DxilPIXMeshShaderOutputInstrumentation : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilPIXMeshShaderOutputInstrumentation() : ModulePass(ID) {}
StringRef getPassName() const override {
return "DXIL mesh shader output instrumentation";
}
void applyOptions(PassOptions O) override;
bool runOnModule(Module &M) override;
private:
CallInst *m_OutputUAV = nullptr;
int m_RemainingReservedSpaceInBytes = 0;
Constant *m_OffsetMask = nullptr;
SmallVector<Value *, 2> m_threadUniquifier;
uint64_t m_UAVSize = 1024 * 1024;
bool m_ExpandPayload = false;
uint32_t m_DispatchArgumentY = 1;
uint32_t m_DispatchArgumentZ = 1;
struct BuilderContext {
Module &M;
DxilModule &DM;
LLVMContext &Ctx;
OP *HlslOP;
IRBuilder<> &Builder;
};
SmallVector<Value *, 2> insertInstructionsToCreateDisambiguationValue(
IRBuilder<> &Builder, OP *HlslOP, LLVMContext &Ctx,
StructType *originalPayloadStructType, Instruction *firstGetPayload);
Value *reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInBytes);
uint32_t UAVDumpingGroundOffset();
Value *writeDwordAndReturnNewOffset(BuilderContext &BC, Value *TheOffset,
Value *TheValue);
template <typename... T> void Instrument(BuilderContext &BC, T... values);
};
void DxilPIXMeshShaderOutputInstrumentation::applyOptions(PassOptions O) {
GetPassOptionUInt64(O, "UAVSize", &m_UAVSize, 1024 * 1024);
GetPassOptionBool(O, "expand-payload", &m_ExpandPayload, 0);
GetPassOptionUInt32(O, "dispatchArgY", &m_DispatchArgumentY, 1);
GetPassOptionUInt32(O, "dispatchArgZ", &m_DispatchArgumentZ, 1);
}
uint32_t DxilPIXMeshShaderOutputInstrumentation::UAVDumpingGroundOffset() {
return static_cast<uint32_t>(m_UAVSize - DebugBufferDumpingGroundSize);
}
Value *DxilPIXMeshShaderOutputInstrumentation::reserveDebugEntrySpace(
BuilderContext &BC, uint32_t SpaceInBytes) {
// Check the previous caller didn't reserve too much space:
assert(m_RemainingReservedSpaceInBytes == 0);
// Check that the caller didn't ask for so much memory that it will
// overwrite the offset counter:
assert(m_RemainingReservedSpaceInBytes < (int)CounterOffsetBeyondUsefulData);
m_RemainingReservedSpaceInBytes = SpaceInBytes;
// Insert the UAV increment instruction:
Function *AtomicOpFunc =
BC.HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(BC.Ctx));
Constant *AtomicBinOpcode =
BC.HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
Constant *AtomicAdd =
BC.HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
Constant *OffsetArg = BC.HlslOP->GetU32Const(UAVDumpingGroundOffset() +
CounterOffsetBeyondUsefulData);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
Constant *Increment = BC.HlslOP->GetU32Const(SpaceInBytes);
auto *PreviousValue = BC.Builder.CreateCall(
AtomicOpFunc,
{
AtomicBinOpcode, // i32, ; opcode
m_OutputUAV, // %dx.types.Handle, ; resource handle
AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD, AND, OR,
// XOR, IMIN, IMAX, UMIN, UMAX
OffsetArg, // i32, ; coordinate c0: index in bytes
UndefArg, // i32, ; coordinate c1 (unused)
UndefArg, // i32, ; coordinate c2 (unused)
Increment, // i32); increment value
},
"UAVIncResult");
return BC.Builder.CreateAnd(PreviousValue, m_OffsetMask, "MaskedForUAVLimit");
}
Value *DxilPIXMeshShaderOutputInstrumentation::writeDwordAndReturnNewOffset(
BuilderContext &BC, Value *TheOffset, Value *TheValue) {
Function *StoreValue =
BC.HlslOP->GetOpFunc(OP::OpCode::BufferStore, Type::getInt32Ty(BC.Ctx));
Constant *StoreValueOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::BufferStore);
UndefValue *Undef32Arg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
Constant *WriteMask_X = BC.HlslOP->GetI8Const(1);
(void)BC.Builder.CreateCall(
StoreValue,
{StoreValueOpcode, // i32 opcode
m_OutputUAV, // %dx.types.Handle, ; resource handle
TheOffset, // i32 c0: index in bytes into UAV
Undef32Arg, // i32 c1: unused
TheValue,
Undef32Arg, // unused values
Undef32Arg, // unused values
Undef32Arg, // unused values
WriteMask_X});
m_RemainingReservedSpaceInBytes -= sizeof(uint32_t);
assert(m_RemainingReservedSpaceInBytes >=
0); // or else the caller didn't reserve enough space
return BC.Builder.CreateAdd(
TheOffset,
BC.HlslOP->GetU32Const(static_cast<unsigned int>(sizeof(uint32_t))));
}
template <typename... T>
void DxilPIXMeshShaderOutputInstrumentation::Instrument(BuilderContext &BC,
T... values) {
llvm::SmallVector<llvm::Value *, 10> Values(
{static_cast<llvm::Value *>(values)...});
const uint32_t DwordCount = Values.size();
llvm::Value *byteOffset =
reserveDebugEntrySpace(BC, DwordCount * sizeof(uint32_t));
for (llvm::Value *V : Values) {
byteOffset = writeDwordAndReturnNewOffset(BC, byteOffset, V);
}
}
Value *GetValueFromExpandedPayload(IRBuilder<> &Builder,
StructType *originalPayloadStructType,
Instruction *firstGetPayload,
unsigned int offset, const char *name) {
auto *DerefPointer = Builder.getInt32(0);
auto *OffsetToExpandedData = Builder.getInt32(offset);
auto *GEP = Builder.CreateGEP(
cast<PointerType>(firstGetPayload->getType()->getScalarType())
->getElementType(),
firstGetPayload, {DerefPointer, OffsetToExpandedData});
return Builder.CreateLoad(GEP, name);
}
SmallVector<Value *, 2> DxilPIXMeshShaderOutputInstrumentation::
insertInstructionsToCreateDisambiguationValue(
IRBuilder<> &Builder, OP *HlslOP, LLVMContext &Ctx,
StructType *originalPayloadStructType, Instruction *firstGetPayload) {
// When a mesh shader is called from an amplification shader, all of the
// thread id values are relative to the DispatchMesh call made by
// that amplification shader. Data about what thread counts were passed
// by the CPU to *CommandList::DispatchMesh are not available, but we
// will have added that value to the AS->MS payload...
SmallVector<Value *, 2> ret;
Constant *Zero32Arg = HlslOP->GetU32Const(0);
bool AmplificationShaderIsActive = originalPayloadStructType != nullptr;
llvm::Value *ASDispatchMeshYCount = nullptr;
llvm::Value *ASDispatchMeshZCount = nullptr;
if (AmplificationShaderIsActive) {
auto *ASThreadId = GetValueFromExpandedPayload(
Builder, originalPayloadStructType, firstGetPayload,
originalPayloadStructType->getStructNumElements(), "ASThreadId");
ret.push_back(ASThreadId);
ASDispatchMeshYCount = GetValueFromExpandedPayload(
Builder, originalPayloadStructType, firstGetPayload,
originalPayloadStructType->getStructNumElements() + 1,
"ASDispatchMeshYCount");
ASDispatchMeshZCount = GetValueFromExpandedPayload(
Builder, originalPayloadStructType, firstGetPayload,
originalPayloadStructType->getStructNumElements() + 2,
"ASDispatchMeshZCount");
} else {
ret.push_back(Zero32Arg);
}
Constant *One32Arg = HlslOP->GetU32Const(1);
Constant *Two32Arg = HlslOP->GetU32Const(2);
auto GroupIdFunc =
HlslOP->GetOpFunc(DXIL::OpCode::GroupId, Type::getInt32Ty(Ctx));
Constant *Opcode = HlslOP->GetU32Const((unsigned)DXIL::OpCode::GroupId);
auto *GroupIdX =
Builder.CreateCall(GroupIdFunc, {Opcode, Zero32Arg}, "GroupIdX");
auto *GroupIdY =
Builder.CreateCall(GroupIdFunc, {Opcode, One32Arg}, "GroupIdY");
auto *GroupIdZ =
Builder.CreateCall(GroupIdFunc, {Opcode, Two32Arg}, "GroupIdZ");
// flattend group number = z + y*numZ + x*numY*numZ
if (AmplificationShaderIsActive) {
auto *GroupYxNumZ = Builder.CreateMul(GroupIdY, ASDispatchMeshZCount);
auto *FlatGroupNumZY = Builder.CreateAdd(GroupIdZ, GroupYxNumZ);
auto *GroupXxNumZ = Builder.CreateMul(GroupIdX, ASDispatchMeshZCount);
auto *GroupXxNumYZ = Builder.CreateMul(GroupXxNumZ, ASDispatchMeshYCount);
auto *FlatGroupNum = Builder.CreateAdd(GroupXxNumYZ, FlatGroupNumZY);
ret.push_back(FlatGroupNum);
} else {
auto *GroupYxNumZ =
Builder.CreateMul(GroupIdY, HlslOP->GetU32Const(m_DispatchArgumentZ));
auto *FlatGroupNumZY = Builder.CreateAdd(GroupIdZ, GroupYxNumZ);
auto *GroupXxNumYZ =
Builder.CreateMul(GroupIdX, HlslOP->GetU32Const(m_DispatchArgumentY *
m_DispatchArgumentZ));
auto *FlatGroupNum = Builder.CreateAdd(GroupXxNumYZ, FlatGroupNumZY);
ret.push_back(FlatGroupNum);
}
return ret;
}
bool DxilPIXMeshShaderOutputInstrumentation::runOnModule(Module &M) {
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
Type *OriginalPayloadStructType = nullptr;
ExpandedStruct expanded = {};
Instruction *FirstNewStructGetMeshPayload = nullptr;
if (m_ExpandPayload) {
Instruction *getMeshPayloadInstructions = nullptr;
llvm::Function *entryFunction = PIXPassHelpers::GetEntryFunction(DM);
for (inst_iterator I = inst_begin(entryFunction),
E = inst_end(entryFunction);
I != E; ++I) {
if (auto *Instr = llvm::cast<Instruction>(&*I)) {
if (hlsl::OP::IsDxilOpFuncCallInst(Instr,
hlsl::OP::OpCode::GetMeshPayload)) {
getMeshPayloadInstructions = Instr;
Type *OriginalPayloadStructPointerType = Instr->getType();
OriginalPayloadStructType =
OriginalPayloadStructPointerType->getPointerElementType();
// The validator assures that there is only one call to
// GetMeshPayload...
break;
}
}
}
if (OriginalPayloadStructType == nullptr) {
// If the application used no payload, then we won't attempt to add one.
// TODO: Is there a credible use case with no AS->MS payload?
// PIX bug #35288335
return false;
}
if (expanded.ExpandedPayloadStructPtrType == nullptr) {
expanded = ExpandStructType(Ctx, OriginalPayloadStructType);
}
if (getMeshPayloadInstructions != nullptr) {
Function *DxilFunc = HlslOP->GetOpFunc(
OP::OpCode::GetMeshPayload, expanded.ExpandedPayloadStructPtrType);
Constant *opArg =
HlslOP->GetU32Const((unsigned)OP::OpCode::GetMeshPayload);
IRBuilder<> Builder(getMeshPayloadInstructions);
Value *args[] = {opArg};
Instruction *payload = Builder.CreateCall(DxilFunc, args);
if (FirstNewStructGetMeshPayload == nullptr) {
FirstNewStructGetMeshPayload = payload;
}
ReplaceAllUsesOfInstructionWithNewValueAndDeleteInstruction(
getMeshPayloadInstructions, payload,
expanded.ExpandedPayloadStructType);
}
}
Instruction *firstInsertionPt =
dxilutil::FirstNonAllocaInsertionPt(GetEntryFunction(DM));
IRBuilder<> Builder(firstInsertionPt);
BuilderContext BC{M, DM, Ctx, HlslOP, Builder};
m_OffsetMask = BC.HlslOP->GetU32Const(UAVDumpingGroundOffset() - 1);
m_OutputUAV = CreateUAVOnceForModule(DM, Builder, 0, "PIX_DebugUAV_Handle");
if (FirstNewStructGetMeshPayload == nullptr) {
Instruction *firstInsertionPt = dxilutil::FirstNonAllocaInsertionPt(
PIXPassHelpers::GetEntryFunction(DM));
IRBuilder<> Builder(firstInsertionPt);
m_threadUniquifier = insertInstructionsToCreateDisambiguationValue(
Builder, HlslOP, Ctx, nullptr, nullptr);
} else {
IRBuilder<> Builder(FirstNewStructGetMeshPayload->getNextNode());
m_threadUniquifier = insertInstructionsToCreateDisambiguationValue(
Builder, HlslOP, Ctx, cast<StructType>(OriginalPayloadStructType),
FirstNewStructGetMeshPayload);
}
auto F = HlslOP->GetOpFunc(DXIL::OpCode::EmitIndices, Type::getVoidTy(Ctx));
auto FunctionUses = F->uses();
for (auto FI = FunctionUses.begin(); FI != FunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto Call = cast<CallInst>(FunctionUser);
IRBuilder<> Builder2(Call);
BuilderContext BC2{M, DM, Ctx, HlslOP, Builder2};
Instrument(BC2, BC2.HlslOP->GetI32Const(triangleIndexIndicator),
m_threadUniquifier[0], m_threadUniquifier[1],
Call->getOperand(1), Call->getOperand(2), Call->getOperand(3),
Call->getOperand(4));
}
struct OutputType {
Type *type;
uint32_t tag;
};
SmallVector<OutputType, 4> StoreVertexOutputOverloads{
{Type::getInt32Ty(Ctx), int32ValueIndicator},
{Type::getInt16Ty(Ctx), int16ValueIndicator},
{Type::getFloatTy(Ctx), floatValueIndicator},
{Type::getHalfTy(Ctx), float16ValueIndicator}};
for (auto const &Overload : StoreVertexOutputOverloads) {
F = HlslOP->GetOpFunc(DXIL::OpCode::StoreVertexOutput, Overload.type);
FunctionUses = F->uses();
for (auto FI = FunctionUses.begin(); FI != FunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto Call = cast<CallInst>(FunctionUser);
IRBuilder<> Builder2(Call);
BuilderContext BC2{M, DM, Ctx, HlslOP, Builder2};
// Expand column index to 32 bits:
auto ColumnIndex = BC2.Builder.CreateCast(
Instruction::ZExt, Call->getOperand(3), Type::getInt32Ty(Ctx));
// Coerce actual value to int32
Value *CoercedValue = Call->getOperand(4);
if (Overload.tag == floatValueIndicator) {
CoercedValue = BC2.Builder.CreateCast(
Instruction::BitCast, CoercedValue, Type::getInt32Ty(Ctx));
} else if (Overload.tag == float16ValueIndicator) {
auto *HalfInt = BC2.Builder.CreateCast(
Instruction::BitCast, CoercedValue, Type::getInt16Ty(Ctx));
CoercedValue = BC2.Builder.CreateCast(Instruction::ZExt, HalfInt,
Type::getInt32Ty(Ctx));
} else if (Overload.tag == int16ValueIndicator) {
CoercedValue = BC2.Builder.CreateCast(Instruction::ZExt, CoercedValue,
Type::getInt32Ty(Ctx));
}
Instrument(BC2, BC2.HlslOP->GetI32Const(Overload.tag),
m_threadUniquifier[0], m_threadUniquifier[1],
Call->getOperand(1), Call->getOperand(2), ColumnIndex,
CoercedValue, Call->getOperand(5));
}
}
DM.ReEmitDxilResources();
return true;
}
char DxilPIXMeshShaderOutputInstrumentation::ID = 0;
ModulePass *llvm::createDxilDxilPIXMeshShaderOutputInstrumentation() {
return new DxilPIXMeshShaderOutputInstrumentation();
}
INITIALIZE_PASS(DxilPIXMeshShaderOutputInstrumentation,
"hlsl-dxil-pix-meshshader-output-instrumentation",
"DXIL mesh shader output instrumentation for PIX", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilForceEarlyZ.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilOutputColorBecomesConstant.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to turn on the early-z flag //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "llvm/IR/Module.h"
using namespace llvm;
using namespace hlsl;
class DxilForceEarlyZ : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilForceEarlyZ() : ModulePass(ID) {}
StringRef getPassName() const override { return "DXIL Force Early Z"; }
bool runOnModule(Module &M) override;
};
bool DxilForceEarlyZ::runOnModule(Module &M) {
// This pass adds the force-early-z flag
DxilModule &DM = M.GetOrCreateDxilModule();
DM.m_ShaderFlags.SetForceEarlyDepthStencil(true);
DM.ReEmitDxilResources();
return true;
}
char DxilForceEarlyZ::ID = 0;
ModulePass *llvm::createDxilForceEarlyZPass() { return new DxilForceEarlyZ(); }
INITIALIZE_PASS(
DxilForceEarlyZ, "hlsl-dxil-force-early-z",
"HLSL DXIL Force the early Z global flag, if shader has no discard calls",
false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilPIXVirtualRegisters.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilPIXVirtualRegisters.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines functions for dealing with the virtual register annotations in //
// DXIL instructions. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/Support/Global.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
void pix_dxil::PixDxilInstNum::AddMD(llvm::LLVMContext &Ctx,
llvm::Instruction *pI,
std::uint32_t InstNum) {
llvm::IRBuilder<> B(Ctx);
pI->setMetadata(
llvm::StringRef(MDName),
llvm::MDNode::get(Ctx,
{llvm::ConstantAsMetadata::get(B.getInt32(ID)),
llvm::ConstantAsMetadata::get(B.getInt32(InstNum))}));
}
bool pix_dxil::PixDxilInstNum::FromInst(llvm::Instruction const *pI,
std::uint32_t *pInstNum) {
*pInstNum = 0;
auto *mdNodes = pI->getMetadata(MDName);
if (mdNodes == nullptr) {
return false;
}
if (mdNodes->getNumOperands() != 2) {
return false;
}
auto *mdID =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(mdNodes->getOperand(0));
if (mdID == nullptr || mdID->getLimitedValue() != ID) {
return false;
}
auto *mdInstNum =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(mdNodes->getOperand(1));
if (mdInstNum == nullptr) {
return false;
}
*pInstNum = mdInstNum->getLimitedValue();
return true;
}
void pix_dxil::PixDxilReg::AddMD(llvm::LLVMContext &Ctx, llvm::Instruction *pI,
std::uint32_t RegNum) {
llvm::IRBuilder<> B(Ctx);
pI->setMetadata(
llvm::StringRef(MDName),
llvm::MDNode::get(Ctx,
{llvm::ConstantAsMetadata::get(B.getInt32(ID)),
llvm::ConstantAsMetadata::get(B.getInt32(RegNum))}));
}
bool pix_dxil::PixDxilReg::FromInst(llvm::Instruction const *pI,
std::uint32_t *pRegNum) {
*pRegNum = 0;
auto *mdNodes = pI->getMetadata(MDName);
if (mdNodes == nullptr) {
return false;
}
if (mdNodes->getNumOperands() != 2) {
return false;
}
auto *mdID =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(mdNodes->getOperand(0));
if (mdID == nullptr || mdID->getLimitedValue() != ID) {
return false;
}
auto *mdRegNum =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(mdNodes->getOperand(1));
if (mdRegNum == nullptr) {
return false;
}
*pRegNum = mdRegNum->getLimitedValue();
return true;
}
static bool ParsePixAllocaReg(llvm::MDNode *MD, std::uint32_t *RegNum,
std::uint32_t *Count) {
if (MD->getNumOperands() != 3) {
return false;
}
auto *mdID = llvm::mdconst::dyn_extract<llvm::ConstantInt>(MD->getOperand(0));
if (mdID == nullptr ||
mdID->getLimitedValue() != pix_dxil::PixAllocaReg::ID) {
return false;
}
auto *mdRegNum =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(MD->getOperand(1));
auto *mdCount =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(MD->getOperand(2));
if (mdRegNum == nullptr || mdCount == nullptr) {
return false;
}
*RegNum = mdRegNum->getLimitedValue();
*Count = mdCount->getLimitedValue();
return true;
}
void pix_dxil::PixAllocaReg::AddMD(llvm::LLVMContext &Ctx,
llvm::AllocaInst *pAlloca,
std::uint32_t RegNum, std::uint32_t Count) {
llvm::IRBuilder<> B(Ctx);
pAlloca->setMetadata(
llvm::StringRef(MDName),
llvm::MDNode::get(Ctx,
{llvm::ConstantAsMetadata::get(B.getInt32(ID)),
llvm::ConstantAsMetadata::get(B.getInt32(RegNum)),
llvm::ConstantAsMetadata::get(B.getInt32(Count))}));
}
bool pix_dxil::PixAllocaReg::FromInst(llvm::AllocaInst const *pAlloca,
std::uint32_t *pRegBase,
std::uint32_t *pRegSize) {
*pRegBase = 0;
*pRegSize = 0;
auto *mdNodes = pAlloca->getMetadata(MDName);
if (mdNodes == nullptr) {
return false;
}
return ParsePixAllocaReg(mdNodes, pRegBase, pRegSize);
}
namespace pix_dxil {
namespace PixAllocaRegWrite {
static constexpr uint32_t IndexIsConst = 1;
static constexpr uint32_t IndexIsPixInst = 2;
} // namespace PixAllocaRegWrite
} // namespace pix_dxil
void pix_dxil::PixAllocaRegWrite::AddMD(llvm::LLVMContext &Ctx,
llvm::StoreInst *pSt,
llvm::MDNode *pAllocaReg,
llvm::Value *Index) {
llvm::IRBuilder<> B(Ctx);
if (auto *C = llvm::dyn_cast<llvm::ConstantInt>(Index)) {
pSt->setMetadata(
llvm::StringRef(MDName),
llvm::MDNode::get(
Ctx, {llvm::ConstantAsMetadata::get(B.getInt32(ID)), pAllocaReg,
llvm::ConstantAsMetadata::get(B.getInt32(IndexIsConst)),
llvm::ConstantAsMetadata::get(C)}));
}
if (auto *I = llvm::dyn_cast<llvm::Instruction>(Index)) {
std::uint32_t InstNum;
if (!PixDxilInstNum::FromInst(I, &InstNum)) {
return;
}
pSt->setMetadata(
llvm::StringRef(MDName),
llvm::MDNode::get(
Ctx, {llvm::ConstantAsMetadata::get(B.getInt32(ID)), pAllocaReg,
llvm::ConstantAsMetadata::get(B.getInt32(IndexIsPixInst)),
llvm::ConstantAsMetadata::get(B.getInt32(InstNum))}));
}
}
bool pix_dxil::PixAllocaRegWrite::FromInst(llvm::StoreInst *pI,
std::uint32_t *pRegBase,
std::uint32_t *pRegSize,
llvm::Value **pIndex) {
*pRegBase = 0;
*pRegSize = 0;
*pIndex = nullptr;
auto *mdNodes = pI->getMetadata(MDName);
if (mdNodes == nullptr || mdNodes->getNumOperands() != 4) {
return false;
}
auto *mdID =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(mdNodes->getOperand(0));
if (mdID == nullptr || mdID->getLimitedValue() != ID) {
return false;
}
auto *mdAllocaReg = llvm::dyn_cast<llvm::MDNode>(mdNodes->getOperand(1));
if (mdAllocaReg == nullptr ||
!ParsePixAllocaReg(mdAllocaReg, pRegBase, pRegSize)) {
return false;
}
auto *mdIndexType =
llvm::dyn_cast<llvm::ConstantAsMetadata>(mdNodes->getOperand(2));
if (mdIndexType == nullptr) {
return false;
}
auto *cIndexType = llvm::dyn_cast<llvm::ConstantInt>(mdIndexType->getValue());
if (cIndexType == nullptr) {
return false;
}
auto *mdIndex =
llvm::dyn_cast<llvm::ConstantAsMetadata>(mdNodes->getOperand(3));
if (mdIndex == nullptr) {
return false;
}
auto *cIndex = llvm::dyn_cast<llvm::ConstantInt>(mdIndex->getValue());
if (cIndex == nullptr) {
return false;
}
switch (cIndexType->getLimitedValue()) {
default:
return false;
case IndexIsConst: {
*pIndex = cIndex;
return true;
}
case IndexIsPixInst: {
for (llvm::Instruction &I :
llvm::inst_range(pI->getParent()->getParent())) {
uint32_t InstNum;
if (PixDxilInstNum::FromInst(&I, &InstNum)) {
*pIndex = &I;
if (InstNum == cIndex->getLimitedValue()) {
return true;
}
}
}
return false;
}
}
return false;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilDebugInstrumentation.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDebugInstrumentation.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Adds instrumentation that enables shader debugging in PIX //
// //
///////////////////////////////////////////////////////////////////////////////
#include <optional>
#include <vector>
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Module.h"
#include "PixPassHelpers.h"
using namespace llvm;
using namespace hlsl;
// Overview of instrumentation:
//
// In summary, instructions are added that cause a "trace" of the execution of
// the shader to be written out to a UAV. This trace is then used by a debugger
// application to provide a postmortem debugging experience that reconstructs
// the execution history of the shader. The caller specifies the power-of-two
// size of the UAV.
//
// The instrumentation is added per basic block, and each block will then write
// a contiguous sequence of values into the UAV.
//
// The trace is only required for particular shader instances of interest, and
// a branchless mechanism is used to write the trace either to an incrementing
// location within the UAV, or to a "dumping ground" area in the top half of the
// UAV if the instance is not of interest.
//
// In addition, each half of the UAV is further subdivided: the first quarter is
// the area in which blocks are permitted to start writing their sequence, and
// that sequence is constrained to be no longer than the size of the second
// quarter. This allows us to limit writes to the appropriate half of the UAV
// via a single AND at the beginning of the basic block. An additional OR
// provides the offset, either 0 for threads-of-interest, or UAVSize/2 for
// not-of-interest.
//
// Threads determine where to start writing their data by incrementing a DWORD
// that lives at the very top of that thread's half of the UAV. This is done
// because several threads may satisfy the selection criteria (e.g. a pixel
// shader may be invoked several times for a given pixel coordinate if the model
// has overlapping triangles).
//
// A picture of the UAV layout:
// <--------------power-of-two-size-of-UAV---------------->
// [1 ][2 ][3 ][4 ]
// <------A-----> ^ ^
// B C
// <------D------>
//
// A: the size of the AND for interesting writes. Their payloads extend
// beyond this into area 2, but those payloads are limited to be small
// enough (1/4 UAV size -1) that they don't overwrite B.
// B: The interesting thread's counter.
// C: The uninteresting thread's counter.
// D: Size of the AND for uninteresting threads (same value as A)
//
// The following modifications are made by this pass:
//
// First, instructions are added to the top of the entry point function that
// implement the following:
// - Examine the input variables that define the instance of the shader that is
// running. This will be SV_Position for pixel shaders, SV_Vertex+SV_Instance
// for vertex shaders, thread id for compute shaders etc. If these system
// values need to be added to the shader, then they are also added to the
// input signature, if appropriate.
// - Compare the above variables with the instance of interest defined by the
// invoker of this pass. If equal, create an OR value of zero that will
// not affect the block's starting write offset. If not equal, the OR will
// move the writes into the second half of the UAV.
// - Calculate an "instance identifier". Even with the above instance
// identification, several invocations may end up matching the selection
// criteria. More on this below.
//
// As mentioned, a counter/offset is maintained at the top of the thread's
// half of the UAV. The very first value of this counter that
// is encountered by each invocation is used as the "instance identifier"
// mentioned above. That instance identifier is written out with each packet,
// since many threads executing in parallel will emit interleaved packets,
// and the debugger application uses the identifiers to gather packets from each
// separate invocation together.
//
// In addition to the above, this pass creates a text precis of the structure
// being written out for each basic block. This precis is passed back to the
// caller, and can be used to parse the UAV output later. The precis will
// contain notes about void-type instructions, which won't write anything to the
// UAV, allowing the caller to reconstruct those instructions.
// Some care has to be taken about whether to emit UAV writes after the
// corresponding instruction or before. Terminators must emit their UAV data
// before the terminator itself, of course. Phi instructions get special
// treatment also: their instrumentation has to come after (since phis must be
// the first instructions in the block), but also the instrumentation must
// execute in the same order as the precis specifies, or the caller will mix
// up the phi values. We achieve this by saying that phi instrumentation must
// come before the first non-phi instruction in the block.
// Some blocks will have all-void instructions, so that no debugging
// data is emitted at all. These blocks still produce a precis, and still
// need to be noticed during execution, so an empty block header is emitted
// into the UAV.
//
// Error conditions:
// Overflow of the debug output from the interesting threads will start to
// overwrite their own area of the UAV (after the AND limits those writes
// to the lower half of the UAV (thus, by the way, avoiding overwriting
// their counter value)). The caller must check the counter value after
// the debugging run is complete to see if this happened, and if so, increase
// the UAV size and try again.
// Uninteresting threads use an AND value that limits their writes to the
// upper half of the UAV and can be entirely ignored by the caller.
// Since a sufficiently-large block is guaranteed to overflow the UAV,
// the precis-creation can exit early and report this "static" overflow
// condition to the caller.
// In all overflow cases, the caller is expected to try to instrument again,
// with a larger UAV.
// These definitions echo those in the debugger application's
// debugshaderrecord.h file
enum DebugShaderModifierRecordType {
DebugShaderModifierRecordTypeInvocationStartMarker,
DebugShaderModifierRecordTypeStep,
DebugShaderModifierRecordTypeEvent,
DebugShaderModifierRecordTypeInputRegister,
DebugShaderModifierRecordTypeReadRegister,
DebugShaderModifierRecordTypeWrittenRegister,
DebugShaderModifierRecordTypeRegisterRelativeIndex0,
DebugShaderModifierRecordTypeRegisterRelativeIndex1,
DebugShaderModifierRecordTypeRegisterRelativeIndex2,
// Note that everything above this line is no longer used, but is kept
// here in order to keep this file more in-sync with the debugger source.
// (As of this writing, the debugger still supports older versions of this
// pass which produced finer-grained debug packets.)
DebugShaderModifierRecordTypeDXILStepBlock = 249,
DebugShaderModifierRecordTypeDXILStepRet = 250,
DebugShaderModifierRecordTypeDXILStepVoid = 251,
DebugShaderModifierRecordTypeDXILStepFloat = 252,
DebugShaderModifierRecordTypeDXILStepUint32 = 253,
DebugShaderModifierRecordTypeDXILStepUint64 = 254,
DebugShaderModifierRecordTypeDXILStepDouble = 255,
};
// These structs echo those in the debugger application's debugshaderrecord.h
// file, but are recapitulated here because the originals use unnamed unions
// which are disallowed by DXCompiler's build.
//
#pragma pack(push, 4)
struct DebugShaderModifierRecordHeader {
union {
struct {
uint32_t SizeDwords : 4;
uint32_t Flags : 4;
uint32_t Type : 8;
uint32_t HeaderPayload : 16;
} Details;
uint32_t u32Header;
} Header;
uint32_t UID;
};
struct DebugShaderModifierRecordDXILStepBase {
union {
struct {
uint32_t SizeDwords : 4;
uint32_t Flags : 4;
uint32_t Type : 8;
uint32_t Opcode : 16;
} Details;
uint32_t u32Header;
} Header;
uint32_t UID;
uint32_t InstructionOffset;
};
struct DebugShaderModifierRecordDXILBlock {
union {
struct {
uint32_t NotUsed0 : 4;
uint32_t NotUsed1 : 4;
uint32_t Type : 8;
uint32_t CountOfInstructions : 16;
} Details;
uint32_t u32Header;
} Header;
uint32_t UID;
uint32_t FirstInstructionOrdinal;
};
template <typename ReturnType>
struct DebugShaderModifierRecordDXILStep
: public DebugShaderModifierRecordDXILStepBase {
ReturnType ReturnValue;
union {
struct {
uint32_t ValueOrdinalBase : 16;
uint32_t ValueOrdinalIndex : 16;
} Details;
uint32_t u32ValueOrdinal;
} ValueOrdinal;
};
template <>
struct DebugShaderModifierRecordDXILStep<void>
: public DebugShaderModifierRecordDXILStepBase {};
#pragma pack(pop)
uint32_t
DebugShaderModifierRecordPayloadSizeDwords(size_t recordTotalSizeBytes) {
return ((recordTotalSizeBytes - sizeof(DebugShaderModifierRecordHeader)) /
sizeof(uint32_t));
}
struct InstructionAndType {
Instruction *Inst;
std::uint32_t InstructionOrdinal;
DebugShaderModifierRecordType Type;
std::uint32_t RegisterNumber;
std::uint32_t AllocaBase;
Value *AllocaWriteIndex = nullptr;
std::optional<uint64_t> ConstantAllocaStoreValue;
};
class DxilDebugInstrumentation : public ModulePass {
private:
union ParametersAllTogether {
unsigned Parameters[3];
struct PixelShaderParameters {
unsigned X;
unsigned Y;
} PixelShader;
struct VertexShaderParameters {
unsigned VertexId;
unsigned InstanceId;
} VertexShader;
struct ComputeShaderParameters {
unsigned ThreadIdX;
unsigned ThreadIdY;
unsigned ThreadIdZ;
} ComputeShader;
struct GeometryShaderParameters {
unsigned PrimitiveId;
unsigned InstanceId;
} GeometryShader;
struct HullShaderParameters {
unsigned PrimitiveId;
unsigned ControlPointId;
} HullShader;
struct DomainShaderParameters {
unsigned PrimitiveId;
} DomainShader;
} m_Parameters = {{0, 0, 0}};
union SystemValueIndices {
struct PixelShaderParameters {
unsigned Position;
} PixelShader;
struct VertexShaderParameters {
unsigned VertexId;
unsigned InstanceId;
} VertexShader;
};
unsigned m_FirstInstruction = 0;
unsigned m_LastInstruction = static_cast<unsigned>(-1);
uint64_t m_UAVSize = 1024 * 1024;
unsigned m_upstreamSVPositionRow;
struct PerFunctionValues {
CallInst *UAVHandle = nullptr;
Instruction *CounterOffset = nullptr;
Value *InvocationId = nullptr;
// Together these two values allow branchless writing to the UAV. An
// invocation of the shader is either of interest or not (e.g. it writes to
// the pixel the user selected for debugging or it doesn't). If not of
// interest, debugging output will still occur, but it will be relegated to
// the top half of the UAV. Invocations of interest, by contrast,
// will be written to the UAV at sequentially increasing offsets.
Value *OffsetMask = nullptr;
Instruction *OffsetOr = nullptr;
Value *SelectionCriterion = nullptr;
Value *CurrentIndex = nullptr;
std::vector<BasicBlock *> AddedBlocksToIgnoreForInstrumentation;
};
std::map<llvm::Function *, PerFunctionValues> m_FunctionToValues;
struct BuilderContext {
Module &M;
DxilModule &DM;
LLVMContext &Ctx;
OP *HlslOP;
IRBuilder<> &Builder;
};
uint32_t m_RemainingReservedSpaceInBytes = 0;
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilDebugInstrumentation() : ModulePass(ID) {}
StringRef getPassName() const override {
return "Add PIX debug instrumentation";
}
void applyOptions(PassOptions O) override;
bool runOnModule(Module &M) override;
bool RunOnFunction(Module &M, DxilModule &DM, hlsl::DxilResource *uav,
llvm::Function *function);
private:
SystemValueIndices addRequiredSystemValues(BuilderContext &BC,
DXIL::ShaderKind shaderKind);
void addInvocationSelectionProlog(BuilderContext &BC,
SystemValueIndices SVIndices,
DXIL::ShaderKind shaderKind);
Value *addPixelShaderProlog(BuilderContext &BC, SystemValueIndices SVIndices);
Value *addGeometryShaderProlog(BuilderContext &BC);
Value *addDispatchedShaderProlog(BuilderContext &BC);
Value *addRaygenShaderProlog(BuilderContext &BC);
Value *addVertexShaderProlog(BuilderContext &BC,
SystemValueIndices SVIndices);
Value *addHullhaderProlog(BuilderContext &BC);
Value *addComparePrimitiveIdProlog(BuilderContext &BC, unsigned SVIndices);
uint32_t addDebugEntryValue(BuilderContext &BC, Value *TheValue);
void addInvocationStartMarker(BuilderContext &BC);
void determineLimitANDAndInitializeCounter(BuilderContext &BC);
void reserveDebugEntrySpace(BuilderContext &BC, uint32_t SpaceInDwords);
std::optional<InstructionAndType> addStoreStepDebugEntry(BuilderContext *BC,
StoreInst *Inst);
std::optional<InstructionAndType>
addStepDebugEntry(BuilderContext *BC, Instruction *Inst,
llvm::SmallPtrSetImpl<Value *> const &RayQueryHandles);
std::optional<DebugShaderModifierRecordType>
addStepDebugEntryValue(BuilderContext *BC, std::uint32_t InstNum, Value *V,
std::uint32_t ValueOrdinal, Value *ValueOrdinalIndex);
uint32_t UAVDumpingGroundOffset();
template <typename ReturnType>
void addStepEntryForType(DebugShaderModifierRecordType RecordType,
BuilderContext &BC, std::uint32_t InstNum, Value *V,
std::uint32_t ValueOrdinal,
Value *ValueOrdinalIndex);
struct InstructionToInstrument {
Value *ValueToWriteToDebugMemory;
DebugShaderModifierRecordType ValueType;
Instruction *InstructionAfterWhichToAddInstrumentation;
Instruction *InstructionBeforeWhichToAddInstrumentation;
};
struct BlockInstrumentationData {
uint32_t FirstInstructionOrdinalInBlock;
std::vector<InstructionToInstrument> Instructions;
};
BlockInstrumentationData FindInstrumentableInstructionsInBlock(
BasicBlock &BB, OP *HlslOP,
llvm::SmallPtrSetImpl<Value *> const &RayQueryHandles);
uint32_t
CountBlockPayloadBytes(std::vector<InstructionToInstrument> const &IsAndTs);
};
void DxilDebugInstrumentation::applyOptions(PassOptions O) {
GetPassOptionUnsigned(O, "FirstInstruction", &m_FirstInstruction, 0);
GetPassOptionUnsigned(O, "LastInstruction", &m_LastInstruction,
static_cast<unsigned>(-1));
GetPassOptionUnsigned(O, "parameter0", &m_Parameters.Parameters[0], 0);
GetPassOptionUnsigned(O, "parameter1", &m_Parameters.Parameters[1], 0);
GetPassOptionUnsigned(O, "parameter2", &m_Parameters.Parameters[2], 0);
GetPassOptionUInt64(O, "UAVSize", &m_UAVSize, 1024 * 1024);
GetPassOptionUnsigned(O, "upstreamSVPositionRow", &m_upstreamSVPositionRow,
0);
}
uint32_t DxilDebugInstrumentation::UAVDumpingGroundOffset() {
return static_cast<uint32_t>(m_UAVSize / 2);
}
unsigned int GetNextEmptyRow(
std::vector<std::unique_ptr<DxilSignatureElement>> const &Elements) {
unsigned int Row = 0;
for (auto const &Element : Elements) {
Row = std::max<unsigned>(Row, Element->GetStartRow() + Element->GetRows());
}
return Row;
}
unsigned FindOrAddVSInSignatureElementForInstanceOrVertexID(
hlsl::DxilSignature &InputSignature,
hlsl::DXIL::SemanticKind semanticKind) {
DXASSERT(InputSignature.GetSigPointKind() == DXIL::SigPointKind::VSIn,
"Unexpected SigPointKind in input signature");
DXASSERT(semanticKind == DXIL::SemanticKind::InstanceID ||
semanticKind == DXIL::SemanticKind::VertexID,
"This function only expects InstaceID or VertexID");
auto const &InputElements = InputSignature.GetElements();
auto ExistingElement =
std::find_if(InputElements.begin(), InputElements.end(),
[&](const std::unique_ptr<DxilSignatureElement> &Element) {
return Element->GetSemantic()->GetKind() == semanticKind;
});
if (ExistingElement == InputElements.end()) {
auto AddedElement =
llvm::make_unique<DxilSignatureElement>(DXIL::SigPointKind::VSIn);
unsigned Row = GetNextEmptyRow(InputElements);
AddedElement->Initialize(
hlsl::Semantic::Get(semanticKind)->GetName(), hlsl::CompType::getU32(),
hlsl::DXIL::InterpolationMode::Constant, 1, 1, Row, 0);
AddedElement->AppendSemanticIndex(0);
AddedElement->SetKind(semanticKind);
AddedElement->SetUsageMask(1);
// AppendElement sets the element's ID by default
auto index = InputSignature.AppendElement(std::move(AddedElement));
return InputElements[index]->GetID();
} else {
return ExistingElement->get()->GetID();
}
}
DxilDebugInstrumentation::SystemValueIndices
DxilDebugInstrumentation::addRequiredSystemValues(BuilderContext &BC,
DXIL::ShaderKind shaderKind) {
SystemValueIndices SVIndices{};
switch (shaderKind) {
case DXIL::ShaderKind::Amplification:
case DXIL::ShaderKind::Mesh:
case DXIL::ShaderKind::Compute:
case DXIL::ShaderKind::RayGeneration:
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Miss:
case DXIL::ShaderKind::Node:
// Dispatch* thread Id is not in the input signature
break;
case DXIL::ShaderKind::Vertex: {
hlsl::DxilSignature &InputSignature = BC.DM.GetInputSignature();
SVIndices.VertexShader.VertexId =
FindOrAddVSInSignatureElementForInstanceOrVertexID(
InputSignature, hlsl::DXIL::SemanticKind::VertexID);
SVIndices.VertexShader.InstanceId =
FindOrAddVSInSignatureElementForInstanceOrVertexID(
InputSignature, hlsl::DXIL::SemanticKind::InstanceID);
} break;
case DXIL::ShaderKind::Geometry:
case DXIL::ShaderKind::Hull:
case DXIL::ShaderKind::Domain:
// GS, HS, DS Primitive id, HS control point id, and GS Instance id are not
// in the input signature
break;
case DXIL::ShaderKind::Pixel: {
SVIndices.PixelShader.Position =
PIXPassHelpers::FindOrAddSV_Position(BC.DM, m_upstreamSVPositionRow);
} break;
default:
assert(false); // guaranteed by runOnModule
}
return SVIndices;
}
Value *DxilDebugInstrumentation::addDispatchedShaderProlog(BuilderContext &BC) {
Constant *Zero32Arg = BC.HlslOP->GetU32Const(0);
Constant *One32Arg = BC.HlslOP->GetU32Const(1);
Constant *Two32Arg = BC.HlslOP->GetU32Const(2);
auto ThreadIdFunc =
BC.HlslOP->GetOpFunc(DXIL::OpCode::ThreadId, Type::getInt32Ty(BC.Ctx));
Constant *Opcode = BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::ThreadId);
auto ThreadIdX =
BC.Builder.CreateCall(ThreadIdFunc, {Opcode, Zero32Arg}, "ThreadIdX");
auto ThreadIdY =
BC.Builder.CreateCall(ThreadIdFunc, {Opcode, One32Arg}, "ThreadIdY");
auto ThreadIdZ =
BC.Builder.CreateCall(ThreadIdFunc, {Opcode, Two32Arg}, "ThreadIdZ");
// Compare to expected thread ID
auto CompareToX = BC.Builder.CreateICmpEQ(
ThreadIdX, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdX),
"CompareToThreadIdX");
auto CompareToY = BC.Builder.CreateICmpEQ(
ThreadIdY, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdY),
"CompareToThreadIdY");
auto CompareToZ = BC.Builder.CreateICmpEQ(
ThreadIdZ, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdZ),
"CompareToThreadIdZ");
auto CompareXAndY =
BC.Builder.CreateAnd(CompareToX, CompareToY, "CompareXAndY");
auto CompareAll =
BC.Builder.CreateAnd(CompareXAndY, CompareToZ, "CompareAll");
return CompareAll;
}
Value *DxilDebugInstrumentation::addRaygenShaderProlog(BuilderContext &BC) {
auto DispatchRaysIndexOpFunc = BC.HlslOP->GetOpFunc(
DXIL::OpCode::DispatchRaysIndex, Type::getInt32Ty(BC.Ctx));
Constant *DispatchRaysIndexOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::DispatchRaysIndex);
auto RayX = BC.Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, BC.HlslOP->GetI8Const(0)}, "RayX");
auto RayY = BC.Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, BC.HlslOP->GetI8Const(1)}, "RayY");
auto RayZ = BC.Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, BC.HlslOP->GetI8Const(2)}, "RayZ");
auto CompareToX = BC.Builder.CreateICmpEQ(
RayX, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdX),
"CompareToThreadIdX");
auto CompareToY = BC.Builder.CreateICmpEQ(
RayY, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdY),
"CompareToThreadIdY");
auto CompareToZ = BC.Builder.CreateICmpEQ(
RayZ, BC.HlslOP->GetU32Const(m_Parameters.ComputeShader.ThreadIdZ),
"CompareToThreadIdZ");
auto CompareXAndY =
BC.Builder.CreateAnd(CompareToX, CompareToY, "CompareXAndY");
auto CompareAll =
BC.Builder.CreateAnd(CompareXAndY, CompareToZ, "CompareAll");
return CompareAll;
}
Value *
DxilDebugInstrumentation::addVertexShaderProlog(BuilderContext &BC,
SystemValueIndices SVIndices) {
Constant *Zero32Arg = BC.HlslOP->GetU32Const(0);
Constant *Zero8Arg = BC.HlslOP->GetI8Const(0);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
auto LoadInputOpFunc =
BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getInt32Ty(BC.Ctx));
Constant *LoadInputOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
Constant *SV_Vert_ID =
BC.HlslOP->GetU32Const(SVIndices.VertexShader.VertexId);
auto VertId =
BC.Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Vert_ID, Zero32Arg /*row*/,
Zero8Arg /*column*/, UndefArg},
"VertId");
Constant *SV_Instance_ID =
BC.HlslOP->GetU32Const(SVIndices.VertexShader.InstanceId);
auto InstanceId =
BC.Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Instance_ID, Zero32Arg /*row*/,
Zero8Arg /*column*/, UndefArg},
"InstanceId");
// Compare to expected vertex ID and instance ID
auto CompareToVert = BC.Builder.CreateICmpEQ(
VertId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.VertexId),
"CompareToVertId");
auto CompareToInstance = BC.Builder.CreateICmpEQ(
InstanceId, BC.HlslOP->GetU32Const(m_Parameters.VertexShader.InstanceId),
"CompareToInstanceId");
auto CompareBoth =
BC.Builder.CreateAnd(CompareToVert, CompareToInstance, "CompareBoth");
return CompareBoth;
}
Value *DxilDebugInstrumentation::addHullhaderProlog(BuilderContext &BC) {
auto LoadControlPointFunction = BC.HlslOP->GetOpFunc(
DXIL::OpCode::OutputControlPointID, Type::getInt32Ty(BC.Ctx));
Constant *LoadControlPointOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::OutputControlPointID);
auto ControlPointId = BC.Builder.CreateCall(
LoadControlPointFunction, {LoadControlPointOpcode}, "ControlPointId");
auto *CompareToPrimId =
addComparePrimitiveIdProlog(BC, m_Parameters.HullShader.PrimitiveId);
auto CompareToControlPoint = BC.Builder.CreateICmpEQ(
ControlPointId,
BC.HlslOP->GetU32Const(m_Parameters.HullShader.ControlPointId),
"CompareToControlPointId");
auto CompareBoth = BC.Builder.CreateAnd(CompareToControlPoint,
CompareToPrimId, "CompareBoth");
return CompareBoth;
}
Value *DxilDebugInstrumentation::addComparePrimitiveIdProlog(BuilderContext &BC,
unsigned primId) {
auto PrimitiveIdFunction =
BC.HlslOP->GetOpFunc(DXIL::OpCode::PrimitiveID, Type::getInt32Ty(BC.Ctx));
Constant *PrimitiveIdOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::PrimitiveID);
auto PrimId =
BC.Builder.CreateCall(PrimitiveIdFunction, {PrimitiveIdOpcode}, "PrimId");
return BC.Builder.CreateICmpEQ(PrimId, BC.HlslOP->GetU32Const(primId),
"CompareToPrimId");
}
Value *DxilDebugInstrumentation::addGeometryShaderProlog(BuilderContext &BC) {
auto CompareToPrim =
addComparePrimitiveIdProlog(BC, m_Parameters.GeometryShader.PrimitiveId);
if (BC.DM.GetGSInstanceCount() <= 1) {
return CompareToPrim;
}
auto GSInstanceIdOpFunc = BC.HlslOP->GetOpFunc(DXIL::OpCode::GSInstanceID,
Type::getInt32Ty(BC.Ctx));
Constant *GSInstanceIdOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::GSInstanceID);
auto GSInstanceId = BC.Builder.CreateCall(
GSInstanceIdOpFunc, {GSInstanceIdOpcode}, "GSInstanceId");
// Compare to expected vertex ID and instance ID
auto CompareToInstance = BC.Builder.CreateICmpEQ(
GSInstanceId,
BC.HlslOP->GetU32Const(m_Parameters.GeometryShader.InstanceId),
"CompareToInstanceId");
auto CompareBoth =
BC.Builder.CreateAnd(CompareToPrim, CompareToInstance, "CompareBoth");
return CompareBoth;
}
Value *
DxilDebugInstrumentation::addPixelShaderProlog(BuilderContext &BC,
SystemValueIndices SVIndices) {
Constant *Zero32Arg = BC.HlslOP->GetU32Const(0);
Constant *Zero8Arg = BC.HlslOP->GetI8Const(0);
Constant *One8Arg = BC.HlslOP->GetI8Const(1);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
// Convert SV_POSITION to UINT
Value *XAsInt;
Value *YAsInt;
{
auto LoadInputOpFunc =
BC.HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getFloatTy(BC.Ctx));
Constant *LoadInputOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
Constant *SV_Pos_ID =
BC.HlslOP->GetU32Const(SVIndices.PixelShader.Position);
auto XPos =
BC.Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
Zero8Arg /*column*/, UndefArg},
"XPos");
auto YPos =
BC.Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
One8Arg /*column*/, UndefArg},
"YPos");
XAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, XPos,
Type::getInt32Ty(BC.Ctx), "XIndex");
YAsInt = BC.Builder.CreateCast(Instruction::CastOps::FPToUI, YPos,
Type::getInt32Ty(BC.Ctx), "YIndex");
}
// Compare to expected pixel position and primitive ID
auto CompareToX = BC.Builder.CreateICmpEQ(
XAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.X), "CompareToX");
auto CompareToY = BC.Builder.CreateICmpEQ(
YAsInt, BC.HlslOP->GetU32Const(m_Parameters.PixelShader.Y), "CompareToY");
auto ComparePos = BC.Builder.CreateAnd(CompareToX, CompareToY, "ComparePos");
return ComparePos;
}
void DxilDebugInstrumentation::addInvocationSelectionProlog(
BuilderContext &BC, SystemValueIndices SVIndices,
DXIL::ShaderKind shaderKind) {
Value *ParameterTestResult = nullptr;
switch (shaderKind) {
case DXIL::ShaderKind::RayGeneration:
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::Miss:
ParameterTestResult = addRaygenShaderProlog(BC);
break;
case DXIL::ShaderKind::Node:
ParameterTestResult = BC.HlslOP->GetI1Const(1);
break;
case DXIL::ShaderKind::Compute:
case DXIL::ShaderKind::Amplification:
case DXIL::ShaderKind::Mesh:
ParameterTestResult = addDispatchedShaderProlog(BC);
break;
case DXIL::ShaderKind::Geometry:
ParameterTestResult = addGeometryShaderProlog(BC);
break;
case DXIL::ShaderKind::Vertex:
ParameterTestResult = addVertexShaderProlog(BC, SVIndices);
break;
case DXIL::ShaderKind::Hull:
ParameterTestResult = addHullhaderProlog(BC);
break;
case DXIL::ShaderKind::Domain:
ParameterTestResult =
addComparePrimitiveIdProlog(BC, m_Parameters.DomainShader.PrimitiveId);
break;
case DXIL::ShaderKind::Pixel:
ParameterTestResult = addPixelShaderProlog(BC, SVIndices);
break;
default:
assert(false); // guaranteed by runOnModule
}
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
values.SelectionCriterion = ParameterTestResult;
}
void DxilDebugInstrumentation::determineLimitANDAndInitializeCounter(
BuilderContext &BC) {
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
// Split the block at the current insertion point. Insert a conditional
// branch that will invoke one of two new blocks depending on if this
// is a thread-of-interest. The two different classes of thread will
// then be given different limiting AND values within these new
// blocks.
BasicBlock *RestOfMainBlock = BC.Builder.GetInsertBlock()->splitBasicBlock(
*BC.Builder.GetInsertPoint());
// Up to this split point is a new block that we don't need to instrument:
values.AddedBlocksToIgnoreForInstrumentation.push_back(
BC.Builder.GetInsertBlock());
auto *InterestingInvocationBlock = BasicBlock::Create(
BC.Ctx, "PIXInterestingBlock", BC.Builder.GetInsertBlock()->getParent(),
RestOfMainBlock);
values.AddedBlocksToIgnoreForInstrumentation.push_back(
InterestingInvocationBlock);
IRBuilder<> BuilderForInteresting(InterestingInvocationBlock);
BuilderForInteresting.CreateBr(RestOfMainBlock);
auto *NonInterestingInvocationBlock = BasicBlock::Create(
BC.Ctx, "PIXNonInterestingBlock",
BC.Builder.GetInsertBlock()->getParent(), RestOfMainBlock);
values.AddedBlocksToIgnoreForInstrumentation.push_back(
NonInterestingInvocationBlock);
IRBuilder<> BuilderForNonInteresting(NonInterestingInvocationBlock);
BuilderForNonInteresting.CreateBr(RestOfMainBlock);
// Connect these new blocks as necessary:
BC.Builder.SetInsertPoint(BC.Builder.GetInsertBlock()->getTerminator());
BC.Builder.CreateCondBr(values.SelectionCriterion, InterestingInvocationBlock,
NonInterestingInvocationBlock);
BC.Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
values.OffsetMask = BC.HlslOP->GetU32Const(m_UAVSize / 4 - 1);
// Now add a phi that selects between two constant OR values based on
// which branch the thread followed above (interesting or not).
// The OR will either place the output in the lower half or the upper
// half of the UAV.
BC.Builder.SetInsertPoint(RestOfMainBlock->getFirstInsertionPt());
auto *PHIForOr =
BC.Builder.CreatePHI(Type::getInt32Ty(BC.Ctx), 2, "PIXOffsetOr");
PHIForOr->addIncoming(BC.HlslOP->GetU32Const(0), InterestingInvocationBlock);
PHIForOr->addIncoming(BC.HlslOP->GetU32Const(m_UAVSize / 2),
NonInterestingInvocationBlock);
values.OffsetOr = PHIForOr;
auto *PHIForCounterOffset =
BC.Builder.CreatePHI(Type::getInt32Ty(BC.Ctx), 2, "PIXCounterLocation");
const uint32_t InterestingCounterOffset =
static_cast<uint32_t>(m_UAVSize / 2 - 1);
PHIForCounterOffset->addIncoming(
BC.HlslOP->GetU32Const(InterestingCounterOffset),
InterestingInvocationBlock);
const uint32_t UninterestingCounterOffsetValue =
static_cast<uint32_t>(m_UAVSize - 1);
PHIForCounterOffset->addIncoming(
BC.HlslOP->GetU32Const(UninterestingCounterOffsetValue),
NonInterestingInvocationBlock);
values.CounterOffset = PHIForCounterOffset;
// These are reported to the caller so there are fewer assumptions made by the
// caller about these internal details:
*OSOverride << "InterestingCounterOffset:"
<< std::to_string(InterestingCounterOffset) << "\n";
*OSOverride << "OverflowThreshold:" << std::to_string(m_UAVSize / 4 - 1)
<< "\n";
}
void DxilDebugInstrumentation::reserveDebugEntrySpace(BuilderContext &BC,
uint32_t SpaceInBytes) {
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
assert(values.CurrentIndex == nullptr);
assert(m_RemainingReservedSpaceInBytes == 0);
m_RemainingReservedSpaceInBytes = SpaceInBytes;
// Insert the UAV increment instruction:
Function *AtomicOpFunc =
BC.HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(BC.Ctx));
Constant *AtomicBinOpcode =
BC.HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
Constant *AtomicAdd =
BC.HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
Constant *Increment = BC.HlslOP->GetU32Const(SpaceInBytes);
auto PreviousValue = BC.Builder.CreateCall(
AtomicOpFunc,
{
AtomicBinOpcode, // i32, ; opcode
values.UAVHandle, // %dx.types.Handle, ; resource handle
AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD, AND, OR,
// XOR, IMIN, IMAX, UMIN, UMAX
values.CounterOffset, // i32, ; coordinate c0: index in bytes
UndefArg, // i32, ; coordinate c1 (unused)
UndefArg, // i32, ; coordinate c2 (unused)
Increment, // i32); increment value
},
"UAVIncResult");
if (values.InvocationId == nullptr) {
values.InvocationId = PreviousValue;
}
auto *Masked = BC.Builder.CreateAnd(PreviousValue, values.OffsetMask,
"MaskedForUAVLimit");
values.CurrentIndex =
BC.Builder.CreateOr(Masked, values.OffsetOr, "ORedForUAVStart");
}
uint32_t DxilDebugInstrumentation::addDebugEntryValue(BuilderContext &BC,
Value *TheValue) {
assert(m_RemainingReservedSpaceInBytes > 0);
uint32_t BytesToBeEmitted = 0;
auto TheValueTypeID = TheValue->getType()->getTypeID();
if (TheValueTypeID == Type::TypeID::DoubleTyID) {
Function *SplitDouble =
BC.HlslOP->GetOpFunc(OP::OpCode::SplitDouble, TheValue->getType());
Constant *SplitDoubleOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::SplitDouble);
auto SplitDoubleIntruction = BC.Builder.CreateCall(
SplitDouble, {SplitDoubleOpcode, TheValue}, "SplitDouble");
auto LowBits =
BC.Builder.CreateExtractValue(SplitDoubleIntruction, 0, "LowBits");
auto HighBits =
BC.Builder.CreateExtractValue(SplitDoubleIntruction, 1, "HighBits");
// addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
addDebugEntryValue(BC, LowBits);
addDebugEntryValue(BC, HighBits);
BytesToBeEmitted += 8;
} else if (TheValueTypeID == Type::TypeID::IntegerTyID &&
TheValue->getType()->getIntegerBitWidth() == 64) {
auto LowBits =
BC.Builder.CreateTrunc(TheValue, Type::getInt32Ty(BC.Ctx), "LowBits");
auto ShiftedBits = BC.Builder.CreateLShr(TheValue, 32, "ShiftedBits");
auto HighBits = BC.Builder.CreateTrunc(
ShiftedBits, Type::getInt32Ty(BC.Ctx), "HighBits");
// addDebugEntryValue(BC, BC.HlslOP->GetU32Const(0)); // padding
addDebugEntryValue(BC, LowBits);
addDebugEntryValue(BC, HighBits);
BytesToBeEmitted += 8;
} else if (TheValueTypeID == Type::TypeID::IntegerTyID &&
(TheValue->getType()->getIntegerBitWidth() < 32)) {
auto As32 =
BC.Builder.CreateZExt(TheValue, Type::getInt32Ty(BC.Ctx), "As32");
BytesToBeEmitted += addDebugEntryValue(BC, As32);
} else if (TheValueTypeID == Type::TypeID::HalfTyID) {
auto AsFloat =
BC.Builder.CreateFPCast(TheValue, Type::getFloatTy(BC.Ctx), "AsFloat");
BytesToBeEmitted += addDebugEntryValue(BC, AsFloat);
} else {
Function *StoreValue =
BC.HlslOP->GetOpFunc(OP::OpCode::RawBufferStore,
TheValue->getType()); // Type::getInt32Ty(BC.Ctx));
Constant *StoreValueOpcode =
BC.HlslOP->GetU32Const((unsigned)DXIL::OpCode::RawBufferStore);
UndefValue *Undef32Arg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
UndefValue *UndefArg = nullptr;
if (TheValueTypeID == Type::TypeID::IntegerTyID) {
UndefArg = UndefValue::get(Type::getInt32Ty(BC.Ctx));
} else if (TheValueTypeID == Type::TypeID::FloatTyID) {
UndefArg = UndefValue::get(Type::getFloatTy(BC.Ctx));
} else {
// The above are the only two valid types for a UAV store
assert(false);
}
BytesToBeEmitted += 4;
Constant *WriteMask_X = BC.HlslOP->GetI8Const(1);
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
Constant *RawBufferStoreAlignment = BC.HlslOP->GetU32Const(4);
(void)BC.Builder.CreateCall(
StoreValue, {StoreValueOpcode, // i32 opcode
values.UAVHandle, // %dx.types.Handle, ; resource handle
values.CurrentIndex, // i32 c0: index in bytes into UAV
Undef32Arg, // i32 c1: unused
TheValue,
UndefArg, // unused values
UndefArg, // unused values
UndefArg, // unused values
WriteMask_X, RawBufferStoreAlignment});
assert(m_RemainingReservedSpaceInBytes >= 4); // check for underflow
m_RemainingReservedSpaceInBytes -= 4;
if (m_RemainingReservedSpaceInBytes != 0) {
values.CurrentIndex =
BC.Builder.CreateAdd(values.CurrentIndex, BC.HlslOP->GetU32Const(4));
} else {
values.CurrentIndex = nullptr;
}
}
return BytesToBeEmitted;
}
void DxilDebugInstrumentation::addInvocationStartMarker(BuilderContext &BC) {
DebugShaderModifierRecordHeader marker{{{0, 0, 0, 0}}, 0};
reserveDebugEntrySpace(BC, sizeof(marker));
marker.Header.Details.SizeDwords =
DebugShaderModifierRecordPayloadSizeDwords(sizeof(marker));
marker.Header.Details.Flags = 0;
marker.Header.Details.Type =
DebugShaderModifierRecordTypeInvocationStartMarker;
addDebugEntryValue(BC, BC.HlslOP->GetU32Const(marker.Header.u32Header));
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
addDebugEntryValue(BC, values.InvocationId);
}
template <typename ReturnType>
void DxilDebugInstrumentation::addStepEntryForType(
DebugShaderModifierRecordType RecordType, BuilderContext &BC,
std::uint32_t InstNum, Value *V, std::uint32_t ValueOrdinal,
Value *ValueOrdinalIndex) {
DebugShaderModifierRecordDXILStep<ReturnType> step = {};
reserveDebugEntrySpace(BC, sizeof(step));
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
step.Header.Details.SizeDwords =
DebugShaderModifierRecordPayloadSizeDwords(sizeof(step));
step.Header.Details.Type = static_cast<uint8_t>(RecordType);
addDebugEntryValue(BC, BC.HlslOP->GetU32Const(step.Header.u32Header));
addDebugEntryValue(BC, values.InvocationId);
addDebugEntryValue(BC, BC.HlslOP->GetU32Const(InstNum));
if (RecordType != DebugShaderModifierRecordTypeDXILStepVoid &&
RecordType != DebugShaderModifierRecordTypeDXILStepRet) {
addDebugEntryValue(BC, V);
IRBuilder<> &B = BC.Builder;
Value *VO = BC.HlslOP->GetU32Const(ValueOrdinal << 16);
Value *VOI = B.CreateAnd(ValueOrdinalIndex, BC.HlslOP->GetU32Const(0xFFFF),
"ValueOrdinalIndex");
Value *EncodedValueOrdinalAndIndex =
BC.Builder.CreateOr(VO, VOI, "ValueOrdinal");
addDebugEntryValue(BC, EncodedValueOrdinalAndIndex);
}
}
std::optional<InstructionAndType>
DxilDebugInstrumentation::addStoreStepDebugEntry(BuilderContext *BC,
StoreInst *Inst) {
std::uint32_t ValueOrdinalBase;
std::uint32_t UnusedValueOrdinalSize;
llvm::Value *ValueOrdinalIndex;
if (!pix_dxil::PixAllocaRegWrite::FromInst(Inst, &ValueOrdinalBase,
&UnusedValueOrdinalSize,
&ValueOrdinalIndex)) {
return std::nullopt;
}
std::uint32_t InstNum;
if (!pix_dxil::PixDxilInstNum::FromInst(Inst, &InstNum)) {
return std::nullopt;
}
auto Type = addStepDebugEntryValue(BC, InstNum, Inst->getValueOperand(),
ValueOrdinalBase, ValueOrdinalIndex);
if (Type) {
if (Instruction *ValueAsInst =
dyn_cast<Instruction>(Inst->getValueOperand())) {
uint32_t RegNum = 0;
if (pix_dxil::PixDxilReg::FromInst(ValueAsInst, &RegNum)) {
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = *Type;
ret.RegisterNumber = RegNum;
ret.AllocaBase = ValueOrdinalBase;
ret.AllocaWriteIndex = ValueOrdinalIndex;
return ret;
}
} else if (Constant *ValueAsConst =
dyn_cast<Constant>(Inst->getValueOperand())) {
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = *Type;
ret.AllocaBase = ValueOrdinalBase;
ret.AllocaWriteIndex = ValueOrdinalIndex;
switch (ValueAsConst->getType()->getTypeID()) {
case Type::HalfTyID:
case Type::FloatTyID:
case Type::DoubleTyID:
ret.ConstantAllocaStoreValue = dyn_cast<ConstantFP>(ValueAsConst)
->getValueAPF()
.bitcastToAPInt()
.getLimitedValue();
break;
case Type::IntegerTyID:
ret.ConstantAllocaStoreValue =
dyn_cast<ConstantInt>(ValueAsConst)->getLimitedValue();
break;
default:
return std::nullopt;
}
return ret;
}
}
return std::nullopt;
}
std::optional<InstructionAndType> DxilDebugInstrumentation::addStepDebugEntry(
BuilderContext *BC, Instruction *Inst,
llvm::SmallPtrSetImpl<Value *> const &RayQueryHandles) {
std::uint32_t InstNum;
if (!pix_dxil::PixDxilInstNum::FromInst(Inst, &InstNum)) {
return std::nullopt;
}
if (RayQueryHandles.count(Inst) != 0) {
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = DebugShaderModifierRecordTypeDXILStepVoid;
return ret;
}
if (auto *St = llvm::dyn_cast<llvm::StoreInst>(Inst)) {
return addStoreStepDebugEntry(BC, St);
}
if (auto *Ld = llvm::dyn_cast<llvm::LoadInst>(Inst)) {
if (llvm::isa<ConstantExpr>(Ld->getPointerOperand())) {
auto *constant = llvm::cast<ConstantExpr>(Ld->getPointerOperand());
if (constant->getOpcode() == Instruction::GetElementPtr) {
PIXPassHelpers::ScopedInstruction asInstr(constant->getAsInstruction());
auto *GEP = llvm::cast<GetElementPtrInst>(asInstr.Get());
if (GEP->getPointerOperand()->getName().equals("dx.nothing.a")) {
// These debug-only loads are interesting as instructions to
// step though where otherwise no step might exist for the
// given HLSL lines, so we include them in the instrumentation:
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = DebugShaderModifierRecordTypeDXILStepVoid;
return ret;
}
}
}
}
std::uint32_t RegNum;
if (!pix_dxil::PixDxilReg::FromInst(Inst, &RegNum)) {
if (Inst->getOpcode() == Instruction::Ret) {
if (BC != nullptr)
addStepEntryForType<void>(DebugShaderModifierRecordTypeDXILStepRet, *BC,
InstNum, nullptr, 0, 0);
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = DebugShaderModifierRecordTypeDXILStepRet;
return ret;
} else if (Inst->isTerminator()) {
if (BC != nullptr)
addStepEntryForType<void>(DebugShaderModifierRecordTypeDXILStepVoid,
*BC, InstNum, nullptr, 0, 0);
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = DebugShaderModifierRecordTypeDXILStepVoid;
return ret;
}
return std::nullopt;
}
auto Type = addStepDebugEntryValue(BC, InstNum, Inst, RegNum,
BC ? BC->Builder.getInt32(0) : nullptr);
if (Type) {
InstructionAndType ret{};
ret.Inst = Inst;
ret.InstructionOrdinal = InstNum;
ret.Type = *Type;
ret.RegisterNumber = RegNum;
return ret;
}
return std::nullopt;
}
std::optional<DebugShaderModifierRecordType>
DxilDebugInstrumentation::addStepDebugEntryValue(BuilderContext *BC,
std::uint32_t InstNum,
Value *V,
std::uint32_t ValueOrdinal,
Value *ValueOrdinalIndex) {
const Type::TypeID ID = V->getType()->getTypeID();
switch (ID) {
case Type::TypeID::StructTyID:
case Type::TypeID::VoidTyID:
if (BC != nullptr)
addStepEntryForType<void>(DebugShaderModifierRecordTypeDXILStepVoid, *BC,
InstNum, V, ValueOrdinal, ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepVoid;
case Type::TypeID::FloatTyID:
if (BC != nullptr)
addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat,
*BC, InstNum, V, ValueOrdinal,
ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepFloat;
case Type::TypeID::IntegerTyID:
assert(V->getType()->getIntegerBitWidth() == 64 ||
V->getType()->getIntegerBitWidth() <= 32);
if (V->getType()->getIntegerBitWidth() > 64) {
return std::nullopt;
}
if (V->getType()->getIntegerBitWidth() == 64) {
if (BC != nullptr)
addStepEntryForType<uint64_t>(
DebugShaderModifierRecordTypeDXILStepUint64, *BC, InstNum, V,
ValueOrdinal, ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepUint64;
} else {
if (V->getType()->getIntegerBitWidth() > 32) {
return std::nullopt;
}
if (BC != nullptr)
addStepEntryForType<uint32_t>(
DebugShaderModifierRecordTypeDXILStepUint32, *BC, InstNum, V,
ValueOrdinal, ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepUint32;
}
case Type::TypeID::DoubleTyID:
if (BC != nullptr)
addStepEntryForType<double>(DebugShaderModifierRecordTypeDXILStepDouble,
*BC, InstNum, V, ValueOrdinal,
ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepDouble;
case Type::TypeID::HalfTyID:
if (BC != nullptr)
addStepEntryForType<float>(DebugShaderModifierRecordTypeDXILStepFloat,
*BC, InstNum, V, ValueOrdinal,
ValueOrdinalIndex);
return DebugShaderModifierRecordTypeDXILStepFloat;
case Type::TypeID::PointerTyID:
// Skip pointer calculation instructions. They aren't particularly
// meaningful to the user (being a mere implementation detail for lookup
// tables, etc.), and their type is problematic from a UI point of view.
// The subsequent instructions that dereference the pointer will be
// properly instrumented and show the (meaningful) retrieved value.
break;
case Type::TypeID::VectorTyID:
// Shows up in "insertelement" in raygen shader?
break;
case Type::TypeID::FP128TyID:
case Type::TypeID::LabelTyID:
case Type::TypeID::MetadataTyID:
case Type::TypeID::FunctionTyID:
case Type::TypeID::ArrayTyID:
case Type::TypeID::X86_FP80TyID:
case Type::TypeID::X86_MMXTyID:
case Type::TypeID::PPC_FP128TyID:
assert(false);
}
return std::nullopt;
}
bool DxilDebugInstrumentation::runOnModule(Module &M) {
DxilModule &DM = M.GetOrCreateDxilModule();
// There is no point running this pass if it can't return its report:
if (OSOverride == nullptr)
return false;
auto ShaderModel = DM.GetShaderModel();
auto shaderKind = ShaderModel->GetKind();
auto HLSLBindId = 0;
auto *uav = PIXPassHelpers::CreateGlobalUAVResource(DM, HLSLBindId, "PIXUAV");
bool modified = false;
if (shaderKind == DXIL::ShaderKind::Library) {
auto instrumentableFunctions =
PIXPassHelpers::GetAllInstrumentableFunctions(DM);
for (auto *F : instrumentableFunctions) {
if (RunOnFunction(M, DM, uav, F)) {
modified = true;
}
}
} else {
llvm::Function *entryFunction = PIXPassHelpers::GetEntryFunction(DM);
modified = RunOnFunction(M, DM, uav, entryFunction);
}
return modified;
}
struct RecordTypeDatum {
DebugShaderModifierRecordType Type;
uint32_t PayloadSize;
const char *AsString;
};
static const RecordTypeDatum RecordTypeData[] = {
{DebugShaderModifierRecordTypeDXILStepRet, 0, "r"},
{DebugShaderModifierRecordTypeDXILStepVoid, 0, "v"},
{DebugShaderModifierRecordTypeDXILStepFloat, 4, "f"},
{DebugShaderModifierRecordTypeDXILStepUint32, 4, "3"},
{DebugShaderModifierRecordTypeDXILStepUint64, 8, "6"},
{DebugShaderModifierRecordTypeDXILStepDouble, 8, "d"}};
std::optional<RecordTypeDatum const *>
FindDatum(DebugShaderModifierRecordType RecordType) {
for (auto const &datum : RecordTypeData) {
if (datum.Type == RecordType) {
return &datum;
}
}
return std::nullopt;
}
uint32_t DxilDebugInstrumentation::CountBlockPayloadBytes(
std::vector<InstructionToInstrument> const &IsAndTs) {
uint32_t count = 0;
for (auto const &IandT : IsAndTs) {
auto datum = FindDatum(IandT.ValueType);
if (datum)
count += (*datum)->PayloadSize;
}
return count;
}
const char *TypeString(InstructionAndType const &IandT) {
auto datum = FindDatum(IandT.Type);
if (datum)
return (*datum)->AsString;
assert(false);
return "v";
}
Instruction *FindFirstNonPhiInstruction(Instruction *I) {
while (llvm::isa<llvm::PHINode>(I))
I = I->getNextNode();
return I;
}
// This function reports a textual representation of the format
// of the debug data that will be output by the instructions
// added by this pass.
// The string has one or more lines of the exemplary form
// Block#3:5,f,22,a;7,f,22,s,20;9,f,22,s,20;10,f,23,a;12,f,23,s,21;
// The integer after the Block# is the first instruction number in the
// block.
// Instructions are delimited by ; The fields within the instruction
// (delimited by ,) are, in order:
// -instruction ordinal
// -data type (r=ret, v=void, f=float, 3=int32, 6=int64, d=double)
// -scalar register number
// -alloca/scalar indicator:
// r == ret instruction
// a == scalar is being created and assigned a value, and that
// value is in the debug output.
// s == Existing scalar is being assigned via static alloca index.
// Index is appended to this instruction record. No
// corresponding data in the debug output.
// d == A dynamic index added to the static base index. Base index
// is appended to this record. The corresponding debug entry is
// the dynamic index into that alloca.
// v == A void terminator or other void-valued instruction. No
// corresponding data in the debug output.
// If indicator is "a", a string of the form [base+index] for the alloca
// store location.
// If indicator is "d", a single integer denoting the base for the alloca
// store.
DxilDebugInstrumentation::BlockInstrumentationData
DxilDebugInstrumentation::FindInstrumentableInstructionsInBlock(
BasicBlock &BB, OP *HlslOP,
llvm::SmallPtrSetImpl<Value *> const &RayQueryHandles) {
BlockInstrumentationData ret{};
auto &Is = BB.getInstList();
*OSOverride << "Block#";
bool FoundFirstInstruction = false;
for (auto &Inst : Is) {
if (!FoundFirstInstruction) {
std::uint32_t InstNum;
if (pix_dxil::PixDxilInstNum::FromInst(&Inst, &InstNum)) {
*OSOverride << std::to_string(InstNum) << ":";
ret.FirstInstructionOrdinalInBlock = InstNum;
FoundFirstInstruction = true;
}
}
auto IandT = addStepDebugEntry(nullptr, &Inst, RayQueryHandles);
if (IandT) {
InstructionToInstrument DebugOutputForThisInstruction{};
DebugOutputForThisInstruction.ValueType = IandT->Type;
auto *InsertionPoint = FindFirstNonPhiInstruction(&Inst);
if (InsertionPoint->isTerminator() || llvm::isa<llvm::PHINode>(Inst))
DebugOutputForThisInstruction
.InstructionBeforeWhichToAddInstrumentation = InsertionPoint;
else
DebugOutputForThisInstruction
.InstructionAfterWhichToAddInstrumentation = InsertionPoint;
const char *IndexingToken = nullptr;
std::optional<std::string> RegisterOrStaticIndex;
if (IandT->Type == DebugShaderModifierRecordTypeDXILStepRet) {
IndexingToken = "r";
} else if (IandT->Type == DebugShaderModifierRecordTypeDXILStepVoid) {
IndexingToken = "v"; // void instruction, no debug output required
} else if (IandT->AllocaWriteIndex != nullptr) {
if (ConstantInt *IndexAsConstant =
dyn_cast<ConstantInt>(IandT->AllocaWriteIndex)) {
RegisterOrStaticIndex =
std::to_string(IandT->AllocaBase) + "+" +
std::to_string(IndexAsConstant->getLimitedValue());
IndexingToken = "s"; // static indexing, no debug output required
} else {
IndexingToken = "d"; // dynamic indexing
RegisterOrStaticIndex = std::to_string(IandT->AllocaBase);
DebugOutputForThisInstruction.ValueToWriteToDebugMemory =
IandT->AllocaWriteIndex;
}
} else {
IndexingToken = "a"; // meaning an SSA assignment
// todo: Can SSA Values be assigned a literal constant?
DebugOutputForThisInstruction.ValueToWriteToDebugMemory = IandT->Inst;
}
*OSOverride << std::to_string(IandT->InstructionOrdinal) << ","
<< TypeString(*IandT) << ","
<< std::to_string(IandT->RegisterNumber) << ","
<< IndexingToken;
if (RegisterOrStaticIndex) {
*OSOverride << "," << *RegisterOrStaticIndex;
}
if (IandT->ConstantAllocaStoreValue) {
*OSOverride << "," << std::to_string(*IandT->ConstantAllocaStoreValue);
}
*OSOverride << ";";
if (DebugOutputForThisInstruction.ValueToWriteToDebugMemory)
ret.Instructions.push_back(std::move(DebugOutputForThisInstruction));
}
}
*OSOverride << "\n";
return ret;
}
bool DxilDebugInstrumentation::RunOnFunction(Module &M, DxilModule &DM,
hlsl::DxilResource *uav,
llvm::Function *function) {
DXIL::ShaderKind shaderKind =
PIXPassHelpers::GetFunctionShaderKind(DM, function);
switch (shaderKind) {
case DXIL::ShaderKind::Amplification:
case DXIL::ShaderKind::Mesh:
case DXIL::ShaderKind::Vertex:
case DXIL::ShaderKind::Geometry:
case DXIL::ShaderKind::Pixel:
case DXIL::ShaderKind::Compute:
case DXIL::ShaderKind::RayGeneration:
case DXIL::ShaderKind::Hull:
case DXIL::ShaderKind::Domain:
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Miss:
case DXIL::ShaderKind::Node:
break;
default:
return false;
}
llvm::SmallPtrSet<Value *, 16> RayQueryHandles;
PIXPassHelpers::FindRayQueryHandlesForFunction(function, RayQueryHandles);
Instruction *firstInsertionPt = dxilutil::FirstNonAllocaInsertionPt(function);
IRBuilder<> Builder(firstInsertionPt);
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
BuilderContext BC{M, DM, Ctx, HlslOP, Builder};
auto &values = m_FunctionToValues[BC.Builder.GetInsertBlock()->getParent()];
// PIX binds two UAVs when running this instrumentation: one for raygen
// shaders and another for the hitgroups and miss shaders. Since PIX invokes
// this pass at the library level, which may contain examples of both types,
// PIX can't really specify which UAV index to use per-shader. This pass
// therefore just has to know this:
constexpr unsigned int RayGenUAVRegister = 0;
constexpr unsigned int HitGroupAndMissUAVRegister = 1;
unsigned int UAVRegisterId = RayGenUAVRegister;
switch (shaderKind) {
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::Miss:
UAVRegisterId = HitGroupAndMissUAVRegister;
break;
}
values.UAVHandle = PIXPassHelpers::CreateHandleForResource(
DM, Builder, uav, "PIX_DebugUAV_Handle");
auto SystemValues = addRequiredSystemValues(BC, shaderKind);
addInvocationSelectionProlog(BC, SystemValues, shaderKind);
determineLimitANDAndInitializeCounter(BC);
addInvocationStartMarker(BC);
// Instrument original instructions:
for (auto &BB : function->getBasicBlockList()) {
if (std::find(values.AddedBlocksToIgnoreForInstrumentation.begin(),
values.AddedBlocksToIgnoreForInstrumentation.end(),
&BB) == values.AddedBlocksToIgnoreForInstrumentation.end()) {
auto BlockInstrumentation =
FindInstrumentableInstructionsInBlock(BB, BC.HlslOP, RayQueryHandles);
if (BlockInstrumentation.FirstInstructionOrdinalInBlock <
m_FirstInstruction ||
BlockInstrumentation.FirstInstructionOrdinalInBlock >=
m_LastInstruction)
continue;
uint32_t BlockPayloadBytes =
CountBlockPayloadBytes(BlockInstrumentation.Instructions);
// If the block has no instructions which require debug output,
// we will still write an empty block header at the end of that
// block (i.e. before the terminator) so that the instrumentation
// at least indicates that flow control went through the block.
Instruction *BlockInstrumentationStart = (BB).getTerminator();
if (!BlockInstrumentation.Instructions.empty()) {
auto const &First = BlockInstrumentation.Instructions[0];
if (First.InstructionAfterWhichToAddInstrumentation != nullptr)
BlockInstrumentationStart =
First.InstructionAfterWhichToAddInstrumentation;
else if (First.InstructionBeforeWhichToAddInstrumentation != nullptr)
BlockInstrumentationStart =
First.InstructionBeforeWhichToAddInstrumentation;
else {
assert(false);
continue;
}
}
IRBuilder<> Builder(BlockInstrumentationStart);
BuilderContext BCForBlock{BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder};
DebugShaderModifierRecordDXILBlock step = {};
auto FullRecordSize =
static_cast<uint32_t>(sizeof(step) + BlockPayloadBytes);
if (FullRecordSize >= (m_UAVSize / 4) - 1) {
*OSOverride << "StaticOverflow:" << std::to_string(FullRecordSize)
<< "\n";
break;
}
reserveDebugEntrySpace(BCForBlock, FullRecordSize);
step.Header.Details.CountOfInstructions =
static_cast<uint16_t>(BlockInstrumentation.Instructions.size());
step.Header.Details.Type =
static_cast<uint8_t>(DebugShaderModifierRecordTypeDXILStepBlock);
addDebugEntryValue(BCForBlock,
BCForBlock.HlslOP->GetU32Const(step.Header.u32Header));
addDebugEntryValue(BCForBlock, values.InvocationId);
addDebugEntryValue(
BCForBlock, BCForBlock.HlslOP->GetU32Const(
BlockInstrumentation.FirstInstructionOrdinalInBlock));
for (auto &Inst : BlockInstrumentation.Instructions) {
Instruction *BuilderInstruction;
if (Inst.InstructionAfterWhichToAddInstrumentation != nullptr)
BuilderInstruction =
Inst.InstructionAfterWhichToAddInstrumentation->getNextNode();
else if (Inst.InstructionBeforeWhichToAddInstrumentation != nullptr)
BuilderInstruction = Inst.InstructionBeforeWhichToAddInstrumentation;
else {
assert(false);
continue;
}
IRBuilder<> Builder(BuilderInstruction);
BuilderContext BC2{BC.M, BC.DM, BC.Ctx, BC.HlslOP, Builder};
addDebugEntryValue(BC2, Inst.ValueToWriteToDebugMemory);
}
}
}
return true;
}
char DxilDebugInstrumentation::ID = 0;
ModulePass *llvm::createDxilDebugInstrumentationPass() {
return new DxilDebugInstrumentation();
}
INITIALIZE_PASS(DxilDebugInstrumentation, "hlsl-dxil-debug-instrumentation",
"HLSL DXIL debug instrumentation for PIX", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilOutputColorBecomesConstant.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilOutputColorBecomesConstant.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to stomp a pixel shader's output color to a given //
// constant value //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Transforms/Utils/Local.h"
#include <array>
#include "PixPassHelpers.h"
using namespace llvm;
using namespace hlsl;
class DxilOutputColorBecomesConstant : public ModulePass {
enum VisualizerInstrumentationMode {
FromLiteralConstant,
FromConstantBuffer
};
float Red = 1.f;
float Green = 1.f;
float Blue = 1.f;
float Alpha = 1.f;
VisualizerInstrumentationMode Mode = FromLiteralConstant;
void visitOutputInstructionCallers(Function *OutputFunction,
const hlsl::DxilSignature &OutputSignature,
OP *HlslOP,
std::function<void(CallInst *)> Visitor);
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilOutputColorBecomesConstant() : ModulePass(ID) {}
StringRef getPassName() const override { return "DXIL Constant Color Mod"; }
void applyOptions(PassOptions O) override;
bool runOnModule(Module &M) override;
};
void DxilOutputColorBecomesConstant::applyOptions(PassOptions O) {
GetPassOptionFloat(O, "constant-red", &Red, 1.f);
GetPassOptionFloat(O, "constant-green", &Green, 1.f);
GetPassOptionFloat(O, "constant-blue", &Blue, 1.f);
GetPassOptionFloat(O, "constant-alpha", &Alpha, 1.f);
int mode = 0;
GetPassOptionInt(O, "mod-mode", &mode, 0);
Mode = static_cast<VisualizerInstrumentationMode>(mode);
}
void DxilOutputColorBecomesConstant::visitOutputInstructionCallers(
Function *OutputFunction, const hlsl::DxilSignature &OutputSignature,
OP *HlslOP, std::function<void(CallInst *)> Visitor) {
auto OutputFunctionUses = OutputFunction->uses();
for (Use &FunctionUse : OutputFunctionUses) {
iterator_range<Value::user_iterator> FunctionUsers = FunctionUse->users();
for (User *FunctionUser : FunctionUsers) {
if (isa<Instruction>(FunctionUser)) {
auto CallInstruction = cast<CallInst>(FunctionUser);
// Check if the instruction writes to a render target (as opposed to a
// system-value, such as RenderTargetArrayIndex)
Value *OutputID = CallInstruction->getArgOperand(
DXIL::OperandIndex::kStoreOutputIDOpIdx);
unsigned SignatureElementIndex =
cast<ConstantInt>(OutputID)->getLimitedValue();
const DxilSignatureElement &SignatureElement =
OutputSignature.GetElement(SignatureElementIndex);
// We only modify the output color for RTV0
if (SignatureElement.GetSemantic()->GetKind() ==
DXIL::SemanticKind::Target &&
SignatureElement.GetSemanticStartIndex() == 0) {
// Replace the source operand with the appropriate constant value
Visitor(CallInstruction);
}
}
}
}
}
bool DxilOutputColorBecomesConstant::runOnModule(Module &M) {
// This pass finds all users of the "StoreOutput" function, and replaces their
// source operands with a constant value.
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
const hlsl::DxilSignature &OutputSignature = DM.GetOutputSignature();
Function *FloatOutputFunction =
HlslOP->GetOpFunc(DXIL::OpCode::StoreOutput, Type::getFloatTy(Ctx));
Function *IntOutputFunction =
HlslOP->GetOpFunc(DXIL::OpCode::StoreOutput, Type::getInt32Ty(Ctx));
bool hasFloatOutputs = false;
bool hasIntOutputs = false;
visitOutputInstructionCallers(
FloatOutputFunction, OutputSignature, HlslOP,
[&hasFloatOutputs](CallInst *) { hasFloatOutputs = true; });
visitOutputInstructionCallers(
IntOutputFunction, OutputSignature, HlslOP,
[&hasIntOutputs](CallInst *) { hasIntOutputs = true; });
if (!hasFloatOutputs && !hasIntOutputs) {
return false;
}
// Otherwise, we assume the shader outputs only one or the other (because the
// 0th RTV can't have a mixed type)
DXASSERT(!hasFloatOutputs || !hasIntOutputs,
"Only one or the other type of output: float or int");
std::array<llvm::Value *, 4> ReplacementColors;
switch (Mode) {
case FromLiteralConstant: {
if (hasFloatOutputs) {
ReplacementColors[0] = HlslOP->GetFloatConst(Red);
ReplacementColors[1] = HlslOP->GetFloatConst(Green);
ReplacementColors[2] = HlslOP->GetFloatConst(Blue);
ReplacementColors[3] = HlslOP->GetFloatConst(Alpha);
}
if (hasIntOutputs) {
ReplacementColors[0] = HlslOP->GetI32Const(static_cast<int>(Red));
ReplacementColors[1] = HlslOP->GetI32Const(static_cast<int>(Green));
ReplacementColors[2] = HlslOP->GetI32Const(static_cast<int>(Blue));
ReplacementColors[3] = HlslOP->GetI32Const(static_cast<int>(Alpha));
}
} break;
case FromConstantBuffer: {
// Setup a constant buffer with a single float4 in it:
SmallVector<llvm::Type *, 4> Elements{
Type::getFloatTy(Ctx), Type::getFloatTy(Ctx), Type::getFloatTy(Ctx),
Type::getFloatTy(Ctx)};
llvm::StructType *CBStructTy =
llvm::StructType::create(Elements, "PIX_ConstantColorCB_Type");
std::unique_ptr<DxilCBuffer> pCBuf = llvm::make_unique<DxilCBuffer>();
pCBuf->SetGlobalName("PIX_ConstantColorCBName");
pCBuf->SetGlobalSymbol(UndefValue::get(CBStructTy));
pCBuf->SetID(static_cast<unsigned int>(DM.GetCBuffers().size()));
pCBuf->SetSpaceID(
(unsigned int)-2); // This is the reserved-for-tools register space
pCBuf->SetLowerBound(0);
pCBuf->SetRangeSize(1);
pCBuf->SetSize(4);
Instruction *entryPointInstruction =
&*(PIXPassHelpers::GetEntryFunction(DM)->begin()->begin());
IRBuilder<> Builder(entryPointInstruction);
// Create handle for the newly-added constant buffer (which is achieved via
// a function call)
auto ConstantBufferName = "PIX_Constant_Color_CB_Handle";
CallInst *callCreateHandle = PIXPassHelpers::CreateHandleForResource(
DM, Builder, pCBuf.get(), ConstantBufferName);
DM.AddCBuffer(std::move(pCBuf));
DM.ReEmitDxilResources();
#define PIX_CONSTANT_VALUE "PIX_Constant_Color_Value"
// Insert the Buffer load instruction:
Function *CBLoad = HlslOP->GetOpFunc(
OP::OpCode::CBufferLoadLegacy,
hasFloatOutputs ? Type::getFloatTy(Ctx) : Type::getInt32Ty(Ctx));
Constant *OpArg =
HlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
Value *ResourceHandle = callCreateHandle;
Constant *RowIndex = HlslOP->GetU32Const(0);
CallInst *loadLegacy = Builder.CreateCall(
CBLoad, {OpArg, ResourceHandle, RowIndex}, PIX_CONSTANT_VALUE);
// Now extract four color values:
ReplacementColors[0] =
Builder.CreateExtractValue(loadLegacy, 0, PIX_CONSTANT_VALUE "0");
ReplacementColors[1] =
Builder.CreateExtractValue(loadLegacy, 1, PIX_CONSTANT_VALUE "1");
ReplacementColors[2] =
Builder.CreateExtractValue(loadLegacy, 2, PIX_CONSTANT_VALUE "2");
ReplacementColors[3] =
Builder.CreateExtractValue(loadLegacy, 3, PIX_CONSTANT_VALUE "3");
} break;
default:
assert(false);
return 0;
}
bool Modified = false;
// The StoreOutput function can store either a float or an integer, depending
// on the intended output render-target resource view.
if (hasFloatOutputs) {
visitOutputInstructionCallers(
FloatOutputFunction, OutputSignature, HlslOP,
[&ReplacementColors, &Modified](CallInst *CallInstruction) {
Modified = true;
// The output column is the channel (red, green, blue or alpha) within
// the output pixel
Value *OutputColumnOperand = CallInstruction->getOperand(
hlsl::DXIL::OperandIndex::kStoreOutputColOpIdx);
ConstantInt *OutputColumnConstant =
cast<ConstantInt>(OutputColumnOperand);
APInt OutputColumn = OutputColumnConstant->getValue();
CallInstruction->setOperand(
hlsl::DXIL::OperandIndex::kStoreOutputValOpIdx,
ReplacementColors[*OutputColumn.getRawData()]);
});
}
if (hasIntOutputs) {
visitOutputInstructionCallers(
IntOutputFunction, OutputSignature, HlslOP,
[&ReplacementColors, &Modified](CallInst *CallInstruction) {
Modified = true;
// The output column is the channel (red, green, blue or alpha) within
// the output pixel
Value *OutputColumnOperand = CallInstruction->getOperand(
hlsl::DXIL::OperandIndex::kStoreOutputColOpIdx);
ConstantInt *OutputColumnConstant =
cast<ConstantInt>(OutputColumnOperand);
APInt OutputColumn = OutputColumnConstant->getValue();
CallInstruction->setOperand(
hlsl::DXIL::OperandIndex::kStoreOutputValOpIdx,
ReplacementColors[*OutputColumn.getRawData()]);
});
}
return Modified;
}
char DxilOutputColorBecomesConstant::ID = 0;
ModulePass *llvm::createDxilOutputColorBecomesConstantPass() {
return new DxilOutputColorBecomesConstant();
}
INITIALIZE_PASS(DxilOutputColorBecomesConstant, "hlsl-dxil-constantColor",
"DXIL Constant Color Mod", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/PixPassHelpers.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// PixPassHelpers.cpp
// // Copyright (C) Microsoft Corporation. All rights reserved. // This file is
// distributed under the University of Illinois Open Source // License. See
// LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResourceBinding.h"
#include "dxc/DXIL/DxilResourceProperties.h"
#include "dxc/DxilRootSignature/DxilRootSignature.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
#include "PixPassHelpers.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#ifdef PIX_DEBUG_DUMP_HELPER
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include <iostream>
#endif
using namespace llvm;
using namespace hlsl;
namespace PIXPassHelpers {
static void FindRayQueryHandlesFromUse(Value *U,
SmallPtrSetImpl<Value *> &Handles) {
if (Handles.insert(U).second) {
auto RayQueryHandleUses = U->uses();
for (Use &Use : RayQueryHandleUses) {
iterator_range<Value::user_iterator> Users = Use->users();
for (User *User : Users) {
if (isa<PHINode>(User) || isa<SelectInst>(User))
FindRayQueryHandlesFromUse(User, Handles);
}
}
}
}
void FindRayQueryHandlesForFunction(llvm::Function *F,
SmallPtrSetImpl<Value *> &RayQueryHandles) {
auto &blocks = F->getBasicBlockList();
if (!blocks.empty()) {
for (auto &block : blocks) {
for (auto &instruction : block) {
if (hlsl::OP::IsDxilOpFuncCallInst(
&instruction, hlsl::OP::OpCode::AllocateRayQuery)) {
FindRayQueryHandlesFromUse(&instruction, RayQueryHandles);
}
}
}
}
}
static bool IsDynamicResourceShaderModel(DxilModule &DM) {
return DM.GetShaderModel()->IsSMAtLeast(6, 6);
}
static bool ShaderModelRequiresAnnotateHandle(DxilModule &DM) {
return DM.GetShaderModel()->IsSMAtLeast(6, 6);
}
static char const *RawUAVType() { return "struct.RWByteAddressBuffer"; }
static char const *ShaderModelHandleTypeName(DxilModule &DM) {
// Prior to sm6.6, lib handles were typed after the resource they denote.
// In 6.6 and after, and in all non-lib shader models,
// all handles are dx.types.Handle.
if (!DM.GetShaderModel()->IsLib() || DM.GetShaderModel()->IsSM66Plus())
return "dx.types.Handle";
return RawUAVType();
}
llvm::CallInst *CreateHandleForResource(hlsl::DxilModule &DM,
llvm::IRBuilder<> &Builder,
hlsl::DxilResourceBase *resource,
const char *name) {
OP *HlslOP = DM.GetOP();
LLVMContext &Ctx = DM.GetModule()->getContext();
DXIL::ResourceClass resourceClass = resource->GetClass();
auto const *shaderModel = DM.GetShaderModel();
Type *resourceHandleType =
DM.GetModule()->getTypeByName(ShaderModelHandleTypeName(DM));
if (shaderModel->IsLib()) {
llvm::Constant *object = resource->GetGlobalSymbol();
Value *load = Builder.CreateLoad(object, resourceHandleType);
llvm::cast<LoadInst>(load)->setAlignment(4);
llvm::cast<LoadInst>(load)->setVolatile(false);
Function *CreateHandleForLibOpFunc =
HlslOP->GetOpFunc(DXIL::OpCode::CreateHandleForLib, load->getType());
Constant *CreateHandleForLibOpcodeArg =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandleForLib);
auto *handle = Builder.CreateCall(CreateHandleForLibOpFunc,
{CreateHandleForLibOpcodeArg, load});
if (ShaderModelRequiresAnnotateHandle(DM)) {
Function *annotHandleFn =
HlslOP->GetOpFunc(DXIL::OpCode::AnnotateHandle, Type::getVoidTy(Ctx));
Value *annotHandleArg =
HlslOP->GetI32Const((unsigned)DXIL::OpCode::AnnotateHandle);
DxilResourceProperties RP =
resource_helper::loadPropsFromResourceBase(resource);
Type *resPropertyTy = HlslOP->GetResourcePropertiesType();
Value *propertiesV = resource_helper::getAsConstant(RP, resPropertyTy,
*DM.GetShaderModel());
return Builder.CreateCall(annotHandleFn,
{annotHandleArg, handle, propertiesV});
} else {
return handle;
}
} else if (IsDynamicResourceShaderModel(DM)) {
Function *CreateHandleFromBindingOpFunc = HlslOP->GetOpFunc(
DXIL::OpCode::CreateHandleFromBinding, Type::getVoidTy(Ctx));
Constant *CreateHandleFromBindingOpcodeArg =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandleFromBinding);
DxilResourceBinding binding =
resource_helper::loadBindingFromResourceBase(resource);
Value *bindingV = resource_helper::getAsConstant(
binding, HlslOP->GetResourceBindingType(), *DM.GetShaderModel());
Value *registerIndex = HlslOP->GetU32Const(0);
Value *isUniformRes = HlslOP->GetI1Const(0);
Value *createHandleFromBindingArgs[] = {CreateHandleFromBindingOpcodeArg,
bindingV, registerIndex,
isUniformRes};
auto *handle = Builder.CreateCall(CreateHandleFromBindingOpFunc,
createHandleFromBindingArgs, name);
Function *annotHandleFn =
HlslOP->GetOpFunc(DXIL::OpCode::AnnotateHandle, Type::getVoidTy(Ctx));
Value *annotHandleArg =
HlslOP->GetI32Const((unsigned)DXIL::OpCode::AnnotateHandle);
DxilResourceProperties RP =
resource_helper::loadPropsFromResourceBase(resource);
Type *resPropertyTy = HlslOP->GetResourcePropertiesType();
Value *propertiesV =
resource_helper::getAsConstant(RP, resPropertyTy, *DM.GetShaderModel());
return Builder.CreateCall(annotHandleFn,
{annotHandleArg, handle, propertiesV});
} else {
Function *CreateHandleOpFunc =
HlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(Ctx));
Constant *CreateHandleOpcodeArg =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandle);
Constant *ClassArg = HlslOP->GetI8Const(
static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
resourceClass));
Constant *MetaDataArg = HlslOP->GetU32Const(resource->GetID());
Constant *IndexArg = HlslOP->GetU32Const(0);
Constant *FalseArg =
HlslOP->GetI1Const(0); // non-uniform resource index: false
return Builder.CreateCall(
CreateHandleOpFunc,
{CreateHandleOpcodeArg, ClassArg, MetaDataArg, IndexArg, FalseArg},
name);
}
}
static std::vector<uint8_t> SerializeRootSignatureToVector(
DxilVersionedRootSignatureDesc const *rootSignature) {
CComPtr<IDxcBlob> serializedRootSignature;
CComPtr<IDxcBlobEncoding> errorBlob;
constexpr bool allowReservedRegisterSpace = true;
SerializeRootSignature(rootSignature, &serializedRootSignature, &errorBlob,
allowReservedRegisterSpace);
std::vector<uint8_t> ret;
auto const *serializedData = reinterpret_cast<const uint8_t *>(
serializedRootSignature->GetBufferPointer());
ret.assign(serializedData,
serializedData + serializedRootSignature->GetBufferSize());
return ret;
}
constexpr uint32_t toolsRegisterSpace = static_cast<uint32_t>(-2);
constexpr uint32_t toolsUAVRegister = 0;
template <typename RootSigDesc, typename RootParameterDesc>
void ExtendRootSig(RootSigDesc &rootSigDesc) {
auto *existingParams = rootSigDesc.pParameters;
auto *newParams = new RootParameterDesc[rootSigDesc.NumParameters + 1];
if (existingParams != nullptr) {
memcpy(newParams, existingParams,
rootSigDesc.NumParameters * sizeof(RootParameterDesc));
delete[] existingParams;
}
rootSigDesc.pParameters = newParams;
rootSigDesc.pParameters[rootSigDesc.NumParameters].ParameterType =
DxilRootParameterType::UAV;
rootSigDesc.pParameters[rootSigDesc.NumParameters].Descriptor.RegisterSpace =
toolsRegisterSpace;
rootSigDesc.pParameters[rootSigDesc.NumParameters].Descriptor.ShaderRegister =
toolsUAVRegister;
rootSigDesc.pParameters[rootSigDesc.NumParameters].ShaderVisibility =
DxilShaderVisibility::All;
rootSigDesc.NumParameters++;
}
static std::vector<uint8_t> AddUAVParamterToRootSignature(const void *Data,
uint32_t Size) {
DxilVersionedRootSignature rootSignature;
DeserializeRootSignature(Data, Size, rootSignature.get_address_of());
auto *rs = rootSignature.get_mutable();
switch (rootSignature->Version) {
case DxilRootSignatureVersion::Version_1_0:
ExtendRootSig<DxilRootSignatureDesc, DxilRootParameter>(rs->Desc_1_0);
break;
case DxilRootSignatureVersion::Version_1_1:
ExtendRootSig<DxilRootSignatureDesc1, DxilRootParameter1>(rs->Desc_1_1);
rs->Desc_1_1.pParameters[rs->Desc_1_1.NumParameters - 1].Descriptor.Flags =
hlsl::DxilRootDescriptorFlags::None;
break;
}
return SerializeRootSignatureToVector(rs);
}
static void AddUAVToShaderAttributeRootSignature(DxilModule &DM) {
auto rs = DM.GetSerializedRootSignature();
if (!rs.empty()) {
std::vector<uint8_t> asVector = AddUAVParamterToRootSignature(
rs.data(), static_cast<uint32_t>(rs.size()));
DM.ResetSerializedRootSignature(asVector);
}
}
static void AddUAVToDxilDefinedGlobalRootSignatures(DxilModule &DM) {
auto *subObjects = DM.GetSubobjects();
if (subObjects != nullptr) {
for (auto const &subObject : subObjects->GetSubobjects()) {
if (subObject.second->GetKind() ==
DXIL::SubobjectKind::GlobalRootSignature) {
const void *Data = nullptr;
uint32_t Size = 0;
constexpr bool notALocalRS = false;
if (subObject.second->GetRootSignature(notALocalRS, Data, Size,
nullptr)) {
auto extendedRootSig = AddUAVParamterToRootSignature(Data, Size);
auto rootSignatureSubObjectName = subObject.first;
subObjects->RemoveSubobject(rootSignatureSubObjectName);
subObjects->CreateRootSignature(
rootSignatureSubObjectName, notALocalRS, extendedRootSig.data(),
static_cast<uint32_t>(extendedRootSig.size()));
break;
}
}
}
}
}
// Set up a UAV with structure of a single int
hlsl::DxilResource *CreateGlobalUAVResource(hlsl::DxilModule &DM,
unsigned int hlslBindIndex,
const char *name) {
LLVMContext &Ctx = DM.GetModule()->getContext();
const char *PIXStructTypeName = ShaderModelHandleTypeName(DM);
llvm::StructType *UAVStructTy =
DM.GetModule()->getTypeByName(PIXStructTypeName);
if (UAVStructTy == nullptr) {
SmallVector<llvm::Type *, 1> Elements{Type::getInt32Ty(Ctx)};
UAVStructTy = llvm::StructType::create(Elements, PIXStructTypeName);
}
// Since this function should only be called once per module,
// we can modify the root sig at the same time:
AddUAVToDxilDefinedGlobalRootSignatures(DM);
AddUAVToShaderAttributeRootSignature(DM);
unsigned int Id = static_cast<unsigned int>(DM.GetUAVs().size());
std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
pUAV->SetID(Id);
auto const *shaderModel = DM.GetShaderModel();
std::string PixUavName = "PIXUAV" + std::to_string(hlslBindIndex);
if (shaderModel->IsLib()) {
auto *Global =
DM.GetModule()->getOrInsertGlobal(PixUavName.c_str(), UAVStructTy);
GlobalVariable *NewGV = cast<GlobalVariable>(Global);
NewGV->setConstant(true);
NewGV->setLinkage(GlobalValue::ExternalLinkage);
NewGV->setThreadLocal(false);
NewGV->setAlignment(4);
pUAV->SetGlobalSymbol(NewGV);
} else {
pUAV->SetGlobalSymbol(UndefValue::get(UAVStructTy->getPointerTo()));
}
pUAV->SetGlobalName(name);
pUAV->SetRW(true); // sets UAV class
pUAV->SetSpaceID(
(unsigned int)-2); // This is the reserved-for-tools register space
pUAV->SetSampleCount(0); // This is what compiler generates for a raw UAV
pUAV->SetGloballyCoherent(false);
pUAV->SetHasCounter(false);
pUAV->SetCompType(
CompType::getInvalid()); // This is what compiler generates for a raw UAV
pUAV->SetLowerBound(hlslBindIndex);
pUAV->SetRangeSize(1);
pUAV->SetElementStride(1);
pUAV->SetKind(DXIL::ResourceKind::RawBuffer);
auto HLSLType = DM.GetModule()->getTypeByName(RawUAVType());
if (HLSLType == nullptr) {
SmallVector<llvm::Type *, 1> Elements{Type::getInt32Ty(Ctx)};
HLSLType = llvm::StructType::create(Elements, RawUAVType());
}
pUAV->SetHLSLType(HLSLType->getPointerTo());
auto pAnnotation = DM.GetTypeSystem().GetStructAnnotation(UAVStructTy);
if (pAnnotation == nullptr) {
pAnnotation = DM.GetTypeSystem().AddStructAnnotation(UAVStructTy);
pAnnotation->GetFieldAnnotation(0).SetCBufferOffset(0);
pAnnotation->GetFieldAnnotation(0).SetCompType(
hlsl::DXIL::ComponentType::I32);
pAnnotation->GetFieldAnnotation(0).SetFieldName("count");
}
auto *ret = pUAV.get();
DM.AddUAV(std::move(pUAV));
return ret;
}
// Set up a UAV with structure of a single int
llvm::CallInst *CreateUAVOnceForModule(hlsl::DxilModule &DM,
llvm::IRBuilder<> &Builder,
unsigned int hlslBindIndex,
const char *name) {
auto uav = CreateGlobalUAVResource(DM, hlslBindIndex, name);
auto *handle = CreateHandleForResource(DM, Builder, uav, name);
return handle;
}
llvm::Function *GetEntryFunction(hlsl::DxilModule &DM) {
if (DM.GetEntryFunction() != nullptr) {
return DM.GetEntryFunction();
}
return DM.GetPatchConstantFunction();
}
std::vector<llvm::Function *>
GetAllInstrumentableFunctions(hlsl::DxilModule &DM) {
std::vector<llvm::Function *> ret;
for (llvm::Function &F : DM.GetModule()->functions()) {
if (F.isDeclaration() || F.isIntrinsic() || hlsl::OP::IsDxilOpFunc(&F))
continue;
if (F.getBasicBlockList().empty())
continue;
ret.push_back(&F);
}
return ret;
}
hlsl::DXIL::ShaderKind GetFunctionShaderKind(hlsl::DxilModule &DM,
llvm::Function *fn) {
hlsl::DXIL::ShaderKind shaderKind = hlsl::DXIL::ShaderKind::Invalid;
if (!DM.HasDxilFunctionProps(fn)) {
auto ShaderModel = DM.GetShaderModel();
shaderKind = ShaderModel->GetKind();
} else {
hlsl::DxilFunctionProps const &props = DM.GetDxilFunctionProps(fn);
shaderKind = props.shaderKind;
}
return shaderKind;
}
std::vector<llvm::BasicBlock *> GetAllBlocks(hlsl::DxilModule &DM) {
std::vector<llvm::BasicBlock *> ret;
auto entryPoints = DM.GetExportedFunctions();
for (auto &fn : entryPoints) {
auto &blocks = fn->getBasicBlockList();
for (auto &block : blocks) {
ret.push_back(&block);
}
}
return ret;
}
ExpandedStruct ExpandStructType(LLVMContext &Ctx,
Type *OriginalPayloadStructType) {
SmallVector<Type *, 16> Elements;
for (unsigned int i = 0;
i < OriginalPayloadStructType->getStructNumElements(); ++i) {
Elements.push_back(OriginalPayloadStructType->getStructElementType(i));
}
Elements.push_back(Type::getInt32Ty(Ctx));
Elements.push_back(Type::getInt32Ty(Ctx));
Elements.push_back(Type::getInt32Ty(Ctx));
ExpandedStruct ret;
ret.ExpandedPayloadStructType =
StructType::create(Ctx, Elements, "PIX_AS2MS_Expanded_Type");
ret.ExpandedPayloadStructPtrType =
ret.ExpandedPayloadStructType->getPointerTo();
return ret;
}
void ReplaceAllUsesOfInstructionWithNewValueAndDeleteInstruction(
Instruction *Instr, Value *newValue, Type *newType) {
std::vector<Value *> users;
for (auto u = Instr->user_begin(); u != Instr->user_end(); ++u) {
users.push_back(*u);
}
for (auto user : users) {
if (auto *instruction = llvm::cast<Instruction>(user)) {
for (unsigned int i = 0; i < instruction->getNumOperands(); ++i) {
auto *Operand = instruction->getOperand(i);
if (Operand == Instr) {
instruction->setOperand(i, newValue);
}
}
if (llvm::isa<GetElementPtrInst>(instruction)) {
auto *GEP = llvm::cast<GetElementPtrInst>(instruction);
GEP->setSourceElementType(newType);
} else if (hlsl::OP::IsDxilOpFuncCallInst(
instruction, hlsl::OP::OpCode::DispatchMesh)) {
DxilModule &DM = instruction->getModule()->GetOrCreateDxilModule();
OP *HlslOP = DM.GetOP();
DxilInst_DispatchMesh DispatchMesh(instruction);
IRBuilder<> B(instruction);
SmallVector<Value *, 5> args;
args.push_back(
HlslOP->GetU32Const((unsigned)hlsl::OP::OpCode::DispatchMesh));
args.push_back(DispatchMesh.get_threadGroupCountX());
args.push_back(DispatchMesh.get_threadGroupCountY());
args.push_back(DispatchMesh.get_threadGroupCountZ());
args.push_back(newValue);
B.CreateCall(HlslOP->GetOpFunc(DXIL::OpCode::DispatchMesh,
newType->getPointerTo()),
args);
instruction->removeFromParent();
delete instruction;
}
}
}
Instr->removeFromParent();
delete Instr;
}
unsigned int FindOrAddSV_Position(hlsl::DxilModule &DM,
unsigned UpStreamSVPosRow) {
hlsl::DxilSignature &InputSignature = DM.GetInputSignature();
auto &InputElements = InputSignature.GetElements();
auto Existing_SV_Position =
std::find_if(InputElements.begin(), InputElements.end(),
[](const std::unique_ptr<DxilSignatureElement> &Element) {
return Element->GetSemantic()->GetKind() ==
hlsl::DXIL::SemanticKind::Position;
});
// SV_Position, if present, has to have full mask, so we needn't worry
// about the shader having selected components that don't include x or y.
// If not present, we add it.
if (Existing_SV_Position == InputElements.end()) {
unsigned int StartColumn = 0;
unsigned int RowCount = 1;
unsigned int ColumnCount = 4;
auto Added_SV_Position =
llvm::make_unique<DxilSignatureElement>(DXIL::SigPointKind::PSIn);
Added_SV_Position->Initialize("Position", hlsl::CompType::getF32(),
hlsl::DXIL::InterpolationMode::Linear,
RowCount, ColumnCount, UpStreamSVPosRow,
StartColumn);
Added_SV_Position->AppendSemanticIndex(0);
Added_SV_Position->SetKind(hlsl::DXIL::SemanticKind::Position);
// AppendElement sets the element's ID by default
auto index = InputSignature.AppendElement(std::move(Added_SV_Position));
return InputElements[index]->GetID();
} else {
return Existing_SV_Position->get()->GetID();
}
}
#ifdef PIX_DEBUG_DUMP_HELPER
static int g_logIndent = 0;
void IncreaseLogIndent() { g_logIndent++; }
void DecreaseLogIndent() { --g_logIndent; }
void Log(const char *format, ...) {
va_list argumentPointer;
va_start(argumentPointer, format);
char buffer[512];
vsnprintf(buffer, _countof(buffer), format, argumentPointer);
va_end(argumentPointer);
for (int i = 0; i < g_logIndent; ++i) {
OutputDebugFormatA(" ");
}
OutputDebugFormatA(buffer);
OutputDebugFormatA("\n");
}
void LogPartialLine(const char *format, ...) {
va_list argumentPointer;
va_start(argumentPointer, format);
char buffer[512];
vsnprintf(buffer, _countof(buffer), format, argumentPointer);
va_end(argumentPointer);
for (int i = 0; i < g_logIndent; ++i) {
OutputDebugFormatA(" ");
}
OutputDebugFormatA(buffer);
}
static llvm::DIType const *DITypePeelTypeAlias(llvm::DIType const *Ty) {
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
const llvm::DITypeIdentifierMap EmptyMap;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_member:
return DITypePeelTypeAlias(DerivedTy->getBaseType().resolve(EmptyMap));
}
}
return Ty;
}
void DumpArrayType(llvm::DICompositeType const *Ty);
void DumpStructType(llvm::DICompositeType const *Ty);
void DumpFullType(llvm::DIType const *type) {
auto *Ty = DITypePeelTypeAlias(type);
const llvm::DITypeIdentifierMap EmptyMap;
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
switch (DerivedTy->getTag()) {
default:
assert(!"Unhandled DIDerivedType");
std::abort();
return;
case llvm::dwarf::DW_TAG_arg_variable: // "this" pointer
case llvm::dwarf::DW_TAG_pointer_type: // "this" pointer
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_inheritance:
DumpFullType(DerivedTy->getBaseType().resolve(EmptyMap));
return;
case llvm::dwarf::DW_TAG_member: {
Log("Member variable");
ScopedIndenter indent;
DumpFullType(DerivedTy->getBaseType().resolve(EmptyMap));
}
return;
case llvm::dwarf::DW_TAG_subroutine_type:
std::abort();
return;
}
} else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty)) {
switch (CompositeTy->getTag()) {
default:
assert(!"Unhandled DICompositeType");
std::abort();
return;
case llvm::dwarf::DW_TAG_array_type:
DumpArrayType(CompositeTy);
return;
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
DumpStructType(CompositeTy);
return;
case llvm::dwarf::DW_TAG_enumeration_type:
// enum base type is int:
std::abort();
return;
}
} else if (auto *BasicTy = llvm::dyn_cast<llvm::DIBasicType>(Ty)) {
Log("%d: %s", BasicTy->getOffsetInBits(), BasicTy->getName().str().c_str());
return;
} else {
std::abort();
}
}
static unsigned NumArrayElements(llvm::DICompositeType const *Array) {
if (Array->getElements().size() == 0) {
return 0;
}
unsigned NumElements = 1;
for (llvm::DINode *N : Array->getElements()) {
if (auto *Subrange = llvm::dyn_cast<llvm::DISubrange>(N)) {
NumElements *= Subrange->getCount();
} else {
assert(!"Unhandled array element");
return 0;
}
}
return NumElements;
}
void DumpArrayType(llvm::DICompositeType const *Ty) {
unsigned NumElements = NumArrayElements(Ty);
Log("Array %s: size: %d", Ty->getName().str().c_str(), NumElements);
if (NumElements == 0) {
std::abort();
return;
}
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *ElementTy = Ty->getBaseType().resolve(EmptyMap);
ScopedIndenter indent;
DumpFullType(ElementTy);
}
void DumpStructType(llvm::DICompositeType const *Ty) {
Log("Struct %s", Ty->getName().str().c_str());
ScopedIndenter indent;
auto Elements = Ty->getElements();
if (Elements.begin() == Elements.end()) {
Log("Resource member: size %d", Ty->getSizeInBits());
return;
}
for (auto *Element : Elements) {
switch (Element->getTag()) {
case llvm::dwarf::DW_TAG_member: {
if (auto *Member = llvm::dyn_cast<llvm::DIDerivedType>(Element)) {
DumpFullType(Member);
break;
}
assert(!"member is not a Member");
std::abort();
return;
}
case llvm::dwarf::DW_TAG_subprogram: {
if (auto *SubProgram = llvm::dyn_cast<llvm::DISubprogram>(Element)) {
Log("Member function %s", SubProgram->getName().str().c_str());
continue;
}
assert(!"DISubprogram not understood");
std::abort();
return;
}
case llvm::dwarf::DW_TAG_inheritance: {
if (auto *Member = llvm::dyn_cast<llvm::DIDerivedType>(Element)) {
DumpFullType(Member);
} else {
std::abort();
}
continue;
}
default:
assert(!"Unhandled field type in DIStructType");
std::abort();
}
}
}
#endif
} // namespace PIXPassHelpers
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilRemoveDiscards.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilRemoveDiscards.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to remove all instances of the discard instruction //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
using namespace llvm;
using namespace hlsl;
class DxilRemoveDiscards : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilRemoveDiscards() : ModulePass(ID) {}
StringRef getPassName() const override {
return "DXIL Remove all discard instructions";
}
bool runOnModule(Module &M) override;
};
bool DxilRemoveDiscards::runOnModule(Module &M) {
// This pass removes all instances of the discard instruction within the
// shader.
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
Function *DiscardFunction =
HlslOP->GetOpFunc(DXIL::OpCode::Discard, Type::getVoidTy(Ctx));
auto DiscardFunctionUses = DiscardFunction->uses();
bool Modified = false;
for (auto FI = DiscardFunctionUses.begin();
FI != DiscardFunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto instruction = cast<Instruction>(FunctionUser);
instruction->eraseFromParent();
Modified = true;
}
return Modified;
}
char DxilRemoveDiscards::ID = 0;
ModulePass *llvm::createDxilRemoveDiscardsPass() {
return new DxilRemoveDiscards();
}
INITIALIZE_PASS(DxilRemoveDiscards, "hlsl-dxil-remove-discards",
"HLSL DXIL Remove all discard instructions", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilPIXDXRInvocationsLog.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilPIXDXRInvocationsLog.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Transforms/Utils/Local.h"
#include "PixPassHelpers.h"
using namespace llvm;
using namespace hlsl;
using namespace PIXPassHelpers;
class DxilPIXDXRInvocationsLog : public ModulePass {
uint64_t m_MaxNumEntriesInLog = 1;
public:
static char ID;
DxilPIXDXRInvocationsLog() : ModulePass(ID) {}
StringRef getPassName() const override {
return "DXIL Logs all non-RayGen DXR 1.0 invocations into a UAV";
}
void applyOptions(PassOptions O) override;
bool runOnModule(Module &M) override;
};
static DXIL::ShaderKind GetShaderKind(DxilModule const &DM,
llvm::Function const *entryFunction) {
DXIL::ShaderKind ShaderKind = DXIL::ShaderKind::Invalid;
if (!DM.HasDxilFunctionProps(entryFunction)) {
auto ShaderModel = DM.GetShaderModel();
ShaderKind = ShaderModel->GetKind();
} else {
auto const &Props = DM.GetDxilFunctionProps(entryFunction);
ShaderKind = Props.shaderKind;
}
return ShaderKind;
}
void DxilPIXDXRInvocationsLog::applyOptions(PassOptions O) {
GetPassOptionUInt64(
O, "maxNumEntriesInLog", &m_MaxNumEntriesInLog,
1); // Use a silly default value. PIX should set a better value here.
}
bool DxilPIXDXRInvocationsLog::runOnModule(Module &M) {
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
bool Modified = false;
for (auto entryFunction : DM.GetExportedFunctions()) {
DXIL::ShaderKind ShaderKind = GetShaderKind(DM, entryFunction);
switch (ShaderKind) {
case DXIL::ShaderKind::Intersection:
case DXIL::ShaderKind::AnyHit:
case DXIL::ShaderKind::ClosestHit:
case DXIL::ShaderKind::Miss:
break;
default:
continue;
}
Modified = true;
IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(entryFunction));
// Add the UAVs that we're going to write to
CallInst *HandleForCountUAV = PIXPassHelpers::CreateUAVOnceForModule(
DM, Builder, /* registerID */ 0, "PIX_CountUAV_Handle");
CallInst *HandleForUAV = PIXPassHelpers::CreateUAVOnceForModule(
DM, Builder, /* registerID */ 1, "PIX_UAV_Handle");
DM.ReEmitDxilResources();
auto DispatchRaysIndexOpFunc = HlslOP->GetOpFunc(
DXIL::OpCode::DispatchRaysIndex, Type::getInt32Ty(Ctx));
auto WorldRayOriginOpFunc =
HlslOP->GetOpFunc(DXIL::OpCode::WorldRayOrigin, Type::getFloatTy(Ctx));
auto WorldRayDirectionOpFunc = HlslOP->GetOpFunc(
DXIL::OpCode::WorldRayDirection, Type::getFloatTy(Ctx));
auto CurrentRayTFunc =
HlslOP->GetOpFunc(DXIL::OpCode::RayTCurrent, Type::getFloatTy(Ctx));
auto MinRayTFunc =
HlslOP->GetOpFunc(DXIL::OpCode::RayTMin, Type::getFloatTy(Ctx));
auto RayFlagsFunc =
HlslOP->GetOpFunc(DXIL::OpCode::RayFlags, Type::getInt32Ty(Ctx));
auto *DispatchRaysIndexOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::DispatchRaysIndex);
auto *WorldRayOriginOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::WorldRayOrigin);
auto *WorldRayDirectionOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::WorldRayDirection);
auto *CurrentRayTOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::RayTCurrent);
auto *MinRayTOpcode = HlslOP->GetU32Const((unsigned)DXIL::OpCode::RayTMin);
auto *RayFlagsOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::RayFlags);
auto DispatchRaysX = Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, HlslOP->GetI8Const(0)}, "DispatchRaysX");
auto DispatchRaysY = Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, HlslOP->GetI8Const(1)}, "DispatchRaysY");
auto DispatchRaysZ = Builder.CreateCall(
DispatchRaysIndexOpFunc,
{DispatchRaysIndexOpcode, HlslOP->GetI8Const(2)}, "DispatchRaysZ");
auto WorldRayOriginX = Builder.CreateCall(
WorldRayOriginOpFunc, {WorldRayOriginOpcode, HlslOP->GetI8Const(0)},
"WorldRayOriginX");
auto WorldRayOriginY = Builder.CreateCall(
WorldRayOriginOpFunc, {WorldRayOriginOpcode, HlslOP->GetI8Const(1)},
"WorldRayOriginY");
auto WorldRayOriginZ = Builder.CreateCall(
WorldRayOriginOpFunc, {WorldRayOriginOpcode, HlslOP->GetI8Const(2)},
"WorldRayOriginZ");
auto WorldRayDirectionX = Builder.CreateCall(
WorldRayDirectionOpFunc,
{WorldRayDirectionOpcode, HlslOP->GetI8Const(0)}, "WorldRayDirectionX");
auto WorldRayDirectionY = Builder.CreateCall(
WorldRayDirectionOpFunc,
{WorldRayDirectionOpcode, HlslOP->GetI8Const(1)}, "WorldRayDirectionY");
auto WorldRayDirectionZ = Builder.CreateCall(
WorldRayDirectionOpFunc,
{WorldRayDirectionOpcode, HlslOP->GetI8Const(2)}, "WorldRayDirectionZ");
auto CurrentRayT =
Builder.CreateCall(CurrentRayTFunc, {CurrentRayTOpcode}, "CurrentRayT");
auto MinRayT = Builder.CreateCall(MinRayTFunc, {MinRayTOpcode}, "MinRayT");
auto RayFlags =
Builder.CreateCall(RayFlagsFunc, {RayFlagsOpcode}, "RayFlags");
Function *AtomicOpFunc =
HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(Ctx));
Constant *AtomicBinOpcode =
HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
Constant *AtomicAdd =
HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
Function *UMinOpFunc =
HlslOP->GetOpFunc(OP::OpCode::UMin, Type::getInt32Ty(Ctx));
Constant *UMinOpCode = HlslOP->GetU32Const((unsigned)OP::OpCode::UMin);
Function *StoreFuncFloat =
HlslOP->GetOpFunc(OP::OpCode::BufferStore, Type::getFloatTy(Ctx));
Function *StoreFuncInt =
HlslOP->GetOpFunc(OP::OpCode::BufferStore, Type::getInt32Ty(Ctx));
Constant *StoreOpcode =
HlslOP->GetU32Const((unsigned)OP::OpCode::BufferStore);
Constant *WriteMask_XYZW = HlslOP->GetI8Const(15);
Constant *WriteMask_X = HlslOP->GetI8Const(1);
Constant *ShaderKindAsConstant = HlslOP->GetU32Const((uint32_t)ShaderKind);
Constant *MaxEntryIndexAsConstant =
HlslOP->GetU32Const((uint32_t)m_MaxNumEntriesInLog - 1u);
Constant *Zero32Arg = HlslOP->GetU32Const(0);
Constant *One32Arg = HlslOP->GetU32Const(1);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(Ctx));
// Firstly we read this invocation's index within the invocations log
// buffer, and atomically increment it for the next invocation
auto *EntryIndex = Builder.CreateCall(
AtomicOpFunc,
{
AtomicBinOpcode, // i32, ; opcode
HandleForCountUAV, // %dx.types.Handle, ; resource handle
AtomicAdd, // i32, ; binary operation code
Zero32Arg, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
UndefArg, // i32, ; coordinate c2 (unused)
One32Arg // i32); increment value
},
"EntryIndexResult");
// Clamp the index so that we don't write off the end of the UAV. If we
// clamp, then it's up to PIX to replay the work again with a larger log
// buffer.
auto *EntryIndexClamped = Builder.CreateCall(
UMinOpFunc, {UMinOpCode, EntryIndex, MaxEntryIndexAsConstant});
const auto numBytesPerEntry =
4 + (3 * 4) + (3 * 4) + (3 * 4) + 4 + 4 +
4; // See number of bytes we store per shader invocation below
auto EntryOffset =
Builder.CreateMul(EntryIndexClamped,
HlslOP->GetU32Const(numBytesPerEntry), "EntryOffset");
auto EntryOffsetPlus16 = Builder.CreateAdd(
EntryOffset, HlslOP->GetU32Const(16), "EntryOffsetPlus16");
auto EntryOffsetPlus32 = Builder.CreateAdd(
EntryOffset, HlslOP->GetU32Const(32), "EntryOffsetPlus32");
auto EntryOffsetPlus48 = Builder.CreateAdd(
EntryOffset, HlslOP->GetU32Const(48), "EntryOffsetPlus48");
// Then we start storing the invocation's info into the main UAV buffer
(void)Builder.CreateCall(
StoreFuncInt,
{
StoreOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
EntryOffset, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
ShaderKindAsConstant, // i32, ; value v0
DispatchRaysX, // i32, ; value v1
DispatchRaysY, // i32, ; value v2
DispatchRaysZ, // i32, ; value v3
WriteMask_XYZW // i8 ;
});
(void)Builder.CreateCall(
StoreFuncFloat,
{
StoreOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
EntryOffsetPlus16, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
WorldRayOriginX, // f32, ; value v0
WorldRayOriginY, // f32, ; value v1
WorldRayOriginZ, // f32, ; value v2
WorldRayDirectionX, // f32, ; value v3
WriteMask_XYZW // i8 ;
});
(void)Builder.CreateCall(
StoreFuncFloat,
{
StoreOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
EntryOffsetPlus32, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
WorldRayDirectionY, // f32, ; value v0
WorldRayDirectionZ, // f32, ; value v1
MinRayT, // f32, ; value v2
CurrentRayT, // f32, ; value v3
WriteMask_XYZW // i8 ;
});
(void)Builder.CreateCall(
StoreFuncInt,
{
StoreOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
EntryOffsetPlus48, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
RayFlags, // i32, ; value v0
UndefArg, // i32, ; value v1
UndefArg, // i32, ; value v2
UndefArg, // i32, ; value v3
WriteMask_X // i8 ;
});
}
return Modified;
}
char DxilPIXDXRInvocationsLog::ID = 0;
ModulePass *llvm::createDxilPIXDXRInvocationsLogPass() {
return new DxilPIXDXRInvocationsLog();
}
INITIALIZE_PASS(DxilPIXDXRInvocationsLog, "hlsl-dxil-pix-dxr-invocations-log",
"HLSL DXIL Logs all non-RayGen DXR 1.0 invocations into a UAV",
false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilShaderAccessTracking.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilShaderAccessTracking.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to add instrumentation to determine pixel hit count and //
// cost. Used by PIX. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilResourceBinding.h"
#include "dxc/DXIL/DxilResourceProperties.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <deque>
#include "PixPassHelpers.h"
#ifdef _WIN32
#include <winerror.h>
#endif
using namespace llvm;
using namespace hlsl;
using namespace hlsl::DXIL::OperandIndex;
void ThrowIf(bool a) {
if (a) {
throw ::hlsl::Exception(E_INVALIDARG);
}
}
//---------------------------------------------------------------------------------------------------------------------------------
// These types are taken from PIX's ShaderAccessHelpers.h
enum class ShaderAccessFlags : uint32_t {
None = 0,
Read = 1 << 0,
Write = 1 << 1,
// "Counter" access is only applicable to UAVs; it means the counter buffer
// attached to the UAV was accessed, but not necessarily the UAV resource.
Counter = 1 << 2,
Sampler = 1 << 3,
// Descriptor-only read (if any), but not the resource contents (if any).
// Used for GetDimensions, samplers, and secondary texture for sampler
// feedback.
// TODO: Make this a unique value if supported in PIX, then enable
// GetDimensions
DescriptorRead = 1 << 0,
};
// Bits in encoded dword:
// 33222222222211111111110000000000
// 10987654321098765432109876543210
// kkkkisssrrrrrrrrrrrrrrrrrrrrrrrr
//
// k: four bits ShaderKind
// i: one bit InstructionOrdinalndicator
// r: 24 bits if i = 0 (resource index) else (instruction ordinal)
constexpr uint32_t InstructionOrdinalndicator = 0x0800'0000;
// (end shared types)
//---------------------------------------------------------------------------------------------------------------------------------
static uint32_t EncodeShaderModel(DXIL::ShaderKind kind) {
DXASSERT_NOMSG(static_cast<int>(DXIL::ShaderKind::Invalid) <= 16);
return static_cast<uint32_t>(kind) << 28;
}
enum class ResourceAccessStyle {
None,
Sampler,
UAVRead,
UAVWrite,
CBVRead,
SRVRead,
EndOfEnum
};
static uint32_t EncodeAccess(ResourceAccessStyle access) {
DXASSERT_NOMSG(static_cast<int>(ResourceAccessStyle::EndOfEnum) <= 8);
uint32_t encoded = static_cast<uint32_t>(access);
return encoded << 24;
}
constexpr uint32_t DWORDsPerResource = 3;
constexpr uint32_t BytesPerDWORD = 4;
static uint32_t OffsetFromAccess(ShaderAccessFlags access) {
switch (access) {
case ShaderAccessFlags::Read:
return 0;
case ShaderAccessFlags::Write:
return 1;
case ShaderAccessFlags::Counter:
return 2;
default:
throw ::hlsl::Exception(E_INVALIDARG);
}
}
// This enum doesn't have to match PIX's version, because the values are
// received from PIX encoded in ASCII. However, for ease of comparing this code
// with PIX, and to be less confusing to future maintainers, this enum does
// indeed match the same-named enum in PIX.
enum class RegisterType {
CBV,
SRV,
UAV,
RTV, // not used.
DSV, // not used.
Sampler,
SOV, // not used.
Invalid,
Terminator
};
RegisterType RegisterTypeFromResourceClass(DXIL::ResourceClass c) {
switch (c) {
case DXIL::ResourceClass::SRV:
return RegisterType::SRV;
break;
case DXIL::ResourceClass::UAV:
return RegisterType::UAV;
break;
case DXIL::ResourceClass::CBuffer:
return RegisterType::CBV;
break;
case DXIL::ResourceClass::Sampler:
return RegisterType::Sampler;
break;
case DXIL::ResourceClass::Invalid:
return RegisterType::Invalid;
break;
default:
ThrowIf(true);
return RegisterType::Invalid;
}
}
struct RegisterTypeAndSpace {
bool operator<(const RegisterTypeAndSpace &o) const {
return static_cast<int>(Type) < static_cast<int>(o.Type) ||
(static_cast<int>(Type) == static_cast<int>(o.Type) &&
Space < o.Space);
}
RegisterType Type;
unsigned Space;
};
// Identifies a bind point as defined by the root signature
struct RSRegisterIdentifier {
RegisterType Type;
unsigned Space;
unsigned Index;
bool operator<(const RSRegisterIdentifier &o) const {
return static_cast<unsigned>(Type) < static_cast<unsigned>(o.Type) &&
Space < o.Space && Index < o.Index;
}
};
struct SlotRange {
unsigned startSlot;
unsigned numSlots;
// Number of slots needed if no descriptors from unbounded ranges are included
unsigned numInvariableSlots;
};
enum class AccessStyle {
None,
FromRootSig,
ResourceFromDescriptorHeap,
SamplerFromDescriptorHeap
};
struct DxilResourceAndClass {
AccessStyle accessStyle;
RegisterType registerType;
int RegisterSpace;
unsigned RegisterID;
Value *index;
Value *indexDynamicOffset;
Value *dynamicallyBoundIndex;
};
//---------------------------------------------------------------------------------------------------------------------------------
class DxilShaderAccessTracking : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilShaderAccessTracking() : ModulePass(ID) {}
StringRef getPassName() const override {
return "DXIL shader access tracking";
}
bool runOnModule(Module &M) override;
void applyOptions(PassOptions O) override;
private:
void EmitAccess(LLVMContext &Ctx, OP *HlslOP, IRBuilder<> &, Value *slot,
ShaderAccessFlags access);
bool EmitResourceAccess(DxilModule &DM, DxilResourceAndClass &res,
Instruction *instruction, OP *HlslOP,
LLVMContext &Ctx, ShaderAccessFlags readWrite);
DxilResourceAndClass GetResourceFromHandle(Value *resHandle, DxilModule &DM);
DxilResourceAndClass
DetermineAccessForHandleForLib(CallInst *handleCreation,
DxilResourceAndClass &initializedRnC,
DxilModule &DM);
private:
struct DynamicResourceBinding {
int HeapIndex;
bool HeapIsSampler; // else resource
std::string Name;
};
std::vector<DynamicResourceBinding> m_dynamicResourceBindings;
bool m_CheckForDynamicIndexing = false;
int m_DynamicResourceDataOffset = -1;
int m_DynamicSamplerDataOffset = -1;
int m_OutputBufferSize = -1;
std::map<RegisterTypeAndSpace, SlotRange> m_slotAssignments;
std::map<llvm::Function *, CallInst *> m_FunctionToUAVHandle;
std::map<llvm::Function *, std::map<ResourceAccessStyle, Constant *>>
m_FunctionToEncodedAccess;
std::set<RSRegisterIdentifier> m_DynamicallyIndexedBindPoints;
std::vector<std::unique_ptr<GetElementPtrInst>>
m_GEPOperandAsInstructionDestroyers;
};
static unsigned DeserializeInt(std::deque<char> &q) {
unsigned i = 0;
while (!q.empty() && isdigit(q.front())) {
i *= 10;
i += q.front() - '0';
q.pop_front();
}
return i;
}
static char DequeFront(std::deque<char> &q) {
ThrowIf(q.empty());
auto c = q.front();
q.pop_front();
return c;
}
static RegisterType ParseRegisterType(std::deque<char> &q) {
switch (DequeFront(q)) {
case 'C':
return RegisterType::CBV;
case 'S':
return RegisterType::SRV;
case 'U':
return RegisterType::UAV;
case 'M':
return RegisterType::Sampler;
case 'I':
return RegisterType::Invalid;
default:
return RegisterType::Terminator;
}
}
static char EncodeRegisterType(RegisterType r) {
switch (r) {
case RegisterType::CBV:
return 'C';
case RegisterType::SRV:
return 'S';
case RegisterType::UAV:
return 'U';
case RegisterType::Sampler:
return 'M';
case RegisterType::Invalid:
return 'I';
}
return '.';
}
static void ValidateDelimiter(std::deque<char> &q, char d) {
ThrowIf(q.front() != d);
q.pop_front();
}
void DxilShaderAccessTracking::applyOptions(PassOptions O) {
int checkForDynamic;
GetPassOptionInt(O, "checkForDynamicIndexing", &checkForDynamic, 0);
m_CheckForDynamicIndexing = checkForDynamic != 0;
StringRef configOption;
if (GetPassOption(O, "config", &configOption)) {
std::deque<char> config;
config.assign(configOption.begin(), configOption.end());
// Parse slot assignments. Compare with PIX's ShaderAccessHelpers.cpp
// (TrackingConfiguration::SerializedRepresentation)
RegisterType rt = ParseRegisterType(config);
while (rt != RegisterType::Terminator) {
RegisterTypeAndSpace rst;
rst.Type = rt;
rst.Space = DeserializeInt(config);
ValidateDelimiter(config, ':');
SlotRange sr;
sr.startSlot = DeserializeInt(config);
ValidateDelimiter(config, ':');
sr.numSlots = DeserializeInt(config);
ValidateDelimiter(config, 'i');
sr.numInvariableSlots = DeserializeInt(config);
ValidateDelimiter(config, ';');
m_slotAssignments[rst] = sr;
rt = ParseRegisterType(config);
}
m_DynamicResourceDataOffset = DeserializeInt(config);
ValidateDelimiter(config, ';');
m_DynamicSamplerDataOffset = DeserializeInt(config);
ValidateDelimiter(config, ';');
m_OutputBufferSize = DeserializeInt(config);
}
}
void DxilShaderAccessTracking::EmitAccess(LLVMContext &Ctx, OP *HlslOP,
IRBuilder<> &Builder,
Value *ByteIndex,
ShaderAccessFlags access) {
unsigned OffsetForAccessType =
static_cast<unsigned>(OffsetFromAccess(access) * BytesPerDWORD);
auto OffsetByteIndex = Builder.CreateAdd(
ByteIndex, HlslOP->GetU32Const(OffsetForAccessType), "OffsetByteIndex");
UndefValue *UndefIntArg = UndefValue::get(Type::getInt32Ty(Ctx));
Constant *LiteralOne = HlslOP->GetU32Const(1);
Constant *ElementMask = HlslOP->GetI8Const(1);
Function *StoreFunc =
HlslOP->GetOpFunc(OP::OpCode::BufferStore, Type::getInt32Ty(Ctx));
Constant *StoreOpcode =
HlslOP->GetU32Const((unsigned)OP::OpCode::BufferStore);
(void)Builder.CreateCall(
StoreFunc,
{
StoreOpcode, // i32, ; opcode
m_FunctionToUAVHandle.at(
Builder.GetInsertBlock()
->getParent()), // %dx.types.Handle, ; resource handle
OffsetByteIndex, // i32, ; coordinate c0: byte offset
UndefIntArg, // i32, ; coordinate c1 (unused)
LiteralOne, // i32, ; value v0
UndefIntArg, // i32, ; value v1
UndefIntArg, // i32, ; value v2
UndefIntArg, // i32, ; value v3
ElementMask // i8 ; just the first value is used
});
}
static ResourceAccessStyle
AccessStyleFromAccessAndType(AccessStyle accessStyle, RegisterType registerType,
ShaderAccessFlags readWrite) {
switch (accessStyle) {
case AccessStyle::ResourceFromDescriptorHeap:
switch (registerType) {
case RegisterType::CBV:
return ResourceAccessStyle::CBVRead;
case RegisterType::SRV:
return ResourceAccessStyle::SRVRead;
case RegisterType::UAV:
return readWrite == ShaderAccessFlags::Read
? ResourceAccessStyle::UAVRead
: ResourceAccessStyle::UAVWrite;
default:
return ResourceAccessStyle::None;
}
case AccessStyle::SamplerFromDescriptorHeap:
return ResourceAccessStyle::Sampler;
default:
return ResourceAccessStyle::None;
}
}
bool DxilShaderAccessTracking::EmitResourceAccess(DxilModule &DM,
DxilResourceAndClass &res,
Instruction *instruction,
OP *HlslOP, LLVMContext &Ctx,
ShaderAccessFlags readWrite) {
IRBuilder<> Builder(instruction);
if (res.accessStyle == AccessStyle::FromRootSig) {
RegisterTypeAndSpace typeAndSpace{
res.registerType,
static_cast<unsigned>(res.RegisterSpace) // reserved spaces are -ve, but
// user spaces can only be +ve
};
auto slot = m_slotAssignments.find(typeAndSpace);
// If the assignment isn't found, we assume it's not accessed
if (slot != m_slotAssignments.end()) {
Value *slotIndex;
if (isa<ConstantInt>(res.index) && res.indexDynamicOffset == nullptr) {
unsigned index = cast<ConstantInt>(res.index)->getLimitedValue();
if (index > slot->second.numSlots) {
// out-of-range accesses are written to slot zero:
slotIndex = HlslOP->GetU32Const(0);
} else {
slotIndex = HlslOP->GetU32Const((slot->second.startSlot + index) *
DWORDsPerResource * BytesPerDWORD);
}
} else {
RSRegisterIdentifier id{typeAndSpace.Type, typeAndSpace.Space,
res.RegisterID};
m_DynamicallyIndexedBindPoints.emplace(std::move(id));
Value *index = res.index;
if (res.indexDynamicOffset != nullptr) {
index = Builder.CreateAdd(res.index, res.indexDynamicOffset,
"IndexPlusGEPIndex");
}
// CompareWithSlotLimit will contain 1 if the access is out-of-bounds
// (both over- and and under-flow via the unsigned >= with slot count)
auto CompareWithSlotLimit = Builder.CreateICmpUGE(
index, HlslOP->GetU32Const(slot->second.numSlots),
"CompareWithSlotLimit");
auto CompareWithSlotLimitAsUint = Builder.CreateCast(
Instruction::CastOps::ZExt, CompareWithSlotLimit,
Type::getInt32Ty(Ctx), "CompareWithSlotLimitAsUint");
// IsInBounds will therefore contain 0 if the access is out-of-bounds,
// and 1 otherwise.
auto IsInBounds = Builder.CreateSub(
HlslOP->GetU32Const(1), CompareWithSlotLimitAsUint, "IsInBounds");
auto SlotDwordOffset = Builder.CreateAdd(
index, HlslOP->GetU32Const(slot->second.startSlot),
"SlotDwordOffset");
auto SlotByteOffset = Builder.CreateMul(
SlotDwordOffset,
HlslOP->GetU32Const(DWORDsPerResource * BytesPerDWORD),
"SlotByteOffset");
// This will drive an out-of-bounds access slot down to 0
slotIndex = Builder.CreateMul(SlotByteOffset, IsInBounds, "slotIndex");
}
EmitAccess(Ctx, HlslOP, Builder, slotIndex, readWrite);
return true; // did modify
}
} else if (m_DynamicResourceDataOffset != -1) {
if (res.accessStyle == AccessStyle::ResourceFromDescriptorHeap ||
res.accessStyle == AccessStyle::SamplerFromDescriptorHeap) {
Constant *BaseOfRecordsForType;
int LimitForType;
if (res.accessStyle == AccessStyle::ResourceFromDescriptorHeap) {
LimitForType = m_DynamicSamplerDataOffset - m_DynamicResourceDataOffset;
BaseOfRecordsForType = HlslOP->GetU32Const(m_DynamicResourceDataOffset);
} else {
LimitForType = m_OutputBufferSize - m_DynamicSamplerDataOffset;
BaseOfRecordsForType = HlslOP->GetU32Const(m_DynamicSamplerDataOffset);
}
// Branchless limit: compare offset to size of data reserved for that
// type, resulting in a value of 0 or 1. Extend that 0/1 to an integer,
// and multiply the offset by that value. Result: expected offset, or 0 if
// too large.
// Add 1 to the index in order to skip over the zeroth entry: that's
// reserved for "out of bounds" writes.
auto *IndexToWrite =
Builder.CreateAdd(res.dynamicallyBoundIndex, HlslOP->GetU32Const(1));
// Each record is two dwords:
// the first dword is for write access, the second for read.
Constant *SizeofRecord =
HlslOP->GetU32Const(2 * static_cast<unsigned int>(sizeof(uint32_t)));
auto *BaseOfRecord = Builder.CreateMul(IndexToWrite, SizeofRecord);
Value *OffsetToWrite;
if (readWrite == ShaderAccessFlags::Write) {
OffsetToWrite = BaseOfRecord;
} else {
OffsetToWrite = Builder.CreateAdd(
BaseOfRecord,
HlslOP->GetU32Const(static_cast<unsigned int>(sizeof(uint32_t))));
}
// Generate the 0 (out of bounds) or 1 (in-bounds) multiplier:
Constant *BufferLimit = HlslOP->GetU32Const(LimitForType);
auto *LimitBoolean = Builder.CreateICmpULT(OffsetToWrite, BufferLimit);
auto *ZeroIfOutOfBounds = Builder.CreateCast(
Instruction::CastOps::ZExt, LimitBoolean, Type::getInt32Ty(Ctx));
// Limit the offset to the out-of-bounds record if the above generated 0,
// or leave it as-is if the above generated 1:
auto *LimitedOffset = Builder.CreateMul(OffsetToWrite, ZeroIfOutOfBounds);
// Offset into the range of records for this type of access (resource or
// sampler)
auto *Offset = Builder.CreateAdd(BaseOfRecordsForType, LimitedOffset);
ResourceAccessStyle accessStyle = AccessStyleFromAccessAndType(
res.accessStyle, res.registerType, readWrite);
Constant *EncodedFlags =
m_FunctionToEncodedAccess.at(Builder.GetInsertBlock()->getParent())
.at(accessStyle);
// Now: if we're out-of-bounds, we'll actually write the offending
// instruction number instead, again using the mul-by-one-or-zero trick
auto *OneIfOutOfBounds =
Builder.CreateSub(HlslOP->GetU32Const(1), ZeroIfOutOfBounds);
auto *MultipliedEncodedFlags =
Builder.CreateMul(ZeroIfOutOfBounds, EncodedFlags);
uint32_t InstructionNumber = 0;
(void)pix_dxil::PixDxilInstNum::FromInst(instruction, &InstructionNumber);
auto const *shaderModel = DM.GetShaderModel();
auto shaderKind = shaderModel->GetKind();
uint32_t EncodedInstructionNumber = InstructionNumber |
InstructionOrdinalndicator |
EncodeShaderModel(shaderKind);
auto *MultipliedOutOfBoundsValue = Builder.CreateMul(
OneIfOutOfBounds, HlslOP->GetU32Const(EncodedInstructionNumber));
auto *CombinedFlagOrInstructionValue =
Builder.CreateAdd(MultipliedEncodedFlags, MultipliedOutOfBoundsValue);
Constant *ElementMask = HlslOP->GetI8Const(1);
Function *StoreFunc =
HlslOP->GetOpFunc(OP::OpCode::BufferStore, Type::getInt32Ty(Ctx));
Constant *StoreOpcode =
HlslOP->GetU32Const((unsigned)OP::OpCode::BufferStore);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(Ctx));
(void)Builder.CreateCall(
StoreFunc,
{
StoreOpcode, // i32, ; opcode
m_FunctionToUAVHandle.at(
Builder.GetInsertBlock()
->getParent()), // %dx.types.Handle, ; resource handle
Offset, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
CombinedFlagOrInstructionValue, // i32, ; value v0
UndefArg, // i32, ; value v1
UndefArg, // i32, ; value v2
UndefArg, // i32, ; value v3
ElementMask // i8 ; just the first value is used
});
return true; // did modify
}
}
return false; // did not modify
}
DxilResourceAndClass DxilShaderAccessTracking::DetermineAccessForHandleForLib(
CallInst *handleCreation, DxilResourceAndClass &initializedRnC,
DxilModule &DM) {
DxilResourceAndClass ret = initializedRnC;
DxilInst_CreateHandleForLib createHandleForLib(handleCreation);
auto *res = createHandleForLib.get_Resource();
auto *loadInstruction = llvm::cast<llvm::LoadInst>(res);
auto *ptr = loadInstruction->getOperand(0);
GlobalVariable *global = nullptr;
Value *GEPIndex = nullptr;
GetElementPtrInst *GEP = nullptr;
if (llvm::isa<GetElementPtrInst>(ptr)) {
GEP = llvm::cast<GetElementPtrInst>(ptr);
} else if (llvm::isa<ConstantExpr>(ptr)) {
auto *constant = llvm::cast<ConstantExpr>(ptr);
if (constant->getOpcode() == Instruction::GetElementPtr) {
m_GEPOperandAsInstructionDestroyers.emplace_back(
llvm::cast<GetElementPtrInst>(constant->getAsInstruction()));
GEP = m_GEPOperandAsInstructionDestroyers.back().get();
}
} else if (llvm::isa<GlobalVariable>(ptr)) {
GlobalVariable *Global = llvm::cast_or_null<GlobalVariable>(ptr);
// If the load instruction points straight at a global, it's not an indexed
// load, so we can ignore it.
global = Global;
}
if (GEP != nullptr) {
// GEPs can have complex nested pointer dereferences, so make sure
// it's the kind we expect for an indexed global lookup:
auto *FirstGEPIndex = GEP->getOperand(1);
if (llvm::isa<ConstantInt>(FirstGEPIndex) &&
llvm::cast<ConstantInt>(FirstGEPIndex)->getLimitedValue() == 0) {
global = llvm::cast_or_null<GlobalVariable>(GEP->getPointerOperand());
GEPIndex = GEP->getOperand(2);
}
}
if (global != nullptr) {
hlsl::DxilResourceBinding binding{};
ret.registerType = RegisterType::Invalid;
auto const &CBuffers = DM.GetCBuffers();
for (auto &CBuffer : CBuffers) {
if (global == CBuffer->GetGlobalSymbol()) {
binding =
hlsl::resource_helper::loadBindingFromResourceBase(CBuffer.get());
ret.registerType = RegisterType::CBV;
break;
}
}
if (ret.registerType == RegisterType::Invalid) {
auto const &SRVs = DM.GetSRVs();
for (auto &SRV : SRVs) {
if (global == SRV->GetGlobalSymbol()) {
binding =
hlsl::resource_helper::loadBindingFromResourceBase(SRV.get());
ret.registerType = RegisterType::SRV;
break;
}
}
}
if (ret.registerType == RegisterType::Invalid) {
auto const &UAVs = DM.GetUAVs();
for (auto &UAV : UAVs) {
if (global == UAV->GetGlobalSymbol()) {
binding =
hlsl::resource_helper::loadBindingFromResourceBase(UAV.get());
ret.registerType = RegisterType::UAV;
break;
}
}
}
if (ret.registerType != RegisterType::Invalid) {
ret.accessStyle = AccessStyle::FromRootSig;
ret.RegisterID = binding.rangeLowerBound;
ret.RegisterSpace = binding.spaceID;
ret.index = DM.GetOP()->GetU32Const(binding.rangeLowerBound);
// The GEP index is of course relative to the base address of the
// resource, so we make a note of it so we can add it to the base
// register index later.
ret.indexDynamicOffset = GEPIndex;
}
}
return ret;
}
DxilResourceAndClass
DxilShaderAccessTracking::GetResourceFromHandle(Value *resHandle,
DxilModule &DM) {
DxilResourceAndClass ret{AccessStyle::None,
RegisterType::Terminator,
0,
0,
nullptr,
nullptr,
nullptr};
Constant *C = dyn_cast<Constant>(resHandle);
if (C && C->isZeroValue()) {
return ret;
}
if (!isa<CallInst>(resHandle)) {
return ret; // todo
}
CallInst *handle = cast<CallInst>(resHandle);
unsigned rangeId = -1;
if (hlsl::OP::IsDxilOpFuncCallInst(handle, hlsl::OP::OpCode::CreateHandle)) {
DxilInst_CreateHandle createHandle(handle);
// Dynamic rangeId is not supported - skip and let validation report the
// error.
if (isa<ConstantInt>(createHandle.get_rangeId())) {
rangeId =
cast<ConstantInt>(createHandle.get_rangeId())->getLimitedValue();
auto resClass = static_cast<DXIL::ResourceClass>(
createHandle.get_resourceClass_val());
DxilResourceBase *resource = nullptr;
RegisterType registerType = RegisterType::Invalid;
switch (resClass) {
case DXIL::ResourceClass::SRV:
resource = &DM.GetSRV(rangeId);
registerType = RegisterType::SRV;
break;
case DXIL::ResourceClass::UAV:
resource = &DM.GetUAV(rangeId);
registerType = RegisterType::UAV;
break;
case DXIL::ResourceClass::CBuffer:
resource = &DM.GetCBuffer(rangeId);
registerType = RegisterType::CBV;
break;
case DXIL::ResourceClass::Sampler:
resource = &DM.GetSampler(rangeId);
registerType = RegisterType::Sampler;
break;
}
if (resource != nullptr) {
ret.index = createHandle.get_index();
ret.registerType = registerType;
ret.accessStyle = AccessStyle::FromRootSig;
ret.RegisterID = resource->GetID();
ret.RegisterSpace = resource->GetSpaceID();
}
}
} else if (hlsl::OP::IsDxilOpFuncCallInst(handle,
hlsl::OP::OpCode::AnnotateHandle)) {
DxilInst_AnnotateHandle annotateHandle(handle);
auto properties = hlsl::resource_helper::loadPropsFromAnnotateHandle(
annotateHandle, *DM.GetShaderModel());
auto *handleCreation = dyn_cast<CallInst>(annotateHandle.get_res());
if (handleCreation != nullptr) {
if (hlsl::OP::IsDxilOpFuncCallInst(
handleCreation, hlsl::OP::OpCode::CreateHandleFromBinding)) {
DxilInst_CreateHandleFromBinding createHandleFromBinding(
handleCreation);
Constant *B = cast<Constant>(createHandleFromBinding.get_bind());
auto binding = hlsl::resource_helper::loadBindingFromConstant(*B);
ret.accessStyle = AccessStyle::FromRootSig;
ret.index = createHandleFromBinding.get_index();
ret.registerType = RegisterTypeFromResourceClass(
static_cast<hlsl::DXIL::ResourceClass>(binding.resourceClass));
ret.RegisterSpace = binding.spaceID;
} else if (hlsl::OP::IsDxilOpFuncCallInst(
handleCreation, hlsl::OP::OpCode::CreateHandleFromHeap)) {
DxilInst_CreateHandleFromHeap createHandleFromHeap(handleCreation);
ret.accessStyle = createHandleFromHeap.get_samplerHeap_val()
? AccessStyle::SamplerFromDescriptorHeap
: AccessStyle::ResourceFromDescriptorHeap;
ret.dynamicallyBoundIndex = createHandleFromHeap.get_index();
ret.registerType =
RegisterTypeFromResourceClass(properties.getResourceClass());
DynamicResourceBinding drb{};
drb.HeapIsSampler = createHandleFromHeap.get_samplerHeap_val();
drb.HeapIndex = -1;
drb.Name = "ShaderNameTodo";
if (auto *constInt =
dyn_cast<ConstantInt>(createHandleFromHeap.get_index())) {
drb.HeapIndex = constInt->getLimitedValue();
}
m_dynamicResourceBindings.emplace_back(std::move(drb));
return ret;
} else if (hlsl::OP::IsDxilOpFuncCallInst(
handleCreation, hlsl::OP::OpCode::CreateHandleForLib)) {
ret = DetermineAccessForHandleForLib(handleCreation, ret, DM);
} else {
DXASSERT_NOMSG(false);
}
}
} else if (hlsl::OP::IsDxilOpFuncCallInst(
handle, hlsl::OP::OpCode::CreateHandleForLib)) {
ret = DetermineAccessForHandleForLib(handle, ret, DM);
}
return ret;
}
static bool CheckForDynamicIndexing(OP *HlslOP, LLVMContext &Ctx,
DxilModule &DM) {
bool FoundDynamicIndexing = false;
for (llvm::Function &F : DM.GetModule()->functions()) {
if (F.isDeclaration() && !F.use_empty() && OP::IsDxilOpFunc(&F)) {
if (F.hasName()) {
if (F.getName().find("createHandleForLib") != StringRef::npos) {
auto FunctionUses = F.uses();
for (auto FI = FunctionUses.begin(); FI != FunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto instruction = cast<Instruction>(FunctionUser);
Value *resourceLoad =
instruction->getOperand(kCreateHandleForLibResOpIdx);
if (auto *load = cast<LoadInst>(resourceLoad)) {
auto *resOrGep = load->getOperand(0);
if (isa<GetElementPtrInst>(resOrGep)) {
FoundDynamicIndexing = true;
break;
}
}
}
}
}
}
if (FoundDynamicIndexing) {
break;
}
}
if (!FoundDynamicIndexing) {
auto CreateHandleFn =
HlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(Ctx));
for (auto FI = CreateHandleFn->user_begin();
FI != CreateHandleFn->user_end();) {
auto *FunctionUser = *FI++;
auto instruction = cast<Instruction>(FunctionUser);
Value *index = instruction->getOperand(kCreateHandleResIndexOpIdx);
if (!isa<Constant>(index)) {
FoundDynamicIndexing = true;
break;
}
}
}
if (!FoundDynamicIndexing) {
auto CreateHandleFromBindingFn = HlslOP->GetOpFunc(
DXIL::OpCode::CreateHandleFromBinding, Type::getVoidTy(Ctx));
for (auto FI = CreateHandleFromBindingFn->user_begin();
FI != CreateHandleFromBindingFn->user_end();) {
auto *FunctionUser = *FI++;
auto instruction = cast<Instruction>(FunctionUser);
Value *index =
instruction->getOperand(kCreateHandleFromBindingResIndexOpIdx);
if (!isa<Constant>(index)) {
FoundDynamicIndexing = true;
break;
}
}
}
if (!FoundDynamicIndexing) {
auto CreateHandleFromHeapFn = HlslOP->GetOpFunc(
DXIL::OpCode::CreateHandleFromHeap, Type::getVoidTy(Ctx));
for (auto FI = CreateHandleFromHeapFn->user_begin();
FI != CreateHandleFromHeapFn->user_end();) {
auto *FunctionUser = *FI++;
auto instruction = cast<Instruction>(FunctionUser);
Value *index =
instruction->getOperand(kCreateHandleFromHeapHeapIndexOpIdx);
if (!isa<Constant>(index)) {
FoundDynamicIndexing = true;
break;
}
}
}
return FoundDynamicIndexing;
}
bool DxilShaderAccessTracking::runOnModule(Module &M) {
// This pass adds instrumentation for shader access to resources
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
bool Modified = false;
if (m_CheckForDynamicIndexing) {
bool FoundDynamicIndexing = CheckForDynamicIndexing(HlslOP, Ctx, DM);
if (FoundDynamicIndexing) {
if (OSOverride != nullptr) {
formatted_raw_ostream FOS(*OSOverride);
FOS << "FoundDynamicIndexing";
}
}
} else {
auto instrumentableFunctions =
PIXPassHelpers::GetAllInstrumentableFunctions(DM);
if (DM.m_ShaderFlags.GetForceEarlyDepthStencil()) {
if (OSOverride != nullptr) {
formatted_raw_ostream FOS(*OSOverride);
FOS << "ShouldAssumeDsvAccess";
}
}
auto uav =
PIXPassHelpers::CreateGlobalUAVResource(DM, 0u, "PIX_ShaderAccessUAV");
for (auto *F : instrumentableFunctions) {
DXIL::ShaderKind shaderKind = DXIL::ShaderKind::Invalid;
if (!DM.HasDxilFunctionProps(F)) {
auto ShaderModel = DM.GetShaderModel();
shaderKind = ShaderModel->GetKind();
if (shaderKind == DXIL::ShaderKind::Library) {
continue;
}
} else {
hlsl::DxilFunctionProps const &props = DM.GetDxilFunctionProps(F);
shaderKind = props.shaderKind;
}
IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
m_FunctionToUAVHandle[F] = PIXPassHelpers::CreateHandleForResource(
DM, Builder, uav, "PIX_ShaderAccessUAV_Handle");
OP *HlslOP = DM.GetOP();
for (int accessStyle = static_cast<int>(ResourceAccessStyle::None);
accessStyle < static_cast<int>(ResourceAccessStyle::EndOfEnum);
++accessStyle) {
ResourceAccessStyle style =
static_cast<ResourceAccessStyle>(accessStyle);
m_FunctionToEncodedAccess[F][style] = HlslOP->GetU32Const(
EncodeShaderModel(shaderKind) | EncodeAccess(style));
}
}
DM.ReEmitDxilResources();
for (llvm::Function &F : M.functions()) {
if (!F.isDeclaration() || F.isIntrinsic() || !OP::IsDxilOpFunc(&F))
continue;
// Gather handle parameter indices, if any
FunctionType *fnTy =
cast<FunctionType>(F.getType()->getPointerElementType());
SmallVector<unsigned, 4> handleParams;
for (unsigned iParam = 1; iParam < fnTy->getFunctionNumParams();
++iParam) {
if (fnTy->getParamType(iParam) == HlslOP->GetHandleType())
handleParams.push_back(iParam);
}
if (handleParams.empty())
continue;
auto FunctionUses = F.uses();
for (auto FI = FunctionUses.begin(); FI != FunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto Call = cast<CallInst>(FunctionUser);
auto *CallerParent = Call->getParent();
if (llvm::isa<llvm::BasicBlock>(CallerParent)) {
auto opCode = OP::GetDxilOpFuncCallInst(Call);
// Base Read/Write on function attribute - should match for all normal
// resource operations
ShaderAccessFlags readWrite = ShaderAccessFlags::Write;
if (OP::GetMemAccessAttr(opCode) ==
llvm::Attribute::AttrKind::ReadOnly)
readWrite = ShaderAccessFlags::Read;
// Special cases
switch (opCode) {
case DXIL::OpCode::GetDimensions:
// readWrite = ShaderAccessFlags::DescriptorRead; // TODO: Support
// GetDimensions
continue;
case DXIL::OpCode::BufferUpdateCounter:
readWrite = ShaderAccessFlags::Counter;
break;
case DXIL::OpCode::TraceRay:
// Read of AccelerationStructure; doesn't match function attribute
// readWrite = ShaderAccessFlags::Read; // TODO: Support
continue;
case DXIL::OpCode::RayQuery_TraceRayInline: {
// Read of AccelerationStructure; doesn't match function attribute
auto res = GetResourceFromHandle(Call->getArgOperand(2), DM);
if (res.accessStyle == AccessStyle::None) {
continue;
}
if (EmitResourceAccess(DM, res, Call, HlslOP, Ctx,
ShaderAccessFlags::Read)) {
Modified = true;
}
}
continue;
default:
break;
}
for (unsigned iParam : handleParams) {
// Don't instrument the accesses to the UAV that we just added
if (Call->getArgOperand(iParam) ==
m_FunctionToUAVHandle[CallerParent->getParent()])
continue;
auto res = GetResourceFromHandle(Call->getArgOperand(iParam), DM);
if (res.accessStyle == AccessStyle::None) {
continue;
}
// Don't instrument the accesses to the UAV that we just added
if (res.RegisterSpace == -2) {
break;
}
if (EmitResourceAccess(DM, res, Call, HlslOP, Ctx, readWrite)) {
Modified = true;
}
// Remaining resources are DescriptorRead.
readWrite = ShaderAccessFlags::DescriptorRead;
}
}
}
}
if (OSOverride != nullptr) {
formatted_raw_ostream FOS(*OSOverride);
FOS << "DynamicallyIndexedBindPoints=";
for (auto const &bp : m_DynamicallyIndexedBindPoints) {
FOS << EncodeRegisterType(bp.Type) << bp.Space << ':' << bp.Index
<< ';';
}
FOS << ".";
// todo: this will reflect dynamic resource names when the metadata
// exists
FOS << "DynamicallyBoundResources=";
for (auto const &drb : m_dynamicResourceBindings) {
FOS << (drb.HeapIsSampler ? 'S' : 'R') << drb.HeapIndex << ';';
}
FOS << ".";
}
}
// Done with these guys:
m_GEPOperandAsInstructionDestroyers.clear();
return Modified;
}
char DxilShaderAccessTracking::ID = 0;
ModulePass *llvm::createDxilShaderAccessTrackingPass() {
return new DxilShaderAccessTracking();
}
INITIALIZE_PASS(DxilShaderAccessTracking,
"hlsl-dxil-pix-shader-access-instrumentation",
"HLSL DXIL shader access tracking for PIX", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilReduceMSAAToSingleSample.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilReduceMSAAToSingleSample.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to reduce all MSAA writes to single-sample writes //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
using namespace llvm;
using namespace hlsl;
class DxilReduceMSAAToSingleSample : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilReduceMSAAToSingleSample() : ModulePass(ID) {}
StringRef getPassName() const override {
return "HLSL DXIL Reduce all MSAA reads to single-sample reads";
}
bool runOnModule(Module &M) override;
};
bool DxilReduceMSAAToSingleSample::runOnModule(Module &M) {
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
// FP16 type doesn't have its own identity, and is covered by float type...
auto TextureLoadOverloads = std::vector<Type *>{
Type::getFloatTy(Ctx), Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)};
bool Modified = false;
for (const auto &Overload : TextureLoadOverloads) {
Function *TexLoadFunction =
HlslOP->GetOpFunc(DXIL::OpCode::TextureLoad, Overload);
auto TexLoadFunctionUses = TexLoadFunction->uses();
for (auto FI = TexLoadFunctionUses.begin();
FI != TexLoadFunctionUses.end();) {
auto &FunctionUse = *FI++;
auto FunctionUser = FunctionUse.getUser();
auto instruction = cast<Instruction>(FunctionUser);
DxilInst_TextureLoad LoadInstruction(instruction);
auto TextureHandle = LoadInstruction.get_srv();
auto TextureHandleInst = cast<CallInst>(TextureHandle);
DxilInst_CreateHandle createHandle(TextureHandleInst);
// Dynamic rangeId is not supported
if (isa<ConstantInt>(createHandle.get_rangeId())) {
unsigned rangeId =
cast<ConstantInt>(createHandle.get_rangeId())->getLimitedValue();
if (static_cast<DXIL::ResourceClass>(
createHandle.get_resourceClass_val()) ==
DXIL::ResourceClass::SRV) {
auto Resource = DM.GetSRV(rangeId);
if (Resource.GetKind() == DXIL::ResourceKind::Texture2DMS ||
Resource.GetKind() == DXIL::ResourceKind::Texture2DMSArray) {
// "2" is the mip-level/sample-index operand index:
// https://github.com/Microsoft/DirectXShaderCompiler/blob/master/docs/DXIL.rst#textureload
instruction->setOperand(2, HlslOP->GetI32Const(0));
Modified = true;
}
}
}
}
}
return Modified;
}
char DxilReduceMSAAToSingleSample::ID = 0;
ModulePass *llvm::createDxilReduceMSAAToSingleSamplePass() {
return new DxilReduceMSAAToSingleSample();
}
INITIALIZE_PASS(DxilReduceMSAAToSingleSample, "hlsl-dxil-reduce-msaa-to-single",
"HLSL DXIL Reduce all MSAA writes to single-sample writes",
false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/CMakeLists.txt | # Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License.
# See LICENSE.TXT for details.
add_hlsl_hctgen(DxilPIXPasses OUTPUT DxilPIXPasses.inc BUILD_DIR)
add_llvm_library(LLVMDxilPIXPasses
DxilAddPixelHitInstrumentation.cpp
DxilAnnotateWithVirtualRegister.cpp
DxilDbgValueToDbgDeclare.cpp
DxilDebugInstrumentation.cpp
DxilForceEarlyZ.cpp
DxilOutputColorBecomesConstant.cpp
DxilPIXMeshShaderOutputInstrumentation.cpp
DxilRemoveDiscards.cpp
DxilReduceMSAAToSingleSample.cpp
DxilShaderAccessTracking.cpp
DxilPIXPasses.cpp
DxilPIXVirtualRegisters.cpp
PixPassHelpers.cpp
DxilPIXAddTidToAmplificationShaderPayload.cpp
DxilPIXDXRInvocationsLog.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
add_dependencies(LLVMDxilPIXPasses intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilDbgValueToDbgDeclare.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilDbgValueToDbgDeclare.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Converts calls to llvm.dbg.value to llvm.dbg.declare + alloca + stores. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResourceBase.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "PixPassHelpers.h"
using namespace PIXPassHelpers;
using namespace llvm;
//#define VALUE_TO_DECLARE_LOGGING
#ifdef VALUE_TO_DECLARE_LOGGING
#ifndef PIX_DEBUG_DUMP_HELPER
#error Turn on PIX_DEBUG_DUMP_HELPER in PixPassHelpers.h
#endif
#define VALUE_TO_DECLARE_LOG Log
#else
#define VALUE_TO_DECLARE_LOG(...)
#endif
#define DEBUG_TYPE "dxil-dbg-value-to-dbg-declare"
namespace {
using OffsetInBits = unsigned;
using SizeInBits = unsigned;
struct Offsets {
OffsetInBits Aligned;
OffsetInBits Packed;
};
// DITypePeelTypeAlias peels const, typedef, and other alias types off of Ty,
// returning the unalised type.
static llvm::DIType *DITypePeelTypeAlias(llvm::DIType *Ty) {
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
const llvm::DITypeIdentifierMap EmptyMap;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_pointer_type:
return DITypePeelTypeAlias(DerivedTy->getBaseType().resolve(EmptyMap));
case llvm::dwarf::DW_TAG_member:
return DITypePeelTypeAlias(DerivedTy->getBaseType().resolve(EmptyMap));
}
}
return Ty;
}
llvm::DIBasicType *BaseTypeIfItIsBasicAndLarger(llvm::DIType *Ty) {
// Working around problems with bitfield size/alignment:
// For bitfield types, size may be < 32, but the underlying type
// will have the size of that basic type, e.g. 32 for ints.
// By contrast, for min16float, size will be 16, but align will be 16 or 32
// depending on whether or not 16-bit is enabled.
// So if we find a disparity in size, we can assume it's not e.g. min16float.
auto *baseType = DITypePeelTypeAlias(Ty);
if (Ty->getSizeInBits() != 0 &&
Ty->getSizeInBits() < baseType->getSizeInBits())
return llvm::dyn_cast<llvm::DIBasicType>(baseType);
return nullptr;
}
// OffsetManager is used to map between "packed" and aligned offsets.
//
// For example, the aligned offsets for a struct [float, half, int, double]
// will be {0, 32, 64, 128} (assuming 32 bit alignments for ints, and 64
// bit for doubles), while the packed offsets will be {0, 32, 48, 80}.
//
// This mapping makes it easier to deal with llvm.dbg.values whose value
// operand does not match exactly the Variable operand's type.
class OffsetManager {
unsigned DescendTypeToGetAlignMask(llvm::DIType *Ty) {
unsigned AlignMask = Ty->getAlignInBits();
if (BaseTypeIfItIsBasicAndLarger(Ty))
AlignMask = 0;
else {
auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty);
if (DerivedTy != nullptr) {
// Working around a bug where byte size is stored instead of bit size
if (AlignMask == 4 && Ty->getSizeInBits() == 32) {
AlignMask = 32;
}
if (AlignMask == 0) {
const llvm::DITypeIdentifierMap EmptyMap;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef: {
llvm::DIType *baseType = DerivedTy->getBaseType().resolve(EmptyMap);
if (baseType != nullptr) {
return DescendTypeToGetAlignMask(baseType);
}
}
}
}
}
}
return AlignMask;
}
public:
OffsetManager() = default;
// AlignTo aligns the current aligned offset to Ty's natural alignment.
void AlignTo(llvm::DIType *Ty) {
unsigned AlignMask = DescendTypeToGetAlignMask(Ty);
if (AlignMask) {
VALUE_TO_DECLARE_LOG("Aligning to %d", AlignMask);
m_CurrentAlignedOffset =
llvm::RoundUpToAlignment(m_CurrentAlignedOffset, AlignMask);
} else {
VALUE_TO_DECLARE_LOG("Failed to find alignment");
}
}
// Add is used to "add" an aggregate element (struct field, array element)
// at the current aligned/packed offsets, bumping them by Ty's size.
Offsets Add(llvm::DIBasicType *Ty, unsigned sizeOverride) {
VALUE_TO_DECLARE_LOG("Adding known type at aligned %d / packed %d, size %d",
m_CurrentAlignedOffset, m_CurrentPackedOffset,
Ty->getSizeInBits());
m_PackedOffsetToAlignedOffset[m_CurrentPackedOffset] =
m_CurrentAlignedOffset;
m_AlignedOffsetToPackedOffset[m_CurrentAlignedOffset] =
m_CurrentPackedOffset;
const Offsets Ret = {m_CurrentAlignedOffset, m_CurrentPackedOffset};
unsigned size = sizeOverride != 0 ? sizeOverride : Ty->getSizeInBits();
m_CurrentPackedOffset += size;
m_CurrentAlignedOffset += size;
return Ret;
}
// AlignToAndAddUnhandledType is used for error handling when Ty
// could not be handled by the transformation. This is a best-effort
// way to continue the pass by ignoring the current type and hoping
// that adding Ty as a blob other fields/elements added will land
// in the proper offset.
void AlignToAndAddUnhandledType(llvm::DIType *Ty) {
VALUE_TO_DECLARE_LOG(
"Adding unhandled type at aligned %d / packed %d, size %d",
m_CurrentAlignedOffset, m_CurrentPackedOffset, Ty->getSizeInBits());
AlignTo(Ty);
m_CurrentPackedOffset += Ty->getSizeInBits();
m_CurrentAlignedOffset += Ty->getSizeInBits();
}
void AddResourceType(llvm::DIType *Ty) {
VALUE_TO_DECLARE_LOG(
"Adding resource type at aligned %d / packed %d, size %d",
m_CurrentAlignedOffset, m_CurrentPackedOffset, Ty->getSizeInBits());
m_PackedOffsetToAlignedOffset[m_CurrentPackedOffset] =
m_CurrentAlignedOffset;
m_AlignedOffsetToPackedOffset[m_CurrentAlignedOffset] =
m_CurrentPackedOffset;
m_CurrentPackedOffset += Ty->getSizeInBits();
m_CurrentAlignedOffset += Ty->getSizeInBits();
}
bool GetAlignedOffsetFromPackedOffset(OffsetInBits PackedOffset,
OffsetInBits *AlignedOffset) const {
return GetOffsetWithMap(m_PackedOffsetToAlignedOffset, PackedOffset,
AlignedOffset);
}
bool GetPackedOffsetFromAlignedOffset(OffsetInBits AlignedOffset,
OffsetInBits *PackedOffset) const {
return GetOffsetWithMap(m_AlignedOffsetToPackedOffset, AlignedOffset,
PackedOffset);
}
OffsetInBits GetCurrentPackedOffset() const { return m_CurrentPackedOffset; }
OffsetInBits GetCurrentAlignedOffset() const {
return m_CurrentAlignedOffset;
}
private:
OffsetInBits m_CurrentPackedOffset = 0;
OffsetInBits m_CurrentAlignedOffset = 0;
using OffsetMap = std::unordered_map<OffsetInBits, OffsetInBits>;
OffsetMap m_PackedOffsetToAlignedOffset;
OffsetMap m_AlignedOffsetToPackedOffset;
static bool GetOffsetWithMap(const OffsetMap &Map, OffsetInBits SrcOffset,
OffsetInBits *DstOffset) {
auto it = Map.find(SrcOffset);
if (it == Map.end()) {
return false;
}
*DstOffset = it->second;
return true;
}
};
// VariableRegisters contains the logic for traversing a DIType T and
// creating AllocaInsts that map back to a specific offset within T.
class VariableRegisters {
public:
VariableRegisters(llvm::DebugLoc const &m_dbgLoc,
llvm::BasicBlock::iterator allocaInsertionPoint,
llvm::DIVariable *Variable, llvm::DIType *Ty,
llvm::Module *M);
llvm::AllocaInst *
GetRegisterForAlignedOffset(OffsetInBits AlignedOffset) const;
const OffsetManager &GetOffsetManager() const { return m_Offsets; }
static SizeInBits GetVariableSizeInbits(DIVariable *Var);
private:
void PopulateAllocaMap(llvm::DIType *Ty);
void PopulateAllocaMap_BasicType(llvm::DIBasicType *Ty,
unsigned sizeOverride);
void PopulateAllocaMap_ArrayType(llvm::DICompositeType *Ty);
void PopulateAllocaMap_StructType(llvm::DICompositeType *Ty);
llvm::DILocation *GetVariableLocation() const;
llvm::Value *GetMetadataAsValue(llvm::Metadata *M) const;
llvm::DIExpression *GetDIExpression(llvm::DIType *Ty, OffsetInBits Offset,
SizeInBits ParentSize,
unsigned sizeOverride) const;
llvm::DebugLoc const &m_dbgLoc;
llvm::DIVariable *m_Variable = nullptr;
llvm::IRBuilder<> m_B;
llvm::Function *m_DbgDeclareFn = nullptr;
OffsetManager m_Offsets;
std::unordered_map<OffsetInBits, llvm::AllocaInst *> m_AlignedOffsetToAlloca;
};
struct GlobalEmbeddedArrayElementStorage {
std::string Name;
OffsetInBits Offset;
SizeInBits Size;
};
using GlobalVariableToLocalMirrorMap =
std::map<llvm::Function const *, llvm::DILocalVariable *>;
struct LocalMirrorsAndStorage {
std::vector<GlobalEmbeddedArrayElementStorage> ArrayElementStorage;
GlobalVariableToLocalMirrorMap LocalMirrors;
};
using GlobalStorageMap =
std::map<llvm::DIGlobalVariable *, LocalMirrorsAndStorage>;
class DxilDbgValueToDbgDeclare : public llvm::ModulePass {
public:
static char ID;
DxilDbgValueToDbgDeclare() : llvm::ModulePass(ID) {}
bool runOnModule(llvm::Module &M) override;
private:
void handleDbgValue(llvm::Module &M, llvm::DbgValueInst *DbgValue);
bool handleStoreIfDestIsGlobal(llvm::Module &M,
GlobalStorageMap &GlobalStorage,
llvm::StoreInst *Store);
std::unordered_map<llvm::DIVariable *, std::unique_ptr<VariableRegisters>>
m_Registers;
};
} // namespace
char DxilDbgValueToDbgDeclare::ID = 0;
struct ValueAndOffset {
llvm::Value *m_V;
OffsetInBits m_PackedOffset;
};
// SplitValue splits an llvm::Value into possibly multiple
// scalar Values. Those scalar values will later be "stored"
// into their corresponding register.
static OffsetInBits SplitValue(llvm::Value *V, OffsetInBits CurrentOffset,
std::vector<ValueAndOffset> *Values,
llvm::IRBuilder<> &B) {
auto *VTy = V->getType();
if (auto *ArrTy = llvm::dyn_cast<llvm::ArrayType>(VTy)) {
for (unsigned i = 0; i < ArrTy->getNumElements(); ++i) {
CurrentOffset =
SplitValue(B.CreateExtractValue(V, {i}), CurrentOffset, Values, B);
}
} else if (auto *StTy = llvm::dyn_cast<llvm::StructType>(VTy)) {
for (unsigned i = 0; i < StTy->getNumElements(); ++i) {
CurrentOffset =
SplitValue(B.CreateExtractValue(V, {i}), CurrentOffset, Values, B);
}
} else if (auto *VecTy = llvm::dyn_cast<llvm::VectorType>(VTy)) {
for (unsigned i = 0; i < VecTy->getNumElements(); ++i) {
CurrentOffset =
SplitValue(B.CreateExtractElement(V, i), CurrentOffset, Values, B);
}
} else {
assert(VTy->isFloatTy() || VTy->isDoubleTy() || VTy->isHalfTy() ||
VTy->isIntegerTy(32) || VTy->isIntegerTy(64) ||
VTy->isIntegerTy(16) || VTy->isPointerTy());
Values->emplace_back(ValueAndOffset{V, CurrentOffset});
CurrentOffset += VTy->getScalarSizeInBits();
}
return CurrentOffset;
}
// A more convenient version of SplitValue.
static std::vector<ValueAndOffset>
SplitValue(llvm::Value *V, OffsetInBits CurrentOffset, llvm::IRBuilder<> &B) {
std::vector<ValueAndOffset> Ret;
SplitValue(V, CurrentOffset, &Ret, B);
return Ret;
}
// Convenient helper for parsing a DIExpression's offset.
static OffsetInBits GetAlignedOffsetFromDIExpression(llvm::DIExpression *Exp) {
if (!Exp->isBitPiece()) {
return 0;
}
return Exp->getBitPieceOffset();
}
llvm::DISubprogram *GetFunctionDebugInfo(llvm::Module &M, llvm::Function *fn) {
auto FnMap = makeSubprogramMap(M);
return FnMap[fn];
}
GlobalVariableToLocalMirrorMap
GenerateGlobalToLocalMirrorMap(llvm::Module &M, llvm::DIGlobalVariable *DIGV) {
auto &Functions = M.getFunctionList();
std::string LocalMirrorOfGlobalName =
std::string("global.") + std::string(DIGV->getName());
GlobalVariableToLocalMirrorMap ret;
DenseMap<const Function *, DISubprogram *> FnMap;
for (llvm::Function const &fn : Functions) {
auto &blocks = fn.getBasicBlockList();
if (!blocks.empty()) {
auto &LocalMirror = ret[&fn];
for (auto &block : blocks) {
bool breakOut = false;
for (auto &instruction : block) {
if (auto const *DbgValue =
llvm::dyn_cast<llvm::DbgValueInst>(&instruction)) {
auto *Variable = DbgValue->getVariable();
if (Variable->getName().equals(LocalMirrorOfGlobalName)) {
LocalMirror = Variable;
breakOut = true;
break;
}
}
if (auto const *DbgDeclare =
llvm::dyn_cast<llvm::DbgDeclareInst>(&instruction)) {
auto *Variable = DbgDeclare->getVariable();
if (Variable->getName().equals(LocalMirrorOfGlobalName)) {
LocalMirror = Variable;
breakOut = true;
break;
}
}
}
if (breakOut)
break;
}
if (LocalMirror == nullptr) {
// If we didn't find a dbg.value for any member of this
// DIGlobalVariable, then no local mirror exists. We must manufacture
// one.
if (FnMap.empty()) {
FnMap = makeSubprogramMap(M);
}
auto DIFn = FnMap[&fn];
if (DIFn != nullptr) {
const llvm::DITypeIdentifierMap EmptyMap;
auto DIGVType = DIGV->getType().resolve(EmptyMap);
DIBuilder DbgInfoBuilder(M);
LocalMirror = DbgInfoBuilder.createLocalVariable(
dwarf::DW_TAG_auto_variable, DIFn, LocalMirrorOfGlobalName,
DIFn->getFile(), DIFn->getLine(), DIGVType);
}
}
}
}
return ret;
}
std::vector<GlobalEmbeddedArrayElementStorage>
DescendTypeAndFindEmbeddedArrayElements(llvm::StringRef VariableName,
uint64_t AccumulatedMemberOffset,
llvm::DIType *Ty, uint64_t OffsetToSeek,
uint64_t SizeToSeek) {
const llvm::DITypeIdentifierMap EmptyMap;
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
auto BaseTy = DerivedTy->getBaseType().resolve(EmptyMap);
auto storage = DescendTypeAndFindEmbeddedArrayElements(
VariableName, AccumulatedMemberOffset, BaseTy, OffsetToSeek,
SizeToSeek);
if (!storage.empty()) {
return storage;
}
} else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty)) {
switch (CompositeTy->getTag()) {
case llvm::dwarf::DW_TAG_array_type: {
for (auto Element : CompositeTy->getElements()) {
// First element for an array is DISubrange
if (auto Subrange = llvm::dyn_cast<DISubrange>(Element)) {
auto ElementTy = CompositeTy->getBaseType().resolve(EmptyMap);
if (auto *BasicTy = llvm::dyn_cast<llvm::DIBasicType>(ElementTy)) {
bool CorrectLowerOffset = AccumulatedMemberOffset == OffsetToSeek;
bool CorrectUpperOffset =
AccumulatedMemberOffset +
Subrange->getCount() * BasicTy->getSizeInBits() ==
OffsetToSeek + SizeToSeek;
if (BasicTy != nullptr && CorrectLowerOffset &&
CorrectUpperOffset) {
std::vector<GlobalEmbeddedArrayElementStorage> storage;
for (int64_t i = 0; i < Subrange->getCount(); ++i) {
auto ElementOffset =
AccumulatedMemberOffset + i * BasicTy->getSizeInBits();
GlobalEmbeddedArrayElementStorage element;
element.Name = VariableName.str() + "." + std::to_string(i);
element.Offset = static_cast<OffsetInBits>(ElementOffset);
element.Size =
static_cast<SizeInBits>(BasicTy->getSizeInBits());
storage.push_back(std::move(element));
}
return storage;
}
}
// If we didn't succeed and return above, then we need to process each
// element in the array
std::vector<GlobalEmbeddedArrayElementStorage> storage;
for (int64_t i = 0; i < Subrange->getCount(); ++i) {
auto elementStorage = DescendTypeAndFindEmbeddedArrayElements(
VariableName,
AccumulatedMemberOffset + ElementTy->getSizeInBits() * i,
ElementTy, OffsetToSeek, SizeToSeek);
std::move(elementStorage.begin(), elementStorage.end(),
std::back_inserter(storage));
}
if (!storage.empty()) {
return storage;
}
}
}
for (auto Element : CompositeTy->getElements()) {
// First element for an array is DISubrange
if (auto Subrange = llvm::dyn_cast<DISubrange>(Element)) {
auto ElementType = CompositeTy->getBaseType().resolve(EmptyMap);
for (int64_t i = 0; i < Subrange->getCount(); ++i) {
auto storage = DescendTypeAndFindEmbeddedArrayElements(
VariableName,
AccumulatedMemberOffset + ElementType->getSizeInBits() * i,
ElementType, OffsetToSeek, SizeToSeek);
if (!storage.empty()) {
return storage;
}
}
}
}
} break;
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type: {
for (auto Element : CompositeTy->getElements()) {
if (auto diMember = llvm::dyn_cast<DIType>(Element)) {
auto storage = DescendTypeAndFindEmbeddedArrayElements(
VariableName,
AccumulatedMemberOffset + diMember->getOffsetInBits(), diMember,
OffsetToSeek, SizeToSeek);
if (!storage.empty()) {
return storage;
}
}
}
} break;
}
}
return {};
}
GlobalStorageMap GatherGlobalEmbeddedArrayStorage(llvm::Module &M) {
GlobalStorageMap ret;
auto DebugFinder = llvm::make_unique<llvm::DebugInfoFinder>();
DebugFinder->processModule(M);
auto GlobalVariables = DebugFinder->global_variables();
// First find the list of global variables that represent HLSL global statics:
const llvm::DITypeIdentifierMap EmptyMap;
SmallVector<llvm::DIGlobalVariable *, 8> GlobalStaticVariables;
for (llvm::DIGlobalVariable *DIGV : GlobalVariables) {
if (DIGV->isLocalToUnit()) {
llvm::DIType *DIGVType = DIGV->getType().resolve(EmptyMap);
// We're only interested in aggregates, since only they might have
// embedded arrays:
if (isa<llvm::DICompositeType>(DIGVType)) {
auto LocalMirrors = GenerateGlobalToLocalMirrorMap(M, DIGV);
if (!LocalMirrors.empty()) {
GlobalStaticVariables.push_back(DIGV);
ret[DIGV].LocalMirrors = std::move(LocalMirrors);
}
}
}
}
// Now find any globals that represent embedded arrays inside the global
// statics
for (auto HLSLStruct : GlobalStaticVariables) {
for (llvm::DIGlobalVariable *DIGV : GlobalVariables) {
if (DIGV != HLSLStruct && !DIGV->isLocalToUnit()) {
llvm::DIType *DIGVType = DIGV->getType().resolve(EmptyMap);
if (auto *DIGVDerivedType =
llvm::dyn_cast<llvm::DIDerivedType>(DIGVType)) {
if (DIGVDerivedType->getTag() == llvm::dwarf::DW_TAG_member) {
// This type is embedded within the containing DIGSV type
const llvm::DITypeIdentifierMap EmptyMap;
auto *Ty = HLSLStruct->getType().resolve(EmptyMap);
auto Storage = DescendTypeAndFindEmbeddedArrayElements(
DIGV->getName(), 0, Ty, DIGVDerivedType->getOffsetInBits(),
DIGVDerivedType->getSizeInBits());
auto &ArrayStorage = ret[HLSLStruct].ArrayElementStorage;
std::move(Storage.begin(), Storage.end(),
std::back_inserter(ArrayStorage));
}
}
}
}
}
return ret;
}
bool DxilDbgValueToDbgDeclare::runOnModule(llvm::Module &M) {
auto GlobalEmbeddedArrayStorage = GatherGlobalEmbeddedArrayStorage(M);
bool Changed = false;
auto &Functions = M.getFunctionList();
for (auto &fn : Functions) {
llvm::SmallPtrSet<Value *, 16> RayQueryHandles;
PIXPassHelpers::FindRayQueryHandlesForFunction(&fn, RayQueryHandles);
// #DSLTodo: We probably need to merge the list of variables for each
// export into one set so that WinPIX shader debugging can follow a
// thread through any function within a given module. (Unless PIX
// chooses to launch a new debugging session whenever control passes
// from one function to another.) For now, it's sufficient to treat each
// exported function as having completely separate variables by clearing
// this member:
m_Registers.clear();
// Note: they key problem here is variables in common functions called
// by multiple exported functions. The DILocalVariables in the common
// function will be exactly the same objects no matter which export
// called the common function, so the instrumentation here gets a bit
// confused that the same variable is present in two functions and ends
// up pointing one function to allocas in another function. (This is
// easy to repro: comment out the above clear(), and run
// PixTest::PixStructAnnotation_Lib_DualRaygen.) Not sure what the right
// path forward is: might be that we have to tag m_Registers with the
// exported function, and maybe write out a function identifier during
// debug instrumentation...
auto &blocks = fn.getBasicBlockList();
if (!blocks.empty()) {
for (auto &block : blocks) {
std::vector<Instruction *> instructions;
for (auto &instruction : block) {
instructions.push_back(&instruction);
}
// Handle store instructions before handling dbg.value, since the
// latter will add store instructions that we don't need to examine.
// Why do we handle store instructions? It's for the case of
// non-const global statics that are backed by an llvm global,
// rather than an alloca. In the llvm global case, there is no
// debug linkage between the store and the HLSL variable being
// modified. But we can patch together enough knowledge about those
// from the lists of such globals (HLSL and llvm) and comparing the
// lists.
for (auto &instruction : instructions) {
if (auto *Store = llvm::dyn_cast<llvm::StoreInst>(instruction)) {
Changed =
handleStoreIfDestIsGlobal(M, GlobalEmbeddedArrayStorage, Store);
}
}
for (auto &instruction : instructions) {
if (auto *DbgValue =
llvm::dyn_cast<llvm::DbgValueInst>(instruction)) {
llvm::Value *V = DbgValue->getValue();
if (RayQueryHandles.count(V) != 0)
continue;
Changed = true;
handleDbgValue(M, DbgValue);
DbgValue->eraseFromParent();
}
}
}
}
}
return Changed;
}
static llvm::DIType *FindStructMemberTypeAtOffset(llvm::DICompositeType *Ty,
uint64_t Offset,
uint64_t Size);
static llvm::DIType *FindMemberTypeAtOffset(llvm::DIType *Ty, uint64_t Offset,
uint64_t Size) {
VALUE_TO_DECLARE_LOG("PopulateAllocaMap for type tag %d", Ty->getTag());
const llvm::DITypeIdentifierMap EmptyMap;
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
switch (DerivedTy->getTag()) {
default:
assert(!"Unhandled DIDerivedType");
return nullptr;
case llvm::dwarf::DW_TAG_arg_variable: // "this" pointer
case llvm::dwarf::DW_TAG_pointer_type: // "this" pointer
// what to do here?
return nullptr;
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef:
return FindMemberTypeAtOffset(DerivedTy->getBaseType().resolve(EmptyMap),
Offset, Size);
case llvm::dwarf::DW_TAG_member:
return FindMemberTypeAtOffset(DerivedTy->getBaseType().resolve(EmptyMap),
Offset, Size);
case llvm::dwarf::DW_TAG_subroutine_type:
// ignore member functions.
return nullptr;
}
} else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty)) {
switch (CompositeTy->getTag()) {
default:
assert(!"Unhandled DICompositeType");
return nullptr;
case llvm::dwarf::DW_TAG_array_type:
return nullptr;
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
return FindStructMemberTypeAtOffset(CompositeTy, Offset, Size);
case llvm::dwarf::DW_TAG_enumeration_type:
return nullptr;
}
} else if (auto *BasicTy = llvm::dyn_cast<llvm::DIBasicType>(Ty)) {
if (Offset == 0 && Ty->getSizeInBits() == Size) {
return BasicTy;
}
}
assert(!"Unhandled DIType");
return nullptr;
}
// SortMembers traverses all of Ty's members and returns them sorted
// by their offset from Ty's start. Returns true if the function succeeds
// and false otherwise.
static bool
SortMembers(llvm::DICompositeType *Ty,
std::map<OffsetInBits, llvm::DIDerivedType *> *SortedMembers) {
auto Elements = Ty->getElements();
if (Elements.begin() == Elements.end()) {
return false;
}
for (auto *Element : Elements) {
switch (Element->getTag()) {
case llvm::dwarf::DW_TAG_member: {
if (auto *Member = llvm::dyn_cast<llvm::DIDerivedType>(Element)) {
if (Member->getSizeInBits()) {
auto it = SortedMembers->emplace(
std::make_pair(Member->getOffsetInBits(), Member));
(void)it;
assert(it.second &&
"Invalid DIStructType"
" - members with the same offset -- are unions possible?");
}
break;
}
assert(!"member is not a Member");
return false;
}
case llvm::dwarf::DW_TAG_subprogram: {
if (isa<llvm::DISubprogram>(Element)) {
continue;
}
assert(!"DISubprogram not understood");
return false;
}
case llvm::dwarf::DW_TAG_inheritance: {
if (auto *Member = llvm::dyn_cast<llvm::DIDerivedType>(Element)) {
auto it = SortedMembers->emplace(
std::make_pair(Member->getOffsetInBits(), Member));
(void)it;
assert(it.second &&
"Invalid DIStructType"
" - members with the same offset -- are unions possible?");
}
continue;
}
default:
assert(!"Unhandled field type in DIStructType");
return false;
}
}
return true;
}
static bool IsResourceObject(llvm::DIDerivedType *DT) {
const llvm::DITypeIdentifierMap EmptyMap;
auto *BT = DT->getBaseType().resolve(EmptyMap);
if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(BT)) {
// Resource variables (e.g. TextureCube) are composite types but have no
// elements:
if (CompositeTy->getElements().begin() ==
CompositeTy->getElements().end()) {
auto name = CompositeTy->getName();
auto openTemplateListMarker = name.find_first_of('<');
if (openTemplateListMarker != llvm::StringRef::npos) {
auto hlslType = name.substr(0, openTemplateListMarker);
for (int i = static_cast<int>(hlsl::DXIL::ResourceKind::Invalid) + 1;
i < static_cast<int>(hlsl::DXIL::ResourceKind::NumEntries); ++i) {
if (hlslType == hlsl::GetResourceKindName(
static_cast<hlsl::DXIL::ResourceKind>(i))) {
return true;
}
}
}
}
}
return false;
}
static llvm::DIType *FindStructMemberTypeAtOffset(llvm::DICompositeType *Ty,
uint64_t Offset,
uint64_t Size) {
std::map<OffsetInBits, llvm::DIDerivedType *> SortedMembers;
if (!SortMembers(Ty, &SortedMembers)) {
return Ty;
}
const llvm::DITypeIdentifierMap EmptyMap;
for (auto &member : SortedMembers) {
// "Inheritance" is a member of a composite type, but has size of zero.
// Therefore, we must descend the hierarchy once to find an actual type.
llvm::DIType *memberType = member.second;
if (memberType->getTag() == llvm::dwarf::DW_TAG_inheritance) {
memberType = member.second->getBaseType().resolve(EmptyMap);
}
if (Offset >= member.first &&
Offset < member.first + memberType->getSizeInBits()) {
uint64_t OffsetIntoThisType = Offset - member.first;
return FindMemberTypeAtOffset(memberType, OffsetIntoThisType, Size);
}
}
// Structure resources are expected to fail this (they have no real
// meaning in storage)
if (SortedMembers.size() == 1) {
switch (SortedMembers.begin()->second->getTag()) {
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
if (IsResourceObject(SortedMembers.begin()->second)) {
return nullptr;
}
}
}
#ifdef VALUE_TO_DECLARE_LOGGING
VALUE_TO_DECLARE_LOG(
"Didn't find a member that straddles the sought type. Container:");
{
ScopedIndenter indent;
Ty->dump();
DumpFullType(Ty);
}
VALUE_TO_DECLARE_LOG(
"Sought type is at offset %d size %d. Members and offsets:", Offset,
Size);
{
ScopedIndenter indent;
for (auto const &member : SortedMembers) {
member.second->dump();
LogPartialLine("Offset %d (size %d): ", member.first,
member.second->getSizeInBits());
DumpFullType(member.second);
}
}
#endif
assert(!"Didn't find a member that straddles the sought type");
return nullptr;
}
static bool IsDITypePointer(DIType *DTy,
const llvm::DITypeIdentifierMap &EmptyMap) {
DIDerivedType *DerivedTy = dyn_cast<DIDerivedType>(DTy);
if (!DerivedTy)
return false;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_pointer_type:
return true;
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
return IsDITypePointer(DerivedTy->getBaseType().resolve(EmptyMap),
EmptyMap);
}
return false;
}
void DxilDbgValueToDbgDeclare::handleDbgValue(llvm::Module &M,
llvm::DbgValueInst *DbgValue) {
VALUE_TO_DECLARE_LOG("DbgValue named %s", DbgValue->getName().str().c_str());
llvm::DIVariable *Variable = DbgValue->getVariable();
if (Variable != nullptr) {
VALUE_TO_DECLARE_LOG("... DbgValue referred to variable named %s",
Variable->getName().str().c_str());
} else {
VALUE_TO_DECLARE_LOG("... variable was null too");
}
llvm::Value *V = DbgValue->getValue();
if (V == nullptr) {
// The metadata contained a null Value, so we ignore it. This
// seems to be a dxcompiler bug.
VALUE_TO_DECLARE_LOG("...Null value!");
return;
}
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *Ty = Variable->getType().resolve(EmptyMap);
if (Ty == nullptr) {
return;
}
if (llvm::isa<llvm::PointerType>(V->getType())) {
// Safeguard: If the type is not a pointer type, then this is
// dbg.value directly pointing to a memory location instead of
// a value.
if (!IsDITypePointer(Ty, EmptyMap)) {
// We only know how to handle AllocaInsts for now
if (!isa<AllocaInst>(V)) {
VALUE_TO_DECLARE_LOG(
"... variable had pointer type, but is not an alloca.");
return;
}
IRBuilder<> B(DbgValue->getNextNode());
V = B.CreateLoad(V);
}
}
// Members' "base type" is actually the containing aggregate's type.
// To find the actual type of the variable, we must descend the
// container's type hierarchy to find the type at the expected
// offset/size.
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
const llvm::DITypeIdentifierMap EmptyMap;
switch (DerivedTy->getTag()) {
case llvm::dwarf::DW_TAG_member: {
Ty = FindMemberTypeAtOffset(DerivedTy->getBaseType().resolve(EmptyMap),
DerivedTy->getOffsetInBits(),
DerivedTy->getSizeInBits());
if (Ty == nullptr) {
return;
}
} break;
}
}
auto &Register = m_Registers[Variable];
if (Register == nullptr) {
Register.reset(new VariableRegisters(
DbgValue->getDebugLoc(),
DbgValue->getParent()->getParent()->getEntryBlock().begin(), Variable,
Ty, &M));
}
// Convert the offset from DbgValue's expression to a packed
// offset, which we'll need in order to determine the (packed)
// offset of each scalar Value in DbgValue.
llvm::DIExpression *expression = DbgValue->getExpression();
const OffsetInBits AlignedOffsetFromVar =
GetAlignedOffsetFromDIExpression(expression);
OffsetInBits PackedOffsetFromVar;
const OffsetManager &Offsets = Register->GetOffsetManager();
if (!Offsets.GetPackedOffsetFromAlignedOffset(AlignedOffsetFromVar,
&PackedOffsetFromVar)) {
// todo: output geometry for GS
return;
}
const OffsetInBits InitialOffset = PackedOffsetFromVar;
auto *insertPt = llvm::dyn_cast<llvm::Instruction>(V);
if (insertPt != nullptr && !llvm::isa<TerminatorInst>(insertPt)) {
insertPt = insertPt->getNextNode();
// Drivers may crash if phi nodes aren't always at the top of a block,
// so we must skip over them before inserting instructions.
while (llvm::isa<llvm::PHINode>(insertPt)) {
insertPt = insertPt->getNextNode();
}
if (insertPt != nullptr) {
llvm::IRBuilder<> B(insertPt);
B.SetCurrentDebugLocation(llvm::DebugLoc());
auto *Zero = B.getInt32(0);
// Now traverse a list of pairs {Scalar Value, InitialOffset +
// Offset}. InitialOffset is the offset from DbgValue's expression
// (i.e., the offset from the Variable's start), and Offset is the
// Scalar Value's packed offset from DbgValue's value.
for (const ValueAndOffset &VO : SplitValue(V, InitialOffset, B)) {
OffsetInBits AlignedOffset;
if (!Offsets.GetAlignedOffsetFromPackedOffset(VO.m_PackedOffset,
&AlignedOffset)) {
continue;
}
auto *AllocaInst = Register->GetRegisterForAlignedOffset(AlignedOffset);
if (AllocaInst == nullptr) {
assert(!"Failed to find alloca for var[offset]");
continue;
}
if (AllocaInst->getAllocatedType()->getArrayElementType() ==
VO.m_V->getType()) {
auto *GEP = B.CreateGEP(AllocaInst, {Zero, Zero});
B.CreateStore(VO.m_V, GEP);
}
}
}
}
}
struct GlobalVariableAndStorage {
llvm::DIGlobalVariable *DIGV;
OffsetInBits Offset;
};
GlobalVariableAndStorage
GetOffsetFromGlobalVariable(llvm::StringRef name,
GlobalStorageMap &GlobalEmbeddedArrayStorage) {
GlobalVariableAndStorage ret{};
for (auto &Variable : GlobalEmbeddedArrayStorage) {
for (auto &Storage : Variable.second.ArrayElementStorage) {
if (llvm::StringRef(Storage.Name).equals(name)) {
ret.DIGV = Variable.first;
ret.Offset = Storage.Offset;
return ret;
}
}
}
return ret;
}
bool DxilDbgValueToDbgDeclare::handleStoreIfDestIsGlobal(
llvm::Module &M, GlobalStorageMap &GlobalEmbeddedArrayStorage,
llvm::StoreInst *Store) {
if (Store->getDebugLoc()) {
llvm::Value *V = Store->getPointerOperand();
std::string MemberName;
if (auto *Constant = llvm::dyn_cast<llvm::ConstantExpr>(V)) {
ScopedInstruction asInstr(Constant->getAsInstruction());
if (auto *asGEP =
llvm::dyn_cast<llvm::GetElementPtrInst>(asInstr.Get())) {
// We are only interested in the case of basic types within an array
// because the PIX debug instrumentation operates at that level.
// Aggregate members will have been descended through to produce
// their own entries in the GlobalStorageMap. Consequently, we're
// only interested in the GEP's index into the array. Any deeper
// indexing in the GEP will be for embedded aggregates. The three
// operands in such a GEP mean:
// 0 = the pointer
// 1 = dereference the pointer (expected to be constant int zero)
// 2 = the index into the array
if (asGEP->getNumOperands() == 3 &&
llvm::isa<ConstantInt>(asGEP->getOperand(1)) &&
llvm::dyn_cast<ConstantInt>(asGEP->getOperand(1))
->getLimitedValue() == 0) {
// TODO: The case where this index is not a constant int
// (Needs changes to the allocas generated elsewhere in this
// pass.)
if (auto *arrayIndexAsConstInt =
llvm::dyn_cast<ConstantInt>(asGEP->getOperand(2))) {
int MemberIndex = arrayIndexAsConstInt->getLimitedValue();
MemberName = std::string(asGEP->getPointerOperand()->getName()) +
"." + std::to_string(MemberIndex);
}
}
}
} else {
MemberName = V->getName();
}
if (!MemberName.empty()) {
auto Storage =
GetOffsetFromGlobalVariable(MemberName, GlobalEmbeddedArrayStorage);
if (Storage.DIGV != nullptr) {
llvm::DILocalVariable *Variable =
GlobalEmbeddedArrayStorage[Storage.DIGV]
.LocalMirrors[Store->getParent()->getParent()];
if (Variable != nullptr) {
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *Ty = Variable->getType().resolve(EmptyMap);
if (Ty != nullptr) {
auto &Register = m_Registers[Variable];
if (Register == nullptr) {
Register.reset(new VariableRegisters(
Store->getDebugLoc(),
Store->getParent()->getParent()->getEntryBlock().begin(),
Variable, Ty, &M));
}
auto *AllocaInst =
Register->GetRegisterForAlignedOffset(Storage.Offset);
if (AllocaInst != nullptr) {
IRBuilder<> B(Store->getNextNode());
auto *Zero = B.getInt32(0);
auto *GEP = B.CreateGEP(AllocaInst, {Zero, Zero});
B.CreateStore(Store->getValueOperand(), GEP);
return true; // yes, we modified the module
}
}
}
}
}
}
return false; // no we did not modify the module
}
SizeInBits VariableRegisters::GetVariableSizeInbits(DIVariable *Var) {
const llvm::DITypeIdentifierMap EmptyMap;
DIType *Ty = Var->getType().resolve(EmptyMap);
DIDerivedType *DerivedTy = nullptr;
if (BaseTypeIfItIsBasicAndLarger(Ty))
return Ty->getSizeInBits();
while (Ty && (Ty->getSizeInBits() == 0 &&
(DerivedTy = dyn_cast<DIDerivedType>(Ty)))) {
Ty = DerivedTy->getBaseType().resolve(EmptyMap);
}
if (!Ty) {
assert(false &&
"Unexpected inability to resolve base type with a real size.");
return 0;
}
return Ty->getSizeInBits();
}
llvm::AllocaInst *
VariableRegisters::GetRegisterForAlignedOffset(OffsetInBits Offset) const {
auto it = m_AlignedOffsetToAlloca.find(Offset);
if (it == m_AlignedOffsetToAlloca.end()) {
return nullptr;
}
return it->second;
}
VariableRegisters::VariableRegisters(
llvm::DebugLoc const &dbgLoc,
llvm::BasicBlock::iterator allocaInsertionPoint, llvm::DIVariable *Variable,
llvm::DIType *Ty, llvm::Module *M)
: m_dbgLoc(dbgLoc), m_Variable(Variable), m_B(allocaInsertionPoint),
m_DbgDeclareFn(
llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::dbg_declare)) {
PopulateAllocaMap(Ty);
m_Offsets.AlignTo(Ty); // For padding.
// (min16* types can occupy 16 or 32 bits depending on whether or not they
// are natively supported. If non-native, the alignment will be 32, but
// the claimed size will still be 16, hence the "max" here)
assert(m_Offsets.GetCurrentAlignedOffset() ==
std::max<uint64_t>(DITypePeelTypeAlias(Ty)->getSizeInBits(),
DITypePeelTypeAlias(Ty)->getAlignInBits()));
}
void VariableRegisters::PopulateAllocaMap(llvm::DIType *Ty) {
VALUE_TO_DECLARE_LOG("PopulateAllocaMap for type tag %d", Ty->getTag());
const llvm::DITypeIdentifierMap EmptyMap;
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty)) {
switch (DerivedTy->getTag()) {
default:
assert(!"Unhandled DIDerivedType");
m_Offsets.AlignToAndAddUnhandledType(DerivedTy);
return;
case llvm::dwarf::DW_TAG_arg_variable: // "this" pointer
case llvm::dwarf::DW_TAG_pointer_type: // "this" pointer
case llvm::dwarf::DW_TAG_restrict_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_typedef:
PopulateAllocaMap(DerivedTy->getBaseType().resolve(EmptyMap));
return;
case llvm::dwarf::DW_TAG_member:
if (auto *baseType = BaseTypeIfItIsBasicAndLarger(DerivedTy))
PopulateAllocaMap_BasicType(baseType, DerivedTy->getSizeInBits());
else
PopulateAllocaMap(DerivedTy->getBaseType().resolve(EmptyMap));
return;
case llvm::dwarf::DW_TAG_subroutine_type:
// ignore member functions.
return;
}
} else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty)) {
switch (CompositeTy->getTag()) {
default:
assert(!"Unhandled DICompositeType");
m_Offsets.AlignToAndAddUnhandledType(CompositeTy);
return;
case llvm::dwarf::DW_TAG_array_type:
PopulateAllocaMap_ArrayType(CompositeTy);
return;
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
PopulateAllocaMap_StructType(CompositeTy);
return;
case llvm::dwarf::DW_TAG_enumeration_type: {
auto *baseType = CompositeTy->getBaseType().resolve(EmptyMap);
if (baseType != nullptr) {
PopulateAllocaMap(baseType);
} else {
m_Offsets.AlignToAndAddUnhandledType(CompositeTy);
}
}
return;
}
} else if (auto *BasicTy = llvm::dyn_cast<llvm::DIBasicType>(Ty)) {
PopulateAllocaMap_BasicType(BasicTy, 0 /*no size override*/);
return;
}
assert(!"Unhandled DIType");
m_Offsets.AlignToAndAddUnhandledType(Ty);
}
static llvm::Type *GetLLVMTypeFromDIBasicType(llvm::IRBuilder<> &B,
llvm::DIBasicType *Ty) {
const SizeInBits Size = Ty->getSizeInBits();
switch (Ty->getEncoding()) {
default:
break;
case llvm::dwarf::DW_ATE_boolean:
case llvm::dwarf::DW_ATE_signed:
case llvm::dwarf::DW_ATE_unsigned:
switch (Size) {
case 16:
return B.getInt16Ty();
case 32:
return B.getInt32Ty();
case 64:
return B.getInt64Ty();
}
break;
case llvm::dwarf::DW_ATE_float:
switch (Size) {
case 16:
return B.getHalfTy();
case 32:
return B.getFloatTy();
case 64:
return B.getDoubleTy();
}
break;
}
return nullptr;
}
void VariableRegisters::PopulateAllocaMap_BasicType(llvm::DIBasicType *Ty,
unsigned sizeOverride) {
llvm::Type *AllocaElementTy = GetLLVMTypeFromDIBasicType(m_B, Ty);
assert(AllocaElementTy != nullptr);
if (AllocaElementTy == nullptr) {
return;
}
const auto offsets = m_Offsets.Add(Ty, sizeOverride);
llvm::Type *AllocaTy = llvm::ArrayType::get(AllocaElementTy, 1);
llvm::AllocaInst *&Alloca = m_AlignedOffsetToAlloca[offsets.Aligned];
if (Alloca == nullptr) {
Alloca = m_B.CreateAlloca(AllocaTy, m_B.getInt32(0));
Alloca->setDebugLoc(llvm::DebugLoc());
}
auto *Storage = GetMetadataAsValue(llvm::ValueAsMetadata::get(Alloca));
auto *Variable = GetMetadataAsValue(m_Variable);
auto *Expression = GetMetadataAsValue(
GetDIExpression(Ty, sizeOverride == 0 ? offsets.Aligned : offsets.Packed,
GetVariableSizeInbits(m_Variable), sizeOverride));
auto *DbgDeclare =
m_B.CreateCall(m_DbgDeclareFn, {Storage, Variable, Expression});
DbgDeclare->setDebugLoc(m_dbgLoc);
}
static unsigned NumArrayElements(llvm::DICompositeType *Array) {
if (Array->getElements().size() == 0) {
return 0;
}
unsigned NumElements = 1;
for (llvm::DINode *N : Array->getElements()) {
if (auto *Subrange = llvm::dyn_cast<llvm::DISubrange>(N)) {
NumElements *= Subrange->getCount();
} else {
assert(!"Unhandled array element");
return 0;
}
}
return NumElements;
}
void VariableRegisters::PopulateAllocaMap_ArrayType(llvm::DICompositeType *Ty) {
unsigned NumElements = NumArrayElements(Ty);
if (NumElements == 0) {
m_Offsets.AlignToAndAddUnhandledType(Ty);
return;
}
const SizeInBits ArraySizeInBits = Ty->getSizeInBits();
(void)ArraySizeInBits;
const llvm::DITypeIdentifierMap EmptyMap;
llvm::DIType *ElementTy = Ty->getBaseType().resolve(EmptyMap);
assert(ArraySizeInBits % NumElements == 0 &&
" invalid DIArrayType"
" - Size is not a multiple of NumElements");
// After aligning the current aligned offset to ElementTy's natural
// alignment, the current aligned offset must match Ty's offset
// in bits.
m_Offsets.AlignTo(ElementTy);
for (unsigned i = 0; i < NumElements; ++i) {
// This is only needed if ElementTy's size is not a multiple of
// its natural alignment.
m_Offsets.AlignTo(ElementTy);
PopulateAllocaMap(ElementTy);
}
}
void VariableRegisters::PopulateAllocaMap_StructType(
llvm::DICompositeType *Ty) {
VALUE_TO_DECLARE_LOG("Struct type : %s, size %d", Ty->getName().str().c_str(),
Ty->getSizeInBits());
std::map<OffsetInBits, llvm::DIDerivedType *> SortedMembers;
if (!SortMembers(Ty, &SortedMembers)) {
m_Offsets.AlignToAndAddUnhandledType(Ty);
return;
}
m_Offsets.AlignTo(Ty);
const OffsetInBits StructStart = m_Offsets.GetCurrentAlignedOffset();
(void)StructStart;
const llvm::DITypeIdentifierMap EmptyMap;
for (auto OffsetAndMember : SortedMembers) {
VALUE_TO_DECLARE_LOG("Member: %s at packed offset %d",
OffsetAndMember.second->getName().str().c_str(),
OffsetAndMember.first);
// Align the offsets to the member's type natural alignment. This
// should always result in the current aligned offset being the
// same as the member's offset.
m_Offsets.AlignTo(OffsetAndMember.second);
if (BaseTypeIfItIsBasicAndLarger(OffsetAndMember.second)) {
// This is the bitfields case (i.e. a field that is smaller
// than the type in which it resides). If we were to take
// the base type, then the information about the member's
// size would be lost
PopulateAllocaMap(OffsetAndMember.second);
} else {
if (OffsetAndMember.second->getAlignInBits() ==
OffsetAndMember.second->getSizeInBits()) {
assert(m_Offsets.GetCurrentAlignedOffset() ==
StructStart + OffsetAndMember.first &&
"Offset mismatch in DIStructType");
}
if (IsResourceObject(OffsetAndMember.second)) {
m_Offsets.AddResourceType(OffsetAndMember.second);
} else {
PopulateAllocaMap(
OffsetAndMember.second->getBaseType().resolve(EmptyMap));
}
}
}
}
// HLSL Change: remove unused function
#if 0
llvm::DILocation *VariableRegisters::GetVariableLocation() const
{
const unsigned DefaultColumn = 1;
return llvm::DILocation::get(
m_B.getContext(),
m_Variable->getLine(),
DefaultColumn,
m_Variable->getScope());
}
#endif
llvm::Value *VariableRegisters::GetMetadataAsValue(llvm::Metadata *M) const {
return llvm::MetadataAsValue::get(m_B.getContext(), M);
}
llvm::DIExpression *
VariableRegisters::GetDIExpression(llvm::DIType *Ty, OffsetInBits Offset,
SizeInBits ParentSize,
unsigned sizeOverride) const {
llvm::SmallVector<uint64_t, 3> ExpElements;
if (Offset != 0 || Ty->getSizeInBits() != ParentSize) {
ExpElements.emplace_back(llvm::dwarf::DW_OP_bit_piece);
ExpElements.emplace_back(Offset);
ExpElements.emplace_back(sizeOverride != 0 ? sizeOverride
: Ty->getSizeInBits());
}
return llvm::DIExpression::get(m_B.getContext(), ExpElements);
}
using namespace llvm;
INITIALIZE_PASS(DxilDbgValueToDbgDeclare, DEBUG_TYPE,
"Converts calls to dbg.value to dbg.declare + stores to new "
"virtual registers",
false, false)
ModulePass *llvm::createDxilDbgValueToDbgDeclarePass() {
return new DxilDbgValueToDbgDeclare();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/LLVMBuild.txt | ; Copyright (C) Microsoft Corporation. All rights reserved.
; This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DxilPIXPasses
parent = Libraries
required_libraries = BitReader Core DxcSupport TransformUtils Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/PixPassHelpers.h | ///////////////////////////////////////////////////////////////////////////////
// //
// PixPassHelpers.h
// // Copyright (C) Microsoft Corporation. All rights reserved. // This file is
// distributed under the University of Illinois Open Source // License. See
// LICENSE.TXT for details. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <vector>
#include "dxc/DXIL/DxilModule.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
//#define PIX_DEBUG_DUMP_HELPER
#ifdef PIX_DEBUG_DUMP_HELPER
#include "dxc/Support/Global.h"
#endif
namespace PIXPassHelpers {
class ScopedInstruction {
llvm::Instruction *m_Instruction;
public:
ScopedInstruction(llvm::Instruction *I) : m_Instruction(I) {}
~ScopedInstruction() { delete m_Instruction; }
llvm::Instruction *Get() const { return m_Instruction; }
};
void FindRayQueryHandlesForFunction(
llvm::Function *F, llvm::SmallPtrSetImpl<llvm::Value *> &RayQueryHandles);
enum class PixUAVHandleMode { NonLib, Lib };
llvm::CallInst *CreateUAVOnceForModule(hlsl::DxilModule &DM,
llvm::IRBuilder<> &Builder,
unsigned int hlslBindIndex,
const char *name);
hlsl::DxilResource *CreateGlobalUAVResource(hlsl::DxilModule &DM,
unsigned int hlslBindIndex,
const char *name);
llvm::CallInst *CreateHandleForResource(hlsl::DxilModule &DM,
llvm::IRBuilder<> &Builder,
hlsl::DxilResourceBase *resource,
const char *name);
llvm::Function *GetEntryFunction(hlsl::DxilModule &DM);
std::vector<llvm::BasicBlock *> GetAllBlocks(hlsl::DxilModule &DM);
std::vector<llvm::Function *>
GetAllInstrumentableFunctions(hlsl::DxilModule &DM);
hlsl::DXIL::ShaderKind GetFunctionShaderKind(hlsl::DxilModule &DM,
llvm::Function *fn);
#ifdef PIX_DEBUG_DUMP_HELPER
void Log(const char *format, ...);
void LogPartialLine(const char *format, ...);
void IncreaseLogIndent();
void DecreaseLogIndent();
void DumpFullType(llvm::DIType const *type);
#else
inline void DumpFullType(llvm::DIType const *) {}
inline void Log(const char *, ...) {}
inline void LogPartialLine(const char *format, ...) {}
inline void IncreaseLogIndent() {}
inline void DecreaseLogIndent() {}
#endif
class ScopedIndenter {
public:
ScopedIndenter() { IncreaseLogIndent(); }
~ScopedIndenter() { DecreaseLogIndent(); }
};
struct ExpandedStruct {
llvm::Type *ExpandedPayloadStructType = nullptr;
llvm::Type *ExpandedPayloadStructPtrType = nullptr;
};
ExpandedStruct ExpandStructType(llvm::LLVMContext &Ctx,
llvm::Type *OriginalPayloadStructType);
void ReplaceAllUsesOfInstructionWithNewValueAndDeleteInstruction(
llvm::Instruction *Instr, llvm::Value *newValue, llvm::Type *newType);
unsigned int FindOrAddSV_Position(hlsl::DxilModule &DM,
unsigned UpStreamSVPosRow);
} // namespace PIXPassHelpers
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilPIXPasses.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilPIXPasses.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides SetupRegistryPassForPIX. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/WinIncludes.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Pass.h"
#include "llvm/PassInfo.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;
using namespace hlsl;
namespace hlsl {
HRESULT SetupRegistryPassForPIX() {
try {
PassRegistry &Registry = *PassRegistry::getPassRegistry();
#include "DxilPIXPasses.inc"
}
CATCH_CPP_RETURN_HRESULT();
return S_OK;
}
} // namespace hlsl
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilAddPixelHitInstrumentation.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilAddPixelHitInstrumentation.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides a pass to add instrumentation to determine pixel hit count and //
// cost. Used by PIX. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Transforms/Utils/Local.h"
#include "PixPassHelpers.h"
using namespace llvm;
using namespace hlsl;
class DxilAddPixelHitInstrumentation : public ModulePass {
bool ForceEarlyZ = false;
bool AddPixelCost = false;
int RTWidth = 1024;
int NumPixels = 128;
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilAddPixelHitInstrumentation() : ModulePass(ID) {}
StringRef getPassName() const override {
return "DXIL Add Pixel Hit Instrumentation";
}
void applyOptions(PassOptions O) override;
bool runOnModule(Module &M) override;
unsigned m_upstreamSVPositionRow;
};
void DxilAddPixelHitInstrumentation::applyOptions(PassOptions O) {
GetPassOptionBool(O, "force-early-z", &ForceEarlyZ, false);
GetPassOptionBool(O, "add-pixel-cost", &AddPixelCost, false);
GetPassOptionInt(O, "rt-width", &RTWidth, 0);
GetPassOptionInt(O, "num-pixels", &NumPixels, 0);
GetPassOptionUnsigned(O, "upstream-sv-position-row", &m_upstreamSVPositionRow,
0);
}
bool DxilAddPixelHitInstrumentation::runOnModule(Module &M) {
// This pass adds instrumentation for pixel hit counting and pixel cost.
DxilModule &DM = M.GetOrCreateDxilModule();
LLVMContext &Ctx = M.getContext();
OP *HlslOP = DM.GetOP();
// ForceEarlyZ is incompatible with the discard function (the Z has to be
// tested/written, and may be written before the shader even runs)
if (ForceEarlyZ) {
DM.m_ShaderFlags.SetForceEarlyDepthStencil(true);
}
auto SV_Position_ID =
PIXPassHelpers::FindOrAddSV_Position(DM, m_upstreamSVPositionRow);
auto EntryPointFunction = PIXPassHelpers::GetEntryFunction(DM);
auto &EntryBlock = EntryPointFunction->getEntryBlock();
CallInst *HandleForUAV;
{
IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(
PIXPassHelpers::GetEntryFunction(DM)));
HandleForUAV = PIXPassHelpers::CreateUAVOnceForModule(
DM, Builder, 0, "PIX_CountUAV_Handle");
DM.ReEmitDxilResources();
}
// todo: is it a reasonable assumption that there will be a "Ret" in the entry
// block, and that these are the only points from which the shader can exit
// (except for a pixel-kill?)
auto &Instructions = EntryBlock.getInstList();
auto It = Instructions.begin();
while (It != Instructions.end()) {
auto ThisInstruction = It++;
LlvmInst_Ret Ret(ThisInstruction);
if (Ret) {
// Check that there is at least one instruction preceding the Ret (no need
// to instrument it if there isn't)
if (ThisInstruction->getPrevNode() != nullptr) {
// Start adding instructions right before the Ret:
IRBuilder<> Builder(ThisInstruction);
// ------------------------------------------------------------------------------------------------------------
// Generate instructions to increment (by one) a UAV value corresponding
// to the pixel currently being rendered
// ------------------------------------------------------------------------------------------------------------
// Useful constants
Constant *Zero32Arg = HlslOP->GetU32Const(0);
Constant *Zero8Arg = HlslOP->GetI8Const(0);
Constant *One32Arg = HlslOP->GetU32Const(1);
Constant *One8Arg = HlslOP->GetI8Const(1);
UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(Ctx));
Constant *NumPixelsByteOffsetArg = HlslOP->GetU32Const(NumPixels * 4);
// Step 1: Convert SV_POSITION to UINT
Value *XAsInt;
Value *YAsInt;
{
auto LoadInputOpFunc =
HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getFloatTy(Ctx));
Constant *LoadInputOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
Constant *SV_Pos_ID = HlslOP->GetU32Const(SV_Position_ID);
auto XPos =
Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
Zero8Arg /*column*/, UndefArg},
"XPos");
auto YPos =
Builder.CreateCall(LoadInputOpFunc,
{LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
One8Arg /*column*/, UndefArg},
"YPos");
XAsInt = Builder.CreateCast(Instruction::CastOps::FPToUI, XPos,
Type::getInt32Ty(Ctx), "XIndex");
YAsInt = Builder.CreateCast(Instruction::CastOps::FPToUI, YPos,
Type::getInt32Ty(Ctx), "YIndex");
}
// Step 2: Calculate pixel index
Value *Index;
{
Constant *RTWidthArg = HlslOP->GetI32Const(RTWidth);
auto YOffset = Builder.CreateMul(YAsInt, RTWidthArg, "YOffset");
auto Elementoffset =
Builder.CreateAdd(XAsInt, YOffset, "ElementOffset");
Index = Builder.CreateMul(Elementoffset, HlslOP->GetU32Const(4),
"ByteIndex");
}
// Insert the UAV increment instruction:
Function *AtomicOpFunc =
HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(Ctx));
Constant *AtomicBinOpcode =
HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
Constant *AtomicAdd =
HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
{
(void)Builder.CreateCall(
AtomicOpFunc,
{
AtomicBinOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD,
// AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
Index, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
UndefArg, // i32, ; coordinate c2 (unused)
One32Arg // i32); increment value
},
"UAVIncResult");
}
if (AddPixelCost) {
// ------------------------------------------------------------------------------------------------------------
// Generate instructions to increment a value corresponding to the
// current pixel in the second half of the UAV, by an amount
// proportional to the estimated average cost of each pixel in the
// current draw call.
// ------------------------------------------------------------------------------------------------------------
// Step 1: Retrieve weight value from UAV; it will be placed after the
// range we're writing to
Value *Weight;
{
Function *LoadWeight = HlslOP->GetOpFunc(OP::OpCode::BufferLoad,
Type::getInt32Ty(Ctx));
Constant *LoadWeightOpcode =
HlslOP->GetU32Const((unsigned)DXIL::OpCode::BufferLoad);
Constant *OffsetIntoUAV = HlslOP->GetU32Const(NumPixels * 2 * 4);
auto WeightStruct = Builder.CreateCall(
LoadWeight,
{
LoadWeightOpcode, // i32 opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
OffsetIntoUAV, // i32 c0: byte offset
UndefArg // i32 c1: unused
},
"WeightStruct");
Weight = Builder.CreateExtractValue(
WeightStruct, static_cast<uint64_t>(0LL), "Weight");
}
// Step 2: Update write position ("Index") to second half of the UAV
auto OffsetIndex = Builder.CreateAdd(Index, NumPixelsByteOffsetArg,
"OffsetByteIndex");
// Step 3: Increment UAV value by the weight
(void)Builder.CreateCall(
AtomicOpFunc,
{
AtomicBinOpcode, // i32, ; opcode
HandleForUAV, // %dx.types.Handle, ; resource handle
AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD,
// AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
OffsetIndex, // i32, ; coordinate c0: byte offset
UndefArg, // i32, ; coordinate c1 (unused)
UndefArg, // i32, ; coordinate c2 (unused)
Weight // i32); increment value
},
"UAVIncResult2");
}
}
}
}
bool Modified = false;
return Modified;
}
char DxilAddPixelHitInstrumentation::ID = 0;
ModulePass *llvm::createDxilAddPixelHitInstrumentationPass() {
return new DxilAddPixelHitInstrumentation();
}
INITIALIZE_PASS(DxilAddPixelHitInstrumentation,
"hlsl-dxil-add-pixel-hit-instrmentation",
"DXIL Count completed PS invocations and costs", false, false)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DxilPIXPasses/DxilAnnotateWithVirtualRegister.cpp | ///////////////////////////////////////////////////////////////////////////////
// //
// DxilAnnotateWithVirtualRegister.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Annotates the llvm instructions with a virtual register number to be used //
// during PIX debugging. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <memory>
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilPIXPasses/DxilPIXPasses.h"
#include "dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "PixPassHelpers.h"
#define DEBUG_TYPE "dxil-annotate-with-virtual-regs"
uint32_t CountStructMembers(llvm::Type const *pType) {
uint32_t Count = 0;
if (auto *VT = llvm::dyn_cast<llvm::VectorType>(pType)) {
// Vector types can only contain scalars:
Count = VT->getVectorNumElements();
} else if (auto *ST = llvm::dyn_cast<llvm::StructType>(pType)) {
for (auto &El : ST->elements()) {
Count += CountStructMembers(El);
}
} else if (auto *AT = llvm::dyn_cast<llvm::ArrayType>(pType)) {
Count = CountStructMembers(AT->getArrayElementType()) *
AT->getArrayNumElements();
} else {
Count = 1;
}
return Count;
}
namespace {
using namespace pix_dxil;
static bool IsInstrumentableFundamentalType(llvm::Type *pAllocaTy) {
return pAllocaTy->isFloatingPointTy() || pAllocaTy->isIntegerTy();
}
class DxilAnnotateWithVirtualRegister : public llvm::ModulePass {
public:
static char ID;
DxilAnnotateWithVirtualRegister() : llvm::ModulePass(ID) {}
bool runOnModule(llvm::Module &M) override;
void applyOptions(llvm::PassOptions O) override;
private:
void AnnotateValues(llvm::Instruction *pI);
void AnnotateStore(llvm::Instruction *pI);
bool IsAllocaRegisterWrite(llvm::Value *V, llvm::AllocaInst **pAI,
llvm::Value **pIdx);
void AnnotateAlloca(llvm::AllocaInst *pAlloca);
void AnnotateGeneric(llvm::Instruction *pI);
void AssignNewDxilRegister(llvm::Instruction *pI);
void AssignNewAllocaRegister(llvm::AllocaInst *pAlloca, std::uint32_t C);
hlsl::DxilModule *m_DM;
std::uint32_t m_uVReg;
std::unique_ptr<llvm::ModuleSlotTracker> m_MST;
int m_StartInstruction = 0;
void Init(llvm::Module &M) {
m_DM = &M.GetOrCreateDxilModule();
m_uVReg = 0;
m_MST.reset(new llvm::ModuleSlotTracker(&M));
auto functions = m_DM->GetExportedFunctions();
for (auto &fn : functions) {
m_MST->incorporateFunction(*fn);
}
}
};
void DxilAnnotateWithVirtualRegister::applyOptions(llvm::PassOptions O) {
GetPassOptionInt(O, "startInstruction", &m_StartInstruction, 0);
}
char DxilAnnotateWithVirtualRegister::ID = 0;
static llvm::StringRef
PrintableSubsetOfMangledFunctionName(llvm::StringRef mangled) {
llvm::StringRef printableNameSubset = mangled;
if (mangled.size() > 2 && mangled[0] == '\1' && mangled[1] == '?') {
printableNameSubset =
llvm::StringRef(mangled.data() + 2, mangled.size() - 2);
}
return printableNameSubset;
}
bool DxilAnnotateWithVirtualRegister::runOnModule(llvm::Module &M) {
Init(M);
if (m_DM == nullptr) {
return false;
}
unsigned int Major = 0;
unsigned int Minor = 0;
m_DM->GetValidatorVersion(Major, Minor);
if (hlsl::DXIL::CompareVersions(Major, Minor, 1, 4) < 0) {
m_DM->SetValidatorVersion(1, 4);
}
std::uint32_t InstNum = m_StartInstruction;
auto instrumentableFunctions =
PIXPassHelpers::GetAllInstrumentableFunctions(*m_DM);
for (auto *F : instrumentableFunctions) {
for (auto &block : F->getBasicBlockList()) {
for (llvm::Instruction &I : block.getInstList()) {
AnnotateValues(&I);
}
}
}
for (auto *F : instrumentableFunctions) {
for (auto &block : F->getBasicBlockList()) {
for (llvm::Instruction &I : block.getInstList()) {
AnnotateStore(&I);
}
}
}
for (auto *F : instrumentableFunctions) {
int InstructionRangeStart = InstNum;
int InstructionRangeEnd = InstNum;
for (auto &block : F->getBasicBlockList()) {
for (llvm::Instruction &I : block.getInstList()) {
// If the instruction is part of the debug value instrumentation added
// by this pass, it doesn't need to be instrumented for the PIX user.
uint32_t unused1, unused2;
if (auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(&I))
if (PixAllocaReg::FromInst(Alloca, &unused1, &unused2))
continue;
if (!llvm::isa<llvm::DbgDeclareInst>(&I)) {
pix_dxil::PixDxilInstNum::AddMD(M.getContext(), &I, InstNum++);
InstructionRangeEnd = InstNum;
}
}
}
if (OSOverride != nullptr) {
auto shaderKind = PIXPassHelpers::GetFunctionShaderKind(*m_DM, F);
std::string FunctioNamePlusKind =
F->getName().str() + " " + hlsl::ShaderModel::GetKindName(shaderKind);
*OSOverride << "InstructionRange: ";
llvm::StringRef printableNameSubset =
PrintableSubsetOfMangledFunctionName(FunctioNamePlusKind);
*OSOverride << InstructionRangeStart << " " << InstructionRangeEnd << " "
<< printableNameSubset << "\n";
}
}
if (OSOverride != nullptr) {
// Print a set of strings of the exemplary form "InstructionCount: <n>
// <fnName>"
if (m_DM->GetShaderModel()->GetKind() == hlsl::ShaderModel::Kind::Library)
*OSOverride << "\nIsLibrary\n";
*OSOverride << "\nInstructionCount:" << InstNum << "\n";
}
m_DM = nullptr;
return m_uVReg > 0;
}
void DxilAnnotateWithVirtualRegister::AnnotateValues(llvm::Instruction *pI) {
if (auto *pAlloca = llvm::dyn_cast<llvm::AllocaInst>(pI)) {
AnnotateAlloca(pAlloca);
} else if (!pI->getType()->isPointerTy()) {
AnnotateGeneric(pI);
} else if (!pI->getType()->isVoidTy()) {
AnnotateGeneric(pI);
}
}
void DxilAnnotateWithVirtualRegister::AnnotateStore(llvm::Instruction *pI) {
auto *pSt = llvm::dyn_cast<llvm::StoreInst>(pI);
if (pSt == nullptr) {
return;
}
llvm::AllocaInst *Alloca;
llvm::Value *Index;
if (!IsAllocaRegisterWrite(pSt->getPointerOperand(), &Alloca, &Index)) {
return;
}
llvm::MDNode *AllocaReg = Alloca->getMetadata(PixAllocaReg::MDName);
if (AllocaReg == nullptr) {
return;
}
PixAllocaRegWrite::AddMD(m_DM->GetCtx(), pSt, AllocaReg, Index);
}
static uint32_t GetStructOffset(llvm::GetElementPtrInst *pGEP,
uint32_t &GEPOperandIndex,
llvm::Type *pElementType) {
if (IsInstrumentableFundamentalType(pElementType)) {
return 0;
} else if (auto *pArray = llvm::dyn_cast<llvm::ArrayType>(pElementType)) {
// 1D-array example:
//
// When referring to the zeroth member of the array in this struct:
// struct smallPayload {
// uint32_t Array[2];
// };
// getelementptr inbounds% struct.smallPayload, % struct.smallPayload*% p,
// i32 0, i32 0, i32 0 The zeros above are:
// -The zeroth element in the array pointed to (so, the actual struct)
// -The zeroth element in the struct (which is the array)
// -The zeroth element in that array
auto *pArrayIndex =
llvm::dyn_cast<llvm::ConstantInt>(pGEP->getOperand(GEPOperandIndex++));
if (pArrayIndex == nullptr) {
return 0;
}
uint32_t ArrayIndex = pArrayIndex->getLimitedValue();
auto pArrayElementType = pArray->getArrayElementType();
uint32_t MemberIndex = ArrayIndex * CountStructMembers(pArrayElementType);
return MemberIndex +
GetStructOffset(pGEP, GEPOperandIndex, pArrayElementType);
} else if (auto *pStruct = llvm::dyn_cast<llvm::StructType>(pElementType)) {
DXASSERT(GEPOperandIndex < pGEP->getNumOperands(),
"Unexpectedly read too many GetElementPtrInst operands");
auto *pMemberIndex =
llvm::dyn_cast<llvm::ConstantInt>(pGEP->getOperand(GEPOperandIndex++));
if (pMemberIndex == nullptr) {
return 0;
}
uint32_t MemberIndex = pMemberIndex->getLimitedValue();
uint32_t MemberOffset = 0;
for (uint32_t i = 0; i < MemberIndex; ++i) {
MemberOffset += CountStructMembers(pStruct->getElementType(i));
}
return MemberOffset + GetStructOffset(pGEP, GEPOperandIndex,
pStruct->getElementType(MemberIndex));
} else {
return 0;
}
}
bool DxilAnnotateWithVirtualRegister::IsAllocaRegisterWrite(
llvm::Value *V, llvm::AllocaInst **pAI, llvm::Value **pIdx) {
llvm::IRBuilder<> B(m_DM->GetCtx());
*pAI = nullptr;
*pIdx = nullptr;
if (auto *pGEP = llvm::dyn_cast<llvm::GetElementPtrInst>(V)) {
uint32_t precedingMemberCount = 0;
auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(pGEP->getPointerOperand());
if (Alloca == nullptr) {
// In the case of vector types (floatN, matrixNxM), the pointer operand
// will actually point to another element pointer instruction. But this
// isn't a recursive thing- we only need to check these two levels.
if (auto *pPointerGEP = llvm::dyn_cast<llvm::GetElementPtrInst>(
pGEP->getPointerOperand())) {
Alloca =
llvm::dyn_cast<llvm::AllocaInst>(pPointerGEP->getPointerOperand());
if (Alloca == nullptr) {
return false;
}
// And of course the member we're after might not be at the beginning of
// the struct:
auto *pStructType = llvm::dyn_cast<llvm::StructType>(
pPointerGEP->getPointerOperandType()->getPointerElementType());
auto *pStructMember =
llvm::dyn_cast<llvm::ConstantInt>(pPointerGEP->getOperand(2));
uint64_t memberIndex = pStructMember->getLimitedValue();
for (uint64_t i = 0; i < memberIndex; ++i) {
precedingMemberCount +=
CountStructMembers(pStructType->getStructElementType(i));
}
} else {
return false;
}
}
// Deref pointer type to get struct type:
llvm::Type *pStructType = pGEP->getPointerOperandType();
pStructType = pStructType->getContainedType(0);
// The 1th operand is an index into the array of the above type. In DXIL
// derived from HLSL, we always expect this to be 0 (since llvm structs are
// only used for single-valued objects in HLSL, such as the
// amplification-to-mesh or TraceRays payloads).
uint32_t GEPOperandIndex = 1;
auto *pBaseArrayIndex =
llvm::dyn_cast<llvm::ConstantInt>(pGEP->getOperand(GEPOperandIndex++));
DXASSERT_LOCALVAR(pBaseArrayIndex, pBaseArrayIndex != nullptr,
"null base array index pointer");
DXASSERT_LOCALVAR(pBaseArrayIndex, pBaseArrayIndex->getLimitedValue() == 0,
"unexpected >0 array index");
// From here on, the indices always come in groups: first, the type
// referenced in the current struct. If that type is an (n-dimensional)
// array, then there follow n indices.
auto offset = GetStructOffset(pGEP, GEPOperandIndex, pStructType);
llvm::Value *IndexValue = B.getInt32(offset + precedingMemberCount);
if (IndexValue != nullptr) {
*pAI = Alloca;
*pIdx = IndexValue;
return true;
}
return false;
}
if (auto *pAlloca = llvm::dyn_cast<llvm::AllocaInst>(V)) {
llvm::Type *pAllocaTy = pAlloca->getType()->getElementType();
if (!IsInstrumentableFundamentalType(pAllocaTy)) {
return false;
}
*pAI = pAlloca;
*pIdx = B.getInt32(0);
return true;
}
return false;
}
void DxilAnnotateWithVirtualRegister::AnnotateAlloca(
llvm::AllocaInst *pAlloca) {
llvm::Type *pAllocaTy = pAlloca->getType()->getElementType();
if (IsInstrumentableFundamentalType(pAllocaTy)) {
AssignNewAllocaRegister(pAlloca, 1);
} else if (auto *AT = llvm::dyn_cast<llvm::ArrayType>(pAllocaTy)) {
AssignNewAllocaRegister(pAlloca, AT->getNumElements());
} else if (auto *ST = llvm::dyn_cast<llvm::StructType>(pAllocaTy)) {
AssignNewAllocaRegister(pAlloca, CountStructMembers(ST));
} else {
DXASSERT_ARGS(false, "Unhandled alloca kind: %d", pAllocaTy->getTypeID());
}
}
void DxilAnnotateWithVirtualRegister::AnnotateGeneric(llvm::Instruction *pI) {
if (auto *GEP = llvm::dyn_cast<llvm::GetElementPtrInst>(pI)) {
// https://llvm.org/docs/LangRef.html#getelementptr-instruction
DXASSERT(!GEP->getOperand(1)->getType()->isVectorTy(),
"struct vectors not supported");
llvm::AllocaInst *StructAlloca =
llvm::dyn_cast<llvm::AllocaInst>(GEP->getOperand(0));
if (StructAlloca != nullptr) {
// This is the case of a pointer to a struct member.
// We treat it as an alias of the actual member in the alloca.
std::uint32_t baseStructRegNum = 0;
std::uint32_t regSize = 0;
if (pix_dxil::PixAllocaReg::FromInst(StructAlloca, &baseStructRegNum,
®Size)) {
llvm::ConstantInt *OffsetAsInt =
llvm::dyn_cast<llvm::ConstantInt>(GEP->getOperand(2));
if (OffsetAsInt != nullptr) {
std::uint32_t OffsetInElementsFromStructureStart =
static_cast<std::uint32_t>(
OffsetAsInt->getValue().getLimitedValue());
DXASSERT(OffsetInElementsFromStructureStart < regSize,
"Structure member offset out of expected range");
std::uint32_t OffsetInValuesFromStructureStart =
OffsetInElementsFromStructureStart;
if (auto *ST = llvm::dyn_cast<llvm::StructType>(
GEP->getPointerOperandType()->getPointerElementType())) {
DXASSERT(OffsetInElementsFromStructureStart < ST->getNumElements(),
"Offset into struct is bigger than struct");
OffsetInValuesFromStructureStart = 0;
for (std::uint32_t Element = 0;
Element < OffsetInElementsFromStructureStart; ++Element) {
OffsetInValuesFromStructureStart +=
CountStructMembers(ST->getElementType(Element));
}
}
PixDxilReg::AddMD(m_DM->GetCtx(), pI,
baseStructRegNum +
OffsetInValuesFromStructureStart);
}
}
}
} else {
if (!IsInstrumentableFundamentalType(pI->getType())) {
return;
}
AssignNewDxilRegister(pI);
}
}
void DxilAnnotateWithVirtualRegister::AssignNewDxilRegister(
llvm::Instruction *pI) {
PixDxilReg::AddMD(m_DM->GetCtx(), pI, m_uVReg);
m_uVReg++;
}
void DxilAnnotateWithVirtualRegister::AssignNewAllocaRegister(
llvm::AllocaInst *pAlloca, std::uint32_t C) {
PixAllocaReg::AddMD(m_DM->GetCtx(), pAlloca, m_uVReg, C);
m_uVReg += C;
}
} // namespace
using namespace llvm;
INITIALIZE_PASS(DxilAnnotateWithVirtualRegister, DEBUG_TYPE,
"Annotates each instruction in the DXIL module with a virtual "
"register number",
false, false)
ModulePass *llvm::createDxilAnnotateWithVirtualRegisterPass() {
return new DxilAnnotateWithVirtualRegister();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.