Skip to content

Commit f729c49

Browse files
authored
Add ability to preserve all function metadata and attributes from LLVM-IR
Initial implementation of function metadata and attribute preservation In Intel's SYCL compiler, we have a use case where we need to convert to SPIR-V and then back to LLVM-IR and preserve all function metadata and attributes. The metadata and attributes we need to preserve have no value outside an internal stage of Intel's SYCL compiler and are not good fits for SPIR-V extensions. The list of what is needed is very volatile as well. To implement generic support in the translator, the general approach is to use SPV_KHR_non_semantic_info to add a new nonsemantic EIS, named NonSemantic.AuxData This new instruction set has two instructions: NonSemanticAuxDataFunctionMetadata and NonSemanticAuxDataFunctionAttribute Both instructions will be placed outside of the function CFG and take in what function to target as an operand, similar to debuginfo. We do this to support function declarations. The operands after the function to target are either strings or values describing the metadata or attribute. Specific information can be found in the SPIRVWriter.cpp changes. I also added a new option, --spirv-preserve-auxdata to preserve these. If a flag is passed for translation to SPIR-V the respective information will be preserved as described above. The flag is also required for reverse translation. If it not provided, it will be dropped as allowed in the spec. In order to handle the case of some metadata/attributes being handled manually (maybe we have metadata "foo=bar" in LLVM-IR, but we translate to "foo=oof" for some reason in SPIR-V (and thus reverse translation)), we process these new instructions very late in reverse translation, and if the metadata or attribute already exists, we skip it. Signed-off-by: Sarnie, Nick <[email protected]>
1 parent b30a2d2 commit f729c49

16 files changed

+339
-6
lines changed

include/LLVMSPIRVOpts.h

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ enum class DebugInfoEIS : uint32_t {
9090
/// \brief Helper class to manage SPIR-V translation
9191
class TranslatorOpts {
9292
public:
93-
using ExtensionsStatusMap = std::map<ExtensionID, bool>;
93+
// Unset optional means not directly specified by user
94+
using ExtensionsStatusMap = std::map<ExtensionID, std::optional<bool>>;
95+
9496
using ArgList = llvm::SmallVector<llvm::StringRef, 4>;
9597

9698
TranslatorOpts() = default;
@@ -107,11 +109,14 @@ class TranslatorOpts {
107109
if (ExtStatusMap.end() == I)
108110
return false;
109111

110-
return I->second;
112+
return I->second && *I->second;
111113
}
112114

113115
void setAllowedToUseExtension(ExtensionID Extension, bool Allow = true) {
114-
ExtStatusMap[Extension] = Allow;
116+
// Only allow using the extension if it has not already been disabled
117+
auto I = ExtStatusMap.find(Extension);
118+
if (I == ExtStatusMap.end() || !I->second || (*I->second) == true)
119+
ExtStatusMap[Extension] = Allow;
115120
}
116121

117122
VersionNumber getMaxVersion() const { return MaxVersion; }
@@ -122,6 +127,10 @@ class TranslatorOpts {
122127

123128
void setMemToRegEnabled(bool Mem2Reg) { SPIRVMemToReg = Mem2Reg; }
124129

130+
bool preserveAuxData() const { return PreserveAuxData; }
131+
132+
void setPreserveAuxData(bool ArgValue) { PreserveAuxData = ArgValue; }
133+
125134
void setGenKernelArgNameMDEnabled(bool ArgNameMD) {
126135
GenKernelArgNameMD = ArgNameMD;
127136
}
@@ -230,6 +239,8 @@ class TranslatorOpts {
230239
// Add a workaround to preserve OpenCL kernel_arg_type and
231240
// kernel_arg_type_qual metadata through OpString
232241
bool PreserveOCLKernelArgTypeMetadataThroughString = false;
242+
243+
bool PreserveAuxData = false;
233244
};
234245

235246
} // namespace SPIRV

lib/SPIRV/SPIRVReader.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3380,6 +3380,11 @@ bool SPIRVToLLVM::translate() {
33803380

33813381
DbgTran->addDbgInfoVersion();
33823382
DbgTran->finalize();
3383+
3384+
for (SPIRVExtInst *EI : BM->getAuxDataInstVec()) {
3385+
transAuxDataInst(EI);
3386+
}
3387+
33833388
return true;
33843389
}
33853390

@@ -4509,6 +4514,60 @@ Instruction *SPIRVToLLVM::transOCLBuiltinFromExtInst(SPIRVExtInst *BC,
45094514
return CI;
45104515
}
45114516

4517+
void SPIRVToLLVM::transAuxDataInst(SPIRVExtInst *BC) {
4518+
assert(BC->getExtSetKind() == SPIRV::SPIRVEIS_NonSemantic_AuxData);
4519+
if (!BC->getModule()->preserveAuxData())
4520+
return;
4521+
auto Args = BC->getArguments();
4522+
// Args 0 and 1 are common between attributes and metadata.
4523+
// 0 is the function, 1 is the name of the attribute/metadata as a string
4524+
auto *SpvFcn = BC->getModule()->getValue(Args[0]);
4525+
auto *F = static_cast<Function *>(getTranslatedValue(SpvFcn));
4526+
assert(F && "Function should already have been translated!");
4527+
auto AttrOrMDName = BC->getModule()->get<SPIRVString>(Args[1])->getStr();
4528+
switch (BC->getExtOp()) {
4529+
case NonSemanticAuxData::FunctionAttribute: {
4530+
assert(Args.size() < 4 && "Unexpected FunctionAttribute Args");
4531+
// If this attr was specially handled and added elsewhere, skip it.
4532+
if (F->hasFnAttribute(AttrOrMDName))
4533+
return;
4534+
// For attributes, arg 2 is the attribute value as a string, which may not
4535+
// exist.
4536+
if (Args.size() == 3) {
4537+
auto AttrValue = BC->getModule()->get<SPIRVString>(Args[2])->getStr();
4538+
F->addFnAttr(AttrOrMDName, AttrValue);
4539+
} else {
4540+
F->addFnAttr(AttrOrMDName);
4541+
}
4542+
break;
4543+
}
4544+
case NonSemanticAuxData::FunctionMetadata: {
4545+
// If this metadata was specially handled and added elsewhere, skip it.
4546+
if (F->hasMetadata(AttrOrMDName))
4547+
return;
4548+
SmallVector<Metadata *> MetadataArgs;
4549+
// Process the metadata values.
4550+
for (size_t CurArg = 2; CurArg < Args.size(); CurArg++) {
4551+
auto *Arg = BC->getModule()->get<SPIRVEntry>(Args[CurArg]);
4552+
// For metadata, the metadata values can be either values or strings.
4553+
if (Arg->getOpCode() == OpString) {
4554+
auto *ArgAsStr = static_cast<SPIRVString *>(Arg);
4555+
MetadataArgs.push_back(
4556+
MDString::get(F->getContext(), ArgAsStr->getStr()));
4557+
} else {
4558+
auto *ArgAsVal = static_cast<SPIRVValue *>(Arg);
4559+
auto *TranslatedMD = transValue(ArgAsVal, F, nullptr);
4560+
MetadataArgs.push_back(ValueAsMetadata::get(TranslatedMD));
4561+
}
4562+
}
4563+
F->setMetadata(AttrOrMDName, MDNode::get(*Context, MetadataArgs));
4564+
break;
4565+
}
4566+
default:
4567+
llvm_unreachable("Invalid op");
4568+
}
4569+
}
4570+
45124571
// SPIR-V only contains language version. Use OpenCL language version as
45134572
// SPIR version.
45144573
void SPIRVToLLVM::transSourceLanguage() {

lib/SPIRV/SPIRVReader.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ class SPIRVToLLVM : private BuiltinCallHelper {
100100
bool transDecoration(SPIRVValue *, Value *);
101101
bool transAlign(SPIRVValue *, Value *);
102102
Instruction *transOCLBuiltinFromExtInst(SPIRVExtInst *BC, BasicBlock *BB);
103+
void transAuxDataInst(SPIRVExtInst *BC);
103104
std::vector<Value *> transValue(const std::vector<SPIRVValue *> &,
104105
Function *F, BasicBlock *);
105106
Function *transFunction(SPIRVFunction *F);

lib/SPIRV/SPIRVWriter.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,8 @@ SPIRVFunction *LLVMToSPIRVBase::transFunctionDecl(Function *F) {
966966

967967
transFunctionMetadataAsUserSemanticDecoration(BF, F);
968968

969+
transAuxDataInst(BF, F);
970+
969971
SPIRVDBG(dbgs() << "[transFunction] " << *F << " => ";
970972
spvdbgs() << *BF << '\n';)
971973
return BF;
@@ -1119,6 +1121,72 @@ void LLVMToSPIRVBase::transFunctionMetadataAsUserSemanticDecoration(
11191121
}
11201122
}
11211123

1124+
void LLVMToSPIRVBase::transAuxDataInst(SPIRVFunction *BF, Function *F) {
1125+
auto *BM = BF->getModule();
1126+
if (!BM->preserveAuxData())
1127+
return;
1128+
BM->addExtension(SPIRV::ExtensionID::SPV_KHR_non_semantic_info);
1129+
const auto &FnAttrs = F->getAttributes().getFnAttrs();
1130+
for (const auto &Attr : FnAttrs) {
1131+
std::vector<SPIRVWord> Ops;
1132+
Ops.push_back(BF->getId());
1133+
if (Attr.isStringAttribute()) {
1134+
// Format for String attributes is:
1135+
// NonSemanticAuxDataFunctionAttribute Fcn AttrName AttrValue
1136+
// or, if no value:
1137+
// NonSemanticAuxDataFunctionAttribute Fcn AttrName
1138+
//
1139+
// AttrName and AttrValue are always Strings
1140+
StringRef AttrKind = Attr.getKindAsString();
1141+
StringRef AttrValue = Attr.getValueAsString();
1142+
auto *KindSpvString = BM->getString(AttrKind.str());
1143+
Ops.push_back(KindSpvString->getId());
1144+
if (!AttrValue.empty()) {
1145+
auto *ValueSpvString = BM->getString(AttrValue.str());
1146+
Ops.push_back(ValueSpvString->getId());
1147+
}
1148+
} else {
1149+
// Format for other types is:
1150+
// NonSemanticAuxDataFunctionAttribute Fcn AttrStr
1151+
// AttrStr is always a String.
1152+
std::string AttrStr = Attr.getAsString();
1153+
auto *AttrSpvString = BM->getString(AttrStr);
1154+
Ops.push_back(AttrSpvString->getId());
1155+
}
1156+
BM->addAuxData(NonSemanticAuxData::FunctionAttribute,
1157+
transType(Type::getVoidTy(F->getContext())), Ops);
1158+
}
1159+
SmallVector<std::pair<unsigned, MDNode *>> AllMD;
1160+
SmallVector<StringRef> MDNames;
1161+
F->getContext().getMDKindNames(MDNames);
1162+
F->getAllMetadata(AllMD);
1163+
for (auto MD : AllMD) {
1164+
// Format for metadata is:
1165+
// NonSemanticAuxDataFunctionMetadata Fcn MDName MDVals...
1166+
// MDName is always a String, MDVals have different types as explained
1167+
// below. Also note this instruction has a variable number of operands
1168+
std::vector<SPIRVWord> Ops;
1169+
Ops.push_back(BF->getId());
1170+
Ops.push_back(BM->getString(MDNames[MD.first].str())->getId());
1171+
for (unsigned int OpIdx = 0; OpIdx < MD.second->getNumOperands(); OpIdx++) {
1172+
const auto &CurOp = MD.second->getOperand(OpIdx);
1173+
if (auto *MDStr = dyn_cast<MDString>(CurOp)) {
1174+
// For MDString, MDVal is String
1175+
auto *SPIRVStr = BM->getString(MDStr->getString().str());
1176+
Ops.push_back(SPIRVStr->getId());
1177+
} else if (auto *ValueAsMeta = dyn_cast<ValueAsMetadata>(CurOp)) {
1178+
// For Value metadata, MDVal is a SPIRVValue
1179+
auto *SPIRVVal = transValue(ValueAsMeta->getValue(), nullptr);
1180+
Ops.push_back(SPIRVVal->getId());
1181+
} else {
1182+
assert(false && "Unsupported metadata type");
1183+
}
1184+
}
1185+
BM->addAuxData(NonSemanticAuxData::FunctionMetadata,
1186+
transType(Type::getVoidTy(F->getContext())), Ops);
1187+
}
1188+
}
1189+
11221190
SPIRVValue *LLVMToSPIRVBase::transConstantUse(Constant *C) {
11231191
// Constant expressions expect their pointer types to be i8* in opaque pointer
11241192
// mode, but the value may have a different "natural" type. If that is the
@@ -2761,6 +2829,11 @@ bool LLVMToSPIRVBase::transBuiltinSet() {
27612829
SPIRVBuiltinSetNameMap::map(BM->getDebugInfoEIS()), &EISId))
27622830
return false;
27632831
}
2832+
if (BM->preserveAuxData()) {
2833+
if (!BM->importBuiltinSet(
2834+
SPIRVBuiltinSetNameMap::map(SPIRVEIS_NonSemantic_AuxData), &EISId))
2835+
return false;
2836+
}
27642837
return true;
27652838
}
27662839

lib/SPIRV/SPIRVWriter.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ class LLVMToSPIRVBase : protected BuiltinCallHelper {
124124
void transFPGAFunctionMetadata(SPIRVFunction *BF, Function *F);
125125
void transFunctionMetadataAsUserSemanticDecoration(SPIRVFunction *BF,
126126
Function *F);
127+
void transAuxDataInst(SPIRVFunction *BF, Function *F);
128+
127129
bool transGlobalVariables();
128130

129131
Op transBoolOpCode(SPIRVValue *Opn, Op OC);
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
** Copyright (c) 2023 The Khronos Group Inc.
3+
**
4+
** Permission is hereby granted, free of charge, to any person obtaining a copy
5+
** of this software and/or associated documentation files (the "Materials"),
6+
** to deal in the Materials without restriction, including without limitation
7+
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
8+
** and/or sell copies of the Materials, and to permit persons to whom the
9+
** Materials are furnished to do so, subject to the following conditions:
10+
**
11+
** The above copyright notice and this permission notice shall be included in
12+
** all copies or substantial portions of the Materials.
13+
**
14+
** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
15+
** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
16+
** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
17+
**
18+
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19+
** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21+
** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23+
** FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
24+
** IN THE MATERIALS.
25+
*/
26+
27+
namespace NonSemanticAuxData {
28+
enum Instruction {
29+
FunctionMetadata = 0,
30+
FunctionAttribute = 1,
31+
PreserveCount = 2
32+
};
33+
} // namespace NonSemanticAuxData

lib/SPIRV/libSPIRV/SPIRVEnum.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ enum SPIRVExtInstSetKind {
8080
SPIRVEIS_OpenCL_DebugInfo_100,
8181
SPIRVEIS_NonSemantic_Shader_DebugInfo_100,
8282
SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
83+
SPIRVEIS_NonSemantic_AuxData,
8384
SPIRVEIS_Count,
8485
};
8586

@@ -135,6 +136,7 @@ template <> inline void SPIRVMap<SPIRVExtInstSetKind, std::string>::init() {
135136
"NonSemantic.Shader.DebugInfo.100");
136137
add(SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
137138
"NonSemantic.Shader.DebugInfo.200");
139+
add(SPIRVEIS_NonSemantic_AuxData, "NonSemantic.AuxData");
138140
}
139141
typedef SPIRVMap<SPIRVExtInstSetKind, std::string> SPIRVBuiltinSetNameMap;
140142

lib/SPIRV/libSPIRV/SPIRVExtInst.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
#ifndef SPIRV_LIBSPIRV_SPIRVEXTINST_H
4141
#define SPIRV_LIBSPIRV_SPIRVEXTINST_H
4242

43+
#include "NonSemantic.AuxData.h"
4344
#include "OpenCL.std.h"
4445
#include "SPIRV.debug.h"
4546
#include "SPIRVEnum.h"
@@ -263,6 +264,16 @@ template <> inline void SPIRVMap<SPIRVDebugExtOpKind, std::string>::init() {
263264
}
264265
SPIRV_DEF_NAMEMAP(SPIRVDebugExtOpKind, SPIRVDebugExtOpMap)
265266

267+
typedef NonSemanticAuxData::Instruction NonSemanticAuxDataOpKind;
268+
template <>
269+
inline void SPIRVMap<NonSemanticAuxDataOpKind, std::string>::init() {
270+
add(NonSemanticAuxData::FunctionMetadata,
271+
"NonSemanticAuxDataFunctionMetadata");
272+
add(NonSemanticAuxData::FunctionAttribute,
273+
"NonSemanticAuxDataFunctionAttribute");
274+
}
275+
SPIRV_DEF_NAMEMAP(NonSemanticAuxDataOpKind, NonSemanticAuxDataOpMap)
276+
266277
} // namespace SPIRV
267278

268279
#endif // SPIRV_LIBSPIRV_SPIRVEXTINST_H

lib/SPIRV/libSPIRV/SPIRVInstruction.h

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242

4343
#include "SPIRVBasicBlock.h"
4444
#include "SPIRVEnum.h"
45+
#include "SPIRVFunction.h"
4546
#include "SPIRVIsValidEnum.h"
4647
#include "SPIRVOpCode.h"
4748
#include "SPIRVStream.h"
@@ -1763,7 +1764,8 @@ class SPIRVExtInst : public SPIRVFunctionCallGeneric<OpExtInst, 5> {
17631764
assert((ExtSetKind == SPIRVEIS_OpenCL || ExtSetKind == SPIRVEIS_Debug ||
17641765
ExtSetKind == SPIRVEIS_OpenCL_DebugInfo_100 ||
17651766
ExtSetKind == SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
1766-
ExtSetKind == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) &&
1767+
ExtSetKind == SPIRVEIS_NonSemantic_Shader_DebugInfo_200 ||
1768+
ExtSetKind == SPIRVEIS_NonSemantic_AuxData) &&
17671769
"not supported");
17681770
}
17691771
void encode(spv_ostream &O) const override {
@@ -1778,6 +1780,9 @@ class SPIRVExtInst : public SPIRVFunctionCallGeneric<OpExtInst, 5> {
17781780
case SPIRVEIS_NonSemantic_Shader_DebugInfo_200:
17791781
getEncoder(O) << ExtOpDebug;
17801782
break;
1783+
case SPIRVEIS_NonSemantic_AuxData:
1784+
getEncoder(O) << ExtOpNonSemanticAuxData;
1785+
break;
17811786
default:
17821787
assert(0 && "not supported");
17831788
getEncoder(O) << ExtOp;
@@ -1797,6 +1802,9 @@ class SPIRVExtInst : public SPIRVFunctionCallGeneric<OpExtInst, 5> {
17971802
case SPIRVEIS_NonSemantic_Shader_DebugInfo_200:
17981803
getDecoder(I) >> ExtOpDebug;
17991804
break;
1805+
case SPIRVEIS_NonSemantic_AuxData:
1806+
getDecoder(I) >> ExtOpNonSemanticAuxData;
1807+
break;
18001808
default:
18011809
assert(0 && "not supported");
18021810
getDecoder(I) >> ExtOp;
@@ -1842,13 +1850,20 @@ class SPIRVExtInst : public SPIRVFunctionCallGeneric<OpExtInst, 5> {
18421850
return ArgTypes;
18431851
}
18441852

1853+
std::optional<ExtensionID> getRequiredExtension() const override {
1854+
if (SPIRVBuiltinSetNameMap::map(ExtSetKind).find("NonSemantic.") == 0)
1855+
return ExtensionID::SPV_KHR_non_semantic_info;
1856+
return {};
1857+
}
1858+
18451859
protected:
18461860
SPIRVExtInstSetKind ExtSetKind;
18471861
SPIRVId ExtSetId;
18481862
union {
18491863
SPIRVWord ExtOp;
18501864
OCLExtOpKind ExtOpOCL;
18511865
SPIRVDebugExtOpKind ExtOpDebug;
1866+
NonSemanticAuxDataOpKind ExtOpNonSemanticAuxData;
18521867
};
18531868
};
18541869

0 commit comments

Comments
 (0)