Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/libSPIRV/SPIRVFnVar.cpp

raw
1 //===- SPIRVFnVar.cpp -===//
2 //
3 // The LLVM/SPIRV Translator
4 //
5 // Copyright (c) 2025 The Khronos Group Inc.
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //===----------------------------------------------------------------------===//
20 /// \file
21 ///
22 /// This file implements functions declared in its header file with the help of
23 /// additional helper functions.
24 ///
25 //===----------------------------------------------------------------------===//
26
27 #include "SPIRVFnVar.h"
28
29 using namespace SPIRV;
30
31 namespace {
32
33 // Replace SPIRV value with OpConstantTrue/False based on a boolean value.
34 void replaceWithBoolConst(SPIRVModule *BM, SPIRVValue *&OldVal, bool Val) {
35 auto *NewVal =
36 Val ? static_cast<SPIRVValue *>(
37 new SPIRVConstantTrue(BM, OldVal->getType(), OldVal->getId()))
38 : static_cast<SPIRVValue *>(
39 new SPIRVConstantFalse(BM, OldVal->getType(), OldVal->getId()));
40 [[maybe_unused]] bool IsSuccess = BM->eraseValue(OldVal);
41 assert(IsSuccess);
42 OldVal = BM->addConstant(NewVal);
43 }
44
45 // Evaluate a constant pointed to by 'Id' and store the result in 'Res'.
46 // Evaluated instruction is replaced with OpConstantTrue/False depending on the
47 // result.
48 //
49 // To keep this simple, only boolean constants and a subset of OpSpecConstantOp
50 // operations are allowed. Support for more can be implemented as necessary.
51 bool evaluateConstant(SPIRVModule *BM, SPIRVId Id, bool &Res,
52 std::string &ErrMsg) {
53 auto *BV = BM->getValue(Id);
54 const Op OpCode = BV->getOpCode();
55
56 assert(isConstantOpCode(OpCode));
57 assert(BV->getType()->getOpCode() == spv::OpTypeBool);
58
59 SPIRVWord SpecId = 0;
60 if (BV->hasDecorate(DecorationSpecId, 0, &SpecId)) {
61 if (OpCode != OpSpecConstantTrue && OpCode != OpSpecConstantFalse &&
62 OpCode != OpSpecConstantArchitectureINTEL &&
63 OpCode != OpSpecConstantTargetINTEL &&
64 OpCode != OpSpecConstantCapabilitiesINTEL) {
65 ErrMsg = "Setting only boolean spec constants is supported";
66 return false;
67 }
68
69 bool IsTrue = OpCode == OpSpecConstantTrue;
70 uint64_t ConstValue = 0;
71 if (BM->getSpecializationConstant(SpecId, ConstValue)) {
72 IsTrue = ConstValue;
73 }
74 Res = IsTrue;
75 replaceWithBoolConst(BM, BV, Res);
76 return true;
77 }
78
79 switch (OpCode) {
80 case OpConstantTrue: {
81 Res = true;
82 break;
83 }
84 case OpConstantFalse: {
85 Res = false;
86 break;
87 }
88 case OpSpecConstantTrue: {
89 Res = true;
90 replaceWithBoolConst(BM, BV, Res);
91 break;
92 }
93 case OpSpecConstantFalse: {
94 Res = false;
95 replaceWithBoolConst(BM, BV, Res);
96 break;
97 }
98 case OpSpecConstantArchitectureINTEL: {
99 Res =
100 static_cast<SPIRVSpecConstantArchitectureINTEL *>(BV)->matchesDevice();
101 replaceWithBoolConst(BM, BV, Res);
102 break;
103 }
104 case OpSpecConstantTargetINTEL: {
105 Res = static_cast<SPIRVSpecConstantTargetINTEL *>(BV)->matchesDevice();
106 replaceWithBoolConst(BM, BV, Res);
107 break;
108 }
109 case OpSpecConstantCapabilitiesINTEL: {
110 Res =
111 static_cast<SPIRVSpecConstantCapabilitiesINTEL *>(BV)->matchesDevice();
112 replaceWithBoolConst(BM, BV, Res);
113 break;
114 }
115 case OpSpecConstantOp: {
116 auto OpWords = static_cast<SPIRVSpecConstantOp *>(BV)->getOpWords();
117 auto OpOpCode = static_cast<Op>(OpWords[0]);
118 if (OpOpCode != OpLogicalOr && OpOpCode != OpLogicalAnd &&
119 OpOpCode != OpLogicalNot) {
120 ErrMsg = "Unsupported operation: Only OpLogicalOr/And/Not are allowed.";
121 return false;
122 }
123
124 bool Val1 = false;
125 if (!evaluateConstant(BM, OpWords[1], Val1, ErrMsg)) {
126 return false;
127 }
128
129 if (OpOpCode == OpLogicalNot) {
130 assert(OpWords.size() == 2);
131 if (OpOpCode == OpLogicalNot) {
132 Res = !Val1;
133 }
134 } else {
135 assert(OpWords.size() == 3);
136 bool Val2 = false;
137 if (!evaluateConstant(BM, OpWords[2], Val2, ErrMsg)) {
138 return false;
139 }
140
141 if (OpOpCode == OpLogicalOr) {
142 Res = Val1 || Val2;
143 } else if (OpOpCode == OpLogicalAnd) {
144 Res = Val1 && Val2;
145 }
146 }
147
148 replaceWithBoolConst(BM, BV, Res);
149 break;
150 }
151 default: {
152 std::ostringstream S;
153 S << "Evaluating unsupported instruction, opcode: " << OpCode;
154 ErrMsg = S.str();
155 return false;
156 }
157 }
158
159 return true;
160 }
161
162 } // anonymous namespace
163
164 namespace SPIRV {
165
166 bool specializeFnVariants(SPIRVModule *BM, std::string &ErrMsg) {
167 // Specialize conditional capabilities
168 std::vector<std::pair<std::pair<SPIRVId, Capability>, bool>> CondCapabilities;
169 for (const auto &CondCap : BM->getConditionalCapabilities()) {
170 const SPIRVId Condition = CondCap.first.first;
171 const Capability Cap = CondCap.first.second;
172 const SPIRVConditionalCapabilityINTEL *Entry = CondCap.second;
173 bool ShouldKeep = false;
174 if (!evaluateConstant(BM, Entry->getCondition(), ShouldKeep, ErrMsg)) {
175 return false;
176 }
177 CondCapabilities.emplace_back(
178 std::make_pair(std::make_pair(Condition, Cap), ShouldKeep));
179 }
180
181 for (const auto &CondCap : CondCapabilities) {
182 const SPIRVId Condition = CondCap.first.first;
183 const Capability Cap = CondCap.first.second;
184 const bool ShouldKeep = CondCap.second;
185 if (ShouldKeep) {
186 BM->addCapability(Cap);
187 } else {
188 // In case the capability was auto-added by other instruction
189 BM->eraseCapability(Cap);
190 }
191 BM->eraseConditionalCapability(Condition, Cap);
192 }
193
194 // Specialize conditional extensions
195 std::vector<std::pair<std::pair<uint32_t, std::string>, bool>> CondExtensions;
196 for (const auto &CondExt : BM->getConditionalExtensions()) {
197 const SPIRVId Cond = CondExt.first;
198 const std::string Ext = CondExt.second;
199 bool ShouldKeep = false;
200 if (!evaluateConstant(BM, Cond, ShouldKeep, ErrMsg)) {
201 return false;
202 }
203 CondExtensions.emplace_back(
204 std::make_pair(std::make_pair(Cond, Ext), ShouldKeep));
205 }
206
207 for (const auto &CondExt : CondExtensions) {
208 const auto Ext = CondExt.first;
209 const bool ShouldKeep = CondExt.second;
210 if (ShouldKeep) {
211 BM->getExtension().insert(Ext.second);
212 } else {
213 // In case the extension was auto-added by other instruction
214 BM->getExtension().erase(Ext.second);
215 }
216 BM->getConditionalExtensions().erase(Ext);
217 }
218
219 // Specialize conditional entry points
220 std::vector<std::pair<SPIRVId, bool>> CondEPs;
221 for (const auto &CondEP : BM->getConditionalEntryPoints()) {
222 const SPIRVId Cond = CondEP->getCondition();
223 bool ShouldKeep = false;
224 if (!evaluateConstant(BM, Cond, ShouldKeep, ErrMsg)) {
225 return false;
226 }
227 CondEPs.emplace_back(std::make_pair(Cond, ShouldKeep));
228 }
229
230 for (const auto &CondEP : CondEPs) {
231 const SPIRVId Cond = CondEP.first;
232 const bool ShouldKeep = CondEP.second;
233 BM->specializeConditionalEntryPoints(Cond, ShouldKeep);
234 }
235
236 // Specialize conditional copy object
237 std::vector<std::pair<SPIRVInstruction *, SPIRVId>> ToReplace;
238 for (unsigned IF = 0; IF < BM->getNumFunctions(); ++IF) {
239 const auto *Fun = BM->getFunction(IF);
240 for (unsigned IB = 0; IB < Fun->getNumBasicBlock(); ++IB) {
241 const auto *BB = Fun->getBasicBlock(IB);
242 for (unsigned II = 0; II < BB->getNumInst(); ++II) {
243 auto *Inst = BB->getInst(II);
244 if (Inst->getOpCode() == OpConditionalCopyObjectINTEL) {
245 const auto OperandIds =
246 static_cast<SPIRVConditionalCopyObjectINTEL *>(Inst)
247 ->getOperandIds();
248 std::optional<unsigned> ITrue = std::nullopt;
249 for (unsigned IO = 0; IO < OperandIds.size(); IO += 2) {
250 const auto CondId = OperandIds[IO];
251 bool Res;
252 if (!evaluateConstant(BM, CondId, Res, ErrMsg)) {
253 return false;
254 }
255 if (Res) {
256 // Stop at the first condition operand that evaluates to true
257 ITrue = IO;
258 break;
259 }
260 }
261 if (!ITrue.has_value()) {
262 ErrMsg = "At least one conditional of OpConditionalCopyObjectINTEL "
263 "must be true. This could mean that all function variants "
264 "have been removed.";
265 return false;
266 }
267 ToReplace.emplace_back(
268 std::make_pair(Inst, OperandIds[ITrue.value() + 1]));
269 }
270 }
271 }
272 }
273
274 for (auto &It : ToReplace) {
275 auto *OldInst = It.first;
276 auto *BB = OldInst->getBasicBlock();
277 auto *NextInst = OldInst->getNext();
278 auto *Operand = BM->getValue(It.second);
279 auto *NewInst =
280 new SPIRVCopyObject(OldInst->getType(), OldInst->getId(), Operand, BB);
281 BM->eraseInstruction(OldInst, BB);
282 BB->addInstruction(NewInst, NextInst);
283 }
284
285 // Specialize IDs annotated with ConditionalINTEL decorations
286 auto *Decors = BM->getDecorateVec();
287 std::vector<SPIRVId> IdsToRemove;
288 for (const auto &D : *Decors) {
289 if (D->getDecorateKind() == DecorationConditionalINTEL) {
290 const SPIRVId ConstId = static_cast<SPIRVWord>(D->getLiteral(0));
291 bool ShouldKeep = false;
292 if (!evaluateConstant(BM, ConstId, ShouldKeep, ErrMsg)) {
293 return false;
294 }
295 if (!ShouldKeep) {
296 IdsToRemove.push_back(D->getTargetId());
297 }
298 }
299 }
300
301 for (const auto &Id : IdsToRemove) {
302 if (!BM->eraseReferencesOfInst(Id)) {
303 ErrMsg = "Error removing references of instruction decorated with "
304 "ConditionalINTEL";
305 return false;
306 }
307 auto *Val = BM->getValue(Id);
308 if (Val->getOpCode() == OpFunctionCall) {
309 auto *Call = static_cast<SPIRVFunctionCall *>(Val);
310 auto *BB = Call->getBasicBlock();
311 BM->eraseInstruction(Call, BB);
312 } else if (Val->getOpCode() == OpFunction) {
313 const auto *Fun = static_cast<const SPIRVFunction *>(Val);
314 for (unsigned I = 0; I < Fun->getNumArguments(); ++I) {
315 const auto ArgId = Fun->getArgumentId(I);
316 if (!BM->eraseReferencesOfInst(ArgId)) {
317 ErrMsg = "Error erasing references of argument of a function "
318 "annotated with ConditionalINTEL";
319 return false;
320 }
321 }
322 for (const auto &VarId : Fun->getVariables()) {
323 if (!BM->eraseReferencesOfInst(VarId)) {
324 ErrMsg = "Error erasing references of variable within function "
325 "annotated with ConditionalINTEL";
326 return false;
327 }
328 }
329 for (unsigned IB = 0; IB < Fun->getNumBasicBlock(); ++IB) {
330 const auto *const BB = Fun->getBasicBlock(IB);
331 for (unsigned II = 0; II < BB->getNumInst(); ++II) {
332 const auto *const Inst = BB->getInst(II);
333 if (Inst->hasId()) {
334 const auto InstId = Inst->getId();
335 if (!BM->eraseReferencesOfInst(InstId)) {
336 ErrMsg = "Error erasing references of instruction within "
337 "function annotated with ConditionalINTEL";
338 return false;
339 }
340 }
341 }
342 if (!BM->eraseReferencesOfInst(BB->getId())) {
343 ErrMsg = "Error erasing references of basic block label within "
344 "function annotated with ConditionalINTEL";
345 return false;
346 }
347 }
348 erase_if(*BM->getFuncVec(), [Id](auto F) { return F->getId() == Id; });
349 } else if (Val->getOpCode() == OpVariable ||
350 isTypeOpCode(Val->getOpCode()) ||
351 Val->getOpCode() == OpExtInstImport ||
352 isConstantOpCode(Val->getOpCode()) ||
353 Val->getOpCode() == OpAsmINTEL ||
354 Val->getOpCode() == OpAsmTargetINTEL) {
355 if (!BM->eraseValue(Val)) {
356 ErrMsg = "Error erasing value annotated with ConditionalINTEL";
357 return false;
358 }
359 } else {
360 ErrMsg = "Unsupported instruction annotated with ConditionalINTEL";
361 return false;
362 }
363 }
364
365 // Remove any leftover ConditionalINTEL decorations
366 erase_if(*Decors, [](auto D) {
367 return D->getDecorateKind() == DecorationConditionalINTEL;
368 });
369
370 // Remove capabilities/extensions of SPV_INTEL_function_variants
371 BM->eraseCapability(CapabilityFunctionVariantsINTEL);
372 BM->eraseCapability(CapabilitySpecConditionalINTEL);
373 BM->getExtension().erase("SPV_INTEL_function_variants");
374
375 return true;
376 }
377
378 } // namespace SPIRV