Skip to content

Commit 5ffcd16

Browse files
sarnexagainull
authored andcommitted
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]> Original commit: KhronosGroup/SPIRV-LLVM-Translator@f729c49
1 parent feb18a4 commit 5ffcd16

File tree

16 files changed

+339
-6
lines changed

16 files changed

+339
-6
lines changed

llvm-spirv/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

llvm-spirv/lib/SPIRV/SPIRVReader.cpp

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

33593359
DbgTran->addDbgInfoVersion();
33603360
DbgTran->finalize();
3361+
3362+
for (SPIRVExtInst *EI : BM->getAuxDataInstVec()) {
3363+
transAuxDataInst(EI);
3364+
}
3365+
33613366
return true;
33623367
}
33633368

@@ -4500,6 +4505,60 @@ Instruction *SPIRVToLLVM::transOCLBuiltinFromExtInst(SPIRVExtInst *BC,
45004505
return CI;
45014506
}
45024507

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

llvm-spirv/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);

llvm-spirv/lib/SPIRV/SPIRVWriter.cpp

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

971971
transFunctionMetadataAsUserSemanticDecoration(BF, F);
972972

973+
transAuxDataInst(BF, F);
974+
973975
SPIRVDBG(dbgs() << "[transFunction] " << *F << " => ";
974976
spvdbgs() << *BF << '\n';)
975977
return BF;
@@ -1137,6 +1139,72 @@ void LLVMToSPIRVBase::transFunctionMetadataAsUserSemanticDecoration(
11371139
}
11381140
}
11391141

1142+
void LLVMToSPIRVBase::transAuxDataInst(SPIRVFunction *BF, Function *F) {
1143+
auto *BM = BF->getModule();
1144+
if (!BM->preserveAuxData())
1145+
return;
1146+
BM->addExtension(SPIRV::ExtensionID::SPV_KHR_non_semantic_info);
1147+
const auto &FnAttrs = F->getAttributes().getFnAttrs();
1148+
for (const auto &Attr : FnAttrs) {
1149+
std::vector<SPIRVWord> Ops;
1150+
Ops.push_back(BF->getId());
1151+
if (Attr.isStringAttribute()) {
1152+
// Format for String attributes is:
1153+
// NonSemanticAuxDataFunctionAttribute Fcn AttrName AttrValue
1154+
// or, if no value:
1155+
// NonSemanticAuxDataFunctionAttribute Fcn AttrName
1156+
//
1157+
// AttrName and AttrValue are always Strings
1158+
StringRef AttrKind = Attr.getKindAsString();
1159+
StringRef AttrValue = Attr.getValueAsString();
1160+
auto *KindSpvString = BM->getString(AttrKind.str());
1161+
Ops.push_back(KindSpvString->getId());
1162+
if (!AttrValue.empty()) {
1163+
auto *ValueSpvString = BM->getString(AttrValue.str());
1164+
Ops.push_back(ValueSpvString->getId());
1165+
}
1166+
} else {
1167+
// Format for other types is:
1168+
// NonSemanticAuxDataFunctionAttribute Fcn AttrStr
1169+
// AttrStr is always a String.
1170+
std::string AttrStr = Attr.getAsString();
1171+
auto *AttrSpvString = BM->getString(AttrStr);
1172+
Ops.push_back(AttrSpvString->getId());
1173+
}
1174+
BM->addAuxData(NonSemanticAuxData::FunctionAttribute,
1175+
transType(Type::getVoidTy(F->getContext())), Ops);
1176+
}
1177+
SmallVector<std::pair<unsigned, MDNode *>> AllMD;
1178+
SmallVector<StringRef> MDNames;
1179+
F->getContext().getMDKindNames(MDNames);
1180+
F->getAllMetadata(AllMD);
1181+
for (auto MD : AllMD) {
1182+
// Format for metadata is:
1183+
// NonSemanticAuxDataFunctionMetadata Fcn MDName MDVals...
1184+
// MDName is always a String, MDVals have different types as explained
1185+
// below. Also note this instruction has a variable number of operands
1186+
std::vector<SPIRVWord> Ops;
1187+
Ops.push_back(BF->getId());
1188+
Ops.push_back(BM->getString(MDNames[MD.first].str())->getId());
1189+
for (unsigned int OpIdx = 0; OpIdx < MD.second->getNumOperands(); OpIdx++) {
1190+
const auto &CurOp = MD.second->getOperand(OpIdx);
1191+
if (auto *MDStr = dyn_cast<MDString>(CurOp)) {
1192+
// For MDString, MDVal is String
1193+
auto *SPIRVStr = BM->getString(MDStr->getString().str());
1194+
Ops.push_back(SPIRVStr->getId());
1195+
} else if (auto *ValueAsMeta = dyn_cast<ValueAsMetadata>(CurOp)) {
1196+
// For Value metadata, MDVal is a SPIRVValue
1197+
auto *SPIRVVal = transValue(ValueAsMeta->getValue(), nullptr);
1198+
Ops.push_back(SPIRVVal->getId());
1199+
} else {
1200+
assert(false && "Unsupported metadata type");
1201+
}
1202+
}
1203+
BM->addAuxData(NonSemanticAuxData::FunctionMetadata,
1204+
transType(Type::getVoidTy(F->getContext())), Ops);
1205+
}
1206+
}
1207+
11401208
SPIRVValue *LLVMToSPIRVBase::transConstantUse(Constant *C) {
11411209
// Constant expressions expect their pointer types to be i8* in opaque pointer
11421210
// mode, but the value may have a different "natural" type. If that is the
@@ -2828,6 +2896,11 @@ bool LLVMToSPIRVBase::transBuiltinSet() {
28282896
SPIRVBuiltinSetNameMap::map(BM->getDebugInfoEIS()), &EISId))
28292897
return false;
28302898
}
2899+
if (BM->preserveAuxData()) {
2900+
if (!BM->importBuiltinSet(
2901+
SPIRVBuiltinSetNameMap::map(SPIRVEIS_NonSemantic_AuxData), &EISId))
2902+
return false;
2903+
}
28312904
return true;
28322905
}
28332906

llvm-spirv/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

llvm-spirv/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

llvm-spirv/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

llvm-spirv/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)